Secure PHP image uploader? Where is an accepted solid solution?

Question: Relative newb here. I'm not a great programmer my self, but am not too bad in finding the chunks of code, from those far cleverer than me are generous enough to share.
However, in all my hunting around, I'm yet to find a secure PHP image uploader which seems to be accepted by the web community as doing a fairly solid job.
I was wondering what people thought of this https://github.com/dimo414/imgupload
Otherwise, through all the security issues and discussions, does anybody know about any resource which I can take and adapt for the purposes of uploading a single image?
Answer: That will work fine, but remember that this is nothing special, it's just standard PHP functionality to create it.
You could use this to get the job done quickly, but if you are using it in a specific solution then you might want to tweak it for your own needs.
This could be to make it work via ajax or something else perhaps?
Comment: +1, agreed. The code just helps refine what PHP already does.
Comment: I'm not too concerned about the beauty of it, and I don't mind tweaking it a little. My main concern is security since I intend to use it on a site which will be handling payments also, i.e. vulnerability to hacking/data theft is to be avoided at all costs.

Thanks for your quick responses BTW.
Answer: This isn't exactly a question suited for StackOverflow since it is less about the code you've tried and more about a subjective question of security. The code you've pointed to is good as long as you understand what it secures you from and what it doesn't. It enforces a max upload size and checks that the upload is the right type, but keep in mind that PHP is already doing some of this. The code in question just packages it up in a way that is easier to use.
This code will stop someone from uploading anything other than images and that's probably the most important part.


vispy visual.HistogramVisual

Question: Going off of the examples/basics/visuals/graphy.py, I tried to display a histogram but failed:
from vispy import app, visuals
import wx
import numpy as np

class snrHistogram(app.Canvas):
    def __init__(self, *args, **kwargs):
        app.Canvas.__init__(self, title='histogram fail',
                            keys="interactive", size=(600, 600))

        self.snr_hist = visuals.HistogramVisual(np.arange(256), bins=4, color='r', orientation='v')
        self.label = visuals.TextVisual("hi", color='blue', pos=[50, 50, 0])
        self.configure_transforms()
        self.show()

    def configure_transforms(self):
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)
        self.label.transforms.configure(canvas=self, viewport=vp)
        self.snr_hist.transforms.configure(canvas=self, viewport=vp)

    def on_resize(self, event):
        self.configure_transforms()

    def on_mouse_wheel(self, event):
        self.update()

    def on_draw(self, event):
        self.snr_hist.draw()
        self.label.draw()
        self.update()

    def on_close(self, event):
        self.close()

if __name__ == '__main__':
    s = snrHistogram()
    app.run()

and yet the text visual works just fine. I understand histogramVisual is a subclass of mesh, but I didn't see anything useful in the source code of mesh.py. I am using wx as my backend.
Answer: The histogram was appearing, but very small. The following input data will coerce the program to display a histogram:
self.snr_hist = visuals.HistogramVisual(
    np.repeat([0, 1, 1, 20, 20, 40, 40, 80, 80, 90, 81, 70, 65],
    100), bins=4, color='r', orientation='h')

vispy visual.HistogramVisual


data.table from long colum to list by grup

Question: I am trying to "paste" all values by group into a list. Something similar to what paste(x, collapse="-") does, but the output should be a list. I managed to do this into two steps. Can it be done in one step?
library("data.table")

d <- data.table( sample(letters, 100, replace = T), sample(LETTERS,100, replace = T)) %>%    unique

d[, paste0(V2, collapse = "--"), by=V1] %>% head
    V1               V1
1:  m       E--T--L--Q
2:  k    J--H--W--P--X
3:  v          D--W--X
4:  g          H--E--I
5:  c K--U--X--H--Y--N
6:  l    O--H--J--R--U

dd <- split(d, by="V1", keep.by=FALSE)
data.table(names(dd), sapply(dd, "[") ) %>% head
   V1          V2
1:  m     E,T,L,Q
2:  k   J,H,W,P,X
3:  v       D,W,X
4:  g       H,E,I
5:  c K,U,X,H,Y,N
6:  l   O,H,J,R,U

I tried with shift as well, with no sucess R data.table create list column by group
Answer: We can wrap it in a list
dd <- d[, .(V2 = list(V2)), V1]
head(dd)
#   V1              V2
#1:  c     Z,W,K,G,Q,A
#2:  a       V,X,T,D,K
#3:  w           Z,I,N
#4:  u N,Y,H,U,M,Z,...
#5:  d         G,M,D,B
#6:  q O,Z,K,V,I,X,...

str(dd)
#Classes 'data.table' and 'data.frame': 25 obs. of  2 variables:
# $ V1: chr  "c" "a" "w" "u" ...
# $ V2:List of 25
#  ..$ : chr  "Z" "W" "K" "G" ...
#  ..$ : chr  "V" "X" "T" "D" ...
#  ..$ : chr  "Z" "I" "N"
#  ..$ : chr  "N" "Y" "H" "U" ...
#  ..$ : chr  "G" "M" "D" "B"
# ..

Comment: sorry for the imprecise description, it should be a list containing a vector of strings, not a list containing one string.
Comment: now I realized why this was not working when I first tried. The original intention was to modify the table by reference, so that each entry will have a list. Can this be achieved without merging in a second step?


How to submit form using JQuery and Spring Controller

Question: I am having difficulty understanding why my form submits successful when i disable the ajax function. When i enable ajax on my input form. Input values i fill are not submitted. I used chrome developer tools to check the FormData being submitted. I realized nothing was being submit.
Hence i get an error asking me to fill those fields.
Controller
    @PostMapping(value = "/basicAjax.json")
    @ResponseBody
    public ResponseEntity<Object> addCertJson(@Valid @ModelAttribute CertificateProgramme certificate, BindingResult result, Principal principal) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        certificate.setUser(user);
        if (result.hasErrors()) {
            List<String> errors = result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
        } else {
            certificateService.save(certificate);
            return new ResponseEntity<>(HttpStatus.ACCEPTED);
        }
    }

JS Script
var $form = $('.editCert');
var formData = $form.serialize();
var url = $form.attr('action');
var storage = {};
$.each($('.editCert').serializeArray(), function(i, field) {
    storage[field.name] = field.value;
});

$form.on('submit',function(e){
    e.preventDefault();
    $.ajax(url,{
            dataType: 'JSON',
            data: storage,
            type: "POST",
        }).done(function(response){
           if(response.status === 'SUCCESS'){
                 console.log('I am Okay' + response);
                  }else{
                  console.log('Holly Molly');
                   }
        }).fail(function(jqXHR, textStatus, errorThrown){
          var errorInfo="";
          for(i =0 ; i <jqXHR.responseJSON.length ; i++){
                           errorInfo += "
" + (i + 1) +". " + jqXHR.responseJSON[i];
                       }
                    var $myerror =  $form.find('.flash').addClass(' failure');
                        $myerror.html("Please correct following errors: " + errorInfo);
           });
    });

Form
<form  method="post" th:object="${certificate}"
      th:action="@{${action1}}" class="form-inline inline new-item editCert">
    <input type="hidden" th:field="*{id}"/>

    <fieldset>
        <legend th:text="${heading}"> Personal Information</legend>

            <input type="text" class="form-control input-sm" th:field="*{fullName}"
                   placeholder="Full Name example Jane Doe"/>

            <select th:field="*{gender}" class="form-control input-lg ">
                <option value="">[Select Gender]</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select>

            <input th:type="date" data-value="20/04/2015" class="form-control input-sm datepicker" th:field="*{date}"
                   placeholder="Date Of Birth"/>

Comment: When you enable ajax, form data is probably sent in json format. When you disable ajax, the data is sent in formdata format, you should adapt your controller to your need. In your Jquery, it seems like you are stopping the submit using  e.preventDefault();, and sending the data as AJAX, why would you do that?
Comment: @zakariaamine I am preventing the default function because, i am loading that form into a div. Hence i can use the jQuery $.post or $,Jquery functionality to submit the form async. If i don't do that i wouldn't  get the functionality i want. In any case that is not why the form is not submitting to the controller
Answer: Solved my problem, Moved the form iteration into the submit $.ajax submit function
$form.on('submit',function(e){
    e.preventDefault();
    $.each($(this).serializeArray(), function(i, field) {
        storage[field.name] = field.value;
    });
   console.log(storage);
    $.ajax(url,{
            //dataType: 'json',
            data: storage,
            type: "POST",
        }).done(function(response){
                 console.log('I am Okay' + response);
        }).fail(function(jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
          if(jqXHR.status === 400){
          var errorInfo="";
          for(i =0 ; i <jqXHR.responseJSON.length ; i++){
                           errorInfo += "
" + (i + 1) +". " + jqXHR.responseJSON[i];
                       }
                    var $myerror =  $form.find('.flash').addClass(' failure');
                        $myerror.html("Please correct following errors: " + errorInfo);
            }
           });
    });


timedelta returning wrong month

Question: I wrote some code to send requests to an API. The API allows the search to be performed between a given set of dates. My code takes a datetime object and increases that object by a timedelta, lets call this timedelta d. I have a second datetime object which increments the by d-1. The idea is to get non overlapping time periods. Everything seems to be working fine except that when the date changes from November the first back to October 31st, the month returned by my date time is incorrect. Here is the code:
start_date=datetime(2013,9,22)
end_date=datetime(2013,12,1)

d = start_date
delta = timedelta(days=10)

while d <= end_date:
    ys=d.strftime('%Y')
    ms=d.strftime('%m')
    ds=d.strftime('%d')
    d += delta

    ye=d.strftime('%Y')
    me=d.strftime('%m')
    de=(d-timedelta(days=1)).strftime('%d')
    print ys+'-'+ms+'-'+ds+'..'+ye+'-'+me+'-'+de

And here is the output:2013-09-22..2013-10-01
2013-10-02..2013-10-11
2013-10-12..2013-10-21
2013-10-22..2013-11-31 #the second date printed should be 2013-10-31
2013-11-01..2013-11-10
2013-11-11..2013-11-20
2013-11-21..2013-12-30
2013-12-01..2013-12-10

Any idea on why this is happening?
Comment: you are calculating the month for the first day of the next section but the day by subtracting one. try using `final_day = d-timedelta(days=1) ; ye=final_day.strftime("%Y")... `etc.
Comment: Try using the *freeze_gun* library for unit testing so you can debug. Allows you to easily mock the current date/time
Comment: Yes, you are right I see my error now, after I subtract a day the whole time object change, but the month and year previously defined as string do not.
Answer: after you have executed:
d += delta

then d represents the start date of the next interval, in one case in your data that is 2013-11-01 so when you get the year and month of that data you get 2013-11 and then get the date of one day before which is 2013-10-31 so it gets 31 instead get all three fields from one day before:
end_interval=d-timedelta(days=1)
ye = end_interval.strftime('%Y')
me=end_interval.strftime('%m')
de=(end_interval).strftime('%d')
print(ys+'-'+ms+'-'+ds+'..'+ye+'-'+me+'-'+de)

or much more concisely you can use strftime('%Y-%m-%d') to get all three fields at once.
start_str = d.strftime("%Y-%m-%d")
d += delta

end_str = (d-timedelta(days=1)).strftime("%Y-%m-%d")
print(start_str+'..'+end_str)

or even more concisely then that:
start_date=datetime(2013,9,22)
end_date=datetime(2013,12,1)

d = start_date
delta = timedelta(days=10)

interval = delta - timedelta(days=1) #the difference between the start of an interval and the last day

while d <= end_date:
    end = d+interval #last day of interval
    print("{:%Y-%m-%d}...{:%Y-%m-%d}".format(d, end))
    d = end + timedelta(days=1) #set d to one day more then the end of interval

Answer: Try to use d-timedelta(days=1) on all the ye, me and de, not only de

timedelta returning wrong month


Shader to combine two sprites

Question: I have two sprites that I need to combine into one. I have a shader using Shaderlab syntax which works well for normal textures, but SpireRenderer gives warnings about it being a Fixed function shader plus it does not work with the Sprite Packer.
This is my goal:

So there is a base sprite which is used for the background and the image sprite which gives the card its final look. With ShaderLab I could just use "Combine Texture" to do this, but I have no idea how or if it is possible to do with CG.
Comment: @user1610743 Yes it should be done on the framebuffer. Doing texture combining in the initialization cranks the up the load time too much.
Comment: When does this process happen ? Can it be done on initialization or does it need to happen on the framebuffer ?
Comment: Thing is, doing something 1x during initialization is far superior to doing something over and over with each frame. This is especially true if you need to do the combination multiple times within each frame. I can't post some code for you, as I'm not sure why it would be bad to render the combination one time into a framebuffer, copy that to a texture buffer (intra GPU) and later use that texture as the pre-processed combination. Also, i'm not familiar with Unity3D that much. It would really save u some performance for ur later game-loop.
Answer: The blending could work something like this:
fixed4 bg = tex2D(_BackgroundSprite, IN.uv);
fixed4 fg = tex2D(_ForegroundSprite, IN.uv);

fixed3 col = fixed3(fg.rgb * fg.a + bg.rgb * bg.a * (1 - fg.a));
return fixed4(col, fg.a + fg.b * (1 - fg.a));

Shader to combine two sprites


jquery to update viewport?

Question: I am trouble shooting a layout issue I am having and was hoping to get some insight.
I have, on the left, a menu panel that opens and collapses and on the right I have Galleria which is set to responsive mode which means it resizes if the window size is changed.
The goal I am setting out to achieve is that when my menu panel collapses I want the responsive Galleria to resize and vice-a-versa.
right now, if the panel begins in the collapsed position and is expanded, the document width increases by the width of the menu panel and the Galleria is not resized. From here if I manually resize my browser even a single pixel the layout refreshes and all is good.
So I began looking for ways I could update the viewport, without actually changing the size just so the Galleria reacts as if the viewport changed. The below is my code for toggling my menu. I am at the point of trying to force the document size to the original size but even this fails to produce result.
Thanks for the help
var documentWidth = $(document).width();
    var documentHeight = $(document).height();
    function hideMenu() {
        $('#User_Menu').hide("slide", { direction: "left" }, 1000, function () {
            showOpenMenu();
            $.cookie('pj-userMenuTab', 'block')
            $(document).width(documentWidth);
        });
    }
    function showOpenMenu() {
        $('#Open_User_Menu').show("slide", { direction: "left" }, 500);
        $.cookie('pj-userMenu', 'none')
    }
    function showMenu() {
        $('#Open_User_Menu').hide("slide", { direction: "left" }, 500, function () {
            hideOpenMenu();
            $.cookie('pj-userMenu', 'block');
        });
    }
    function hideOpenMenu() {
        $('#User_Menu').show("slide", { direction: "left" }, 1000);
        $.cookie('pj-userMenuTab', 'none')
        alert('...' + documentWidth);
        $(document).width(documentWidth);
        alert($(document).width());
    }

Comment: If so, then try adding a `$(window).trigger("resize")` to your open/close functions.
Comment: It seems like something is changing on the `resize` event (of `window`).
Comment: yes I think the Galleria plugin is using that. I was hoping to create a viewport update in order to trigger that event
Comment: Thanks. I actually was just looking through the galleria js and saw that exact function so I gave it a show and it worked.
Comment: I have posted that as an answer, since it fixed your problem.
Answer: Per the comments, what was necessary was to trigger the resize event so the Galleria plugin will resize.
The following code (when added to the open/close functions) should work:
$(window).trigger("resize");

jquery to update viewport?


Convergent Series in a dual space

Question: I don't know how solve this problem.
Please I need help.

Let $X  =\mathcal{C}[0,1]$ with the uniform norm and let
  $\{p_j\}_{j\in\mathbb{N}}$, $\{q_j\}_{j\in\mathbb{N}}\subseteq X$ such
  that the series $\sum\limits_{j=1}^{\infty}p_j(s)q_j(t)$ uniformly
  converge to a continuous function $K:[0,1]\times [0,1]\rightarrow
> \mathbb{R}$, i.e., $$\lim_{N\rightarrow +\infty}\left\{\max_{(s,t)\in [0,1]\times [0,1]}\left|K(s,t) - \sum_{j=1}^Np_j(s)q_j(t)\right|\right\}\ =\ 0.$$ Besides, let $F_j\in
 X^{\prime}$ defined by $F_j(u) := \int_0^1q_j(t)u(t)dt$, $\forall\
 u\in X$. Show that, for all $G\in X^{\prime}$, the series
  $\sum\limits_{j=1}^{\infty}G(p_j)F_j$ is convergent in $X^{\prime}$.
  Identify the limit value, in terms of the adjoint of a convenient
  operator.

Thanks in advance.
Comment: Maybe I am not a mortal, because I denote $X^{\prime}$ as the dual of $X$ too.
Comment: Is $\,X'\,$ the dual space of $\,X\,$, what we mortals usually denote as $\,X^*\,$ ?
Comment: Yes, $X^{\prime}$ is the dual of $X$.
Answer: For the first question, notice that for a fixed $u\in X$, we have
$$\sum_{j=1}^NG(p_j)F_j(u)=\sum_{j=1}^NG((F_j(u))\cdot p_j)=G\left(\sum_{j=1}^NF_j(u)p_j\right),$$
hence given integers $M$ and $N$, we get
$$\left|\sum_{j=M}^{M+N}G(p_j)F_j(u)\right|\leqslant \lVert G\rVert\cdot\max_x\left\lvert\sum_{j=M}^{M+N}p_j(x)\int_0^1q_j(t)dt\rvert\right|.$$
Recall that a dual space is complete.

Convergent Series in a dual space


Sometimes I cannot spawn on my teammates on Hardcore

Question: The other day I was playing Operation Locker Conquest in Hardcore mode on PS3 and for some reason I could not spawn from SOME of my teammates. I vividly remember spawning on a teammate but not the other two. Is this a Hardcore thing?
Answer: Servers can choose to disable spawning on squad mates, and only allow spawning on your squad leader. If you are the squad leader, you cannot spawn at a team mate.
You can use this filter to find servers that use this feature:
Comment: I think that if you are a squad leader, you CAN spawn on ANY squad member
Comment: @novarg now that you mention it, I'm not sure. Need to check it.


How to submit a form using the Enter key in asp.net

Question: I have 3 buttons in a form. One of them is the submit button. How can I make it the default button to be clicked when I press the enter key. Is there a property for this?
Answer: There is a property for the form: defaultbutton.
<form runat="server" defaultbutton="myButton">
...
</form>

It is first time implemented in ASP.NET 2.0.
Answer: Another helpful tip is that you can set the default button on asp:panel's too.
Comment: Thank you. Thank you. Thank you. It's been a horrific morning of debugging and now I'd like to have your children!
Answer: Or you can do it in code - Page_load:
Page.Form.DefaultButton = btnSearch.UniqueID;

Whenever you press enter the btnSearch control will be used as default.


How to convert one-hot vector to label index and back in Pytorch?

Question: How to transform vectors of labels to one-hot encoding and back in Pytorch?
The solution to the question was copied to here after having to go through the entire forum discussion, instead of just finding an easy one from googling.
Comment: I don't really see the point of creating a thread to copy-paste a solution from another forum.
Comment: @Ivan https://meta.stackoverflow.com/a/347922/913098
Comment: The point is to allow Google searchability. Searching through forums is a waste of time for everyone.
Answer: From the Pytorch forums
<code>import torch
import numpy as np

labels = torch.randint(0, 10, (10,))

# labels --> one-hot
one_hot = torch.nn.functional.one_hot(labels)
# one-hot --> labels
labels_again = torch.argmax(one_hot, dim=1)

np.testing.assert_equals(labels.numpy(), labels_again.numpy())
</code>
Comment: Notice [this answer](https://stackoverflow.com/a/74784150/913098) for cases where you have to specify the number of classes [which is most of the time]
Answer: Since I can't comment on the accepted answer, I just wanted to add that if your target does not include all classes (e.g. because you train in batches), you can specify the number of classes as argument:
<code># labels --> one-hot
one_hot = torch.nn.functional.one_hot(target, num_classes=7)
</code>
Comment: You now have sufficient reputation to comment. I suggest you do this.


python regex relace for wildcard

Question: I am trying to apply regex on python for following code.
Country_name = "usa_t1_usq_t1_[0-9]*.csv"
new_result = re.sub(r'(?:_[[0-9-]+].*[a-zA-Z])+', '', Country_name)

# Display the Content
print(new_result)

The problem here is its working for above input, but not working for input without [0-9] pattern (3rd input in below example).
for example:
input - usa_t1_usq_t1_[0-9]*.csv  Expected output - usa_t1_usq_t1
input - usa_t1_usq_t1_[0-9]*.gzip.csv  Expected output - usa_t1_usq_t1
input - usa_t1_usq_t1.gzip.csv  Expected output - usa_t1_usq_t1
can someone help me to make proper regex for the above scenario as I am new to regex world ?
Comment: why don't you just split on last underscore? `Country_name.rsplit('_', 1)[0]`?
Comment: will it satisfy third example ?
Comment: Are `[0-9]*` wildcards or plain chars in filenames?
Comment: its wildcard characters
Comment: @BigD oh i didn't see that example, i thought all will follow same pattern
Comment: [regex101](https://regex101.com/) is a great site showing how the regex works. Have fun!
Answer: IIUC,
inputs = ['usa_t1_usq_t1_[0-9]*.csv', 'usa_t1_usq_t1_[0-9]*.gzip.csv', 'usa_t1_usq_t1.gzip.csv']
for Country_name in inputs:
    result = re.sub('(_\[0\-9\]\*)?(\.[a-zA-Z]+)+', '', Country_name)
    print(result)
# usa_t1_usq_t1
# usa_t1_usq_t1
# usa_t1_usq_t1

(_\[0\-9\]\*) matches the plain string _[0-9]* in Country_name, and ? after this means it appears zero or one times.
(\.[a-zA-Z]+) matches the suffix starting with ., and another + means it may appear more than once.
Comment: This will not satisfy  input -  usa_t1_usq_t1_[0-9]*.csv. Sorry its wildcard for me, however we need to consider its as plain chars
Comment: You said `[0-9]*` is not plain chars.
Comment: my bad - Sorry its wildcard for me, however we need to consider its as plain chars
Comment: Ok. If it is a plain string, use `(_\[0\-9\]\*)*(\.[a-zA-Z]+)+`.

python regex relace for wildcard


Android Parallax Image

Question: I would like to create an animation in one of my activities that, when a button is clicked, the background "moves" to the next section of an image. A very good example of this is how Expedia Android app does this for creating a user. When create an expedia account is selected, the background animates to another section of the background image.
Any help on how to approach this problem would be greatly appreciated!
Answer: This can be done extending viewPager. Take a look at some of the github libraries for demo :
https://github.com/prolificinteractive/ParallaxPager
https://github.com/xgc1986/ParallaxPagerTransformer
https://github.com/MatthieuLJ/ViewPagerParallax
https://github.com/garrapeta/ParallaxViewPager
https://github.com/andraskindler/parallaxviewpager
Comment: Trying out solutions, will respond soon
Answer: I have had some success using this library:
https://github.com/andraskindler/parallaxviewpager
Instead of changing the background when scrolling, I make it change when a button is clicked.

Android Parallax Image


Question on relative warp resistance of engineered wood

Question: I aim to place, unsecured, (though blocked from movement on 3 sides) a piece of sheet/engineered wood on top of the side rails of a single bed frame. The siderails are 2 cm wide and will be acting as if beams supporting a subfloor.
The horizontal space between the siderails is approx 92cm and the length is approx 191cm.
My understanding is I will be outwidth the max recommended spar/beam distance for a subfloor where I have seen a rough max of 60cm for a sheet of mdf at 22mm thick.
Can anyone recommend the best type of engineered wood for this please?
IE
•   particle board/chipboard
•   mdf
•   plywood (softwood)
•   plywood (hardwood)
And possibly a thickness though I guess the thickest would be best?
Looks not important, I just want the type of engineered wood that is least likely to warp.
Thanks
G
Comment: Is this going to sit inside the rails like a mattress and therefore be exactly 92cm x 191cm? Or is it really on top and if so how much larger than 92 x 191?
Answer: You will want plywood for the application that you desire. The 92cm (36.22 inches) width demands a thick plywood to prevent flexing and warping. Good quality plywood that is 20mm (0.75 inches) thick should be adequate for that width just a small amount of flex.
As a point of reference in the past I had built a platform bed for a daughter that used a 22mm (0.75 inch) thick fir plywood base that was supported along the two long edges very similar to what you are proposing. That plywood was 99cm (38 inches) wide and it was plenty sturdy enough. As a matter of fact to make that platform bed easier to easier to transport and assemble that base plywood was cut in two separate pieces instead of the full length of the bed frame.
Comment: Thanks for that Michael. Is it the case that you reckon the plywood can be softwood for this application and there is no issue with it having to be a hardwood?
Comment: @user89970 - I had used fir plywood in the case of the platform bed. I guess you could call that soft wood. I did use a higher quality style plywood that had more layers than the typical construction grade plywood.


Run an UIActivityIndicatorView while the main thread is busy

Question: is there a way to display the animated spinning wheel while the main thread does a lengthy operation? The animation is handled by the same thread that created the UIActivityIndicatorView, right? If so, can views that belong to several threads sit in the same view hierarchy?
All else failing, I don't mind moving a lengthy operation itself into a background thread, but then I'd have to freeze the UI somehow while it's running. That I'm not sure how to do.
EDIT: "lengthy" is around 2 sec on a 1st-gen device.
Answer: The solution is to start the animation at least one iteration through the run loop before running the lengthy operation.  For example:
[activity startAnimating];
[self performSelector:@selector(lengthyOperation) withObject:nil afterDelay:0];

You don't have to use the performSelector method, just some way to set the method to run later so the activity indicator has a chance to start animating before you get busy.
Comment: @Seva Running lengthy operations on the main thread is generally a bad idea.
Comment: Heck, I was close :) Tried performSelectorOnMainThread, but it seems like delay was the key.
Comment: What Giao says is true.  However, if you need the application to pause while it's happening, it doesn't seem like a TERRIBLE idea.  A better solution, however, might be to use [[UIApplication sharedApplication] beginIgnoringInteractionEvents] and endIgnoringInteractionEvents when you're done.
Comment: I have to agree with Giao; the main thread/run loop should *never* be stalled--the OS will terminate an application that has its main thread stalled for too long.
Comment: yes but isn't it the case that the main thread isn't being 'stalled' here? the main thread is running a lengthy operation which isn't the same as being stalled (or am i mistaken?). @ed Marty does this force the UIActivityIndicator onto a background thread (i read somewhere that the OS forces the activity indicator onto the main thread no matter what you specify - which, I presume was the original problem here...).
Comment: "the main thread/run loop should never be stalled": what about core data -- if I have a long running query that returns thousands of objects, it may take a couple seconds.  And, from what I understand, if I want to use the core data objects on the main thread I have to run the query on the main thread.  This seems to be the solution I was looking for.
Answer: The right answer is definitely to move the lengthly operation to a background thread and have it communicate to the main thread when it's done.  If you don't know how to do this, read on NSOperationQueue and NSInvocationOperation.  Your app and your users will thank you for the minimal time it will take to learn.


Is there a date function by which i can extract days and then substract them from the current date?

Question: /** @OnlyCurrentDoc */
function myFunction() {

    var app = SpreadsheetApp
    var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

    for (var i = 2; i < 10; i++) {

        var workingcell = activeSheet.getRange(i, 1).getDisplayValue();
        var workingcell2 = activeSheet.getRange(i, 7).getDisplayValue();
        if (workingcell == 'TRUE' & workingcell2 == 'Partner Care::Complaint::Payments Issue::Fraud Deduction')

        {

            activeSheet.getRange(i, 2).setValue("Incorrect Data");

        }
    }

    for (var j = 2; j < 10; j++) {
        var workingcell3 = activeSheet.getRange(j, 1).getValue();
        var todayDate = new Date();

        if (todayDate.getDay() - workingcell3.getDay() > 30) {
            activeSheet.getRange(j, 8).setValue(">30 Days");

        }
    }

}

This code is compiled but it does not serve the objectives which are as follows:

To check if the range of cells in A contain the word "TRUE". If yes then mark -- "Incorrect Data"
To check if the range of cells in column number 5 (E) have a date that is greater than 30 days old
Answer: In order to make your code work as expected, I suggest you make the following changes to it:
Snippet
for (var j = 2; j < 10; j++) {
   var workingcell3 = activeSheet.getRange(j, 5).getValue();
   var sheetDate = new Date(workingcell3);
   var pastDate = new Date();
   const pastTime = pastDate.getTime() - 30 * (24 * 3600 * 1000);
   if (pastTime > sheetDate.getTime()) {
      activeSheet.getRange(j, 8).setValue(">30 Days");
   }
}

The above snippet parses the workingcell3 cell's value as a date and it also creates a constant const pastTime which represents the date from 30 days ago. For calculating the day from 30 days ago, the following formula has been used:
past_date = today_date - number_of_days * (24 * 3600 * 1000)

Afterwards the two dates are compared by using the getTime method and based on that, the cells are updated with the ">30 Days" value.
Reference

JDBC Service Apps Script
Comment: Thank you so much @ale13, it really helped me. However, the first part of my code seems to have a problem because "Incorrect Data" is only getting printed on one cell and that is (1,2). I am not sure why this is happening
Comment: Make sure the ranges for `workingcell` and `workingcell3` are different. In the code you have provided, they're both the same - which may cause the issue. The first part is working with no issues for me, so I suspect the above might be the cause for it.
Comment: Thank you very much! One final question. I want to understand how to run the code for only a range till which the cells have data. I have defined a variable using the last row function. But i am not sure how i should use the var.

  var lastrow = activeSheet.getLastRow();
Comment: If you want to get all data excluding blank lines, consider doing  [`sheet.getDataRange().getValues()`](https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange) instead of `getRange(j,5)`.

Otherwise, you could also just add a check (`if`) to skip blank cells.


save a view to Bitmap without displaying it in Android using Kotlin

Question: how can we save a view to Bitmap without displaying it in Android using Kotlin
Earlier we used
 View.setDrawingCacheEnabled(true);
 Bitmap bmp=  View.getDrawingCache();

but now getDrawingCache is deprecated
How can we save a view without displaying it.
Answer: In my solution, on Android 9 and 10, I am preparing a WebView off screen, loading html and saving the result to bitmap.
// height and width should be >0
val myBitmap = Bitmap.createBitmap(
    myView.measuredWidth,
    myView.measuredHeight,
    Bitmap.Config.ARGB_8888
)
myBitmap.applyCanvas {
    myView.draw(this)
}


How to proportionally size images to fit dimensions of 200px x 150px thumbnail in css?

Question: I`ve tried a couple of things even using the CSS clip, but not getting it proportionally fit in the thumbnails here http://giantmango.com/arttest2-2510.
In CSS, what  is the best way and how would I proportionally resize an image to display in dimensions of a 200px (width)  x 150 (height) thumbnail?
Just checked firebug and for some reason all my img tags are always set to a height of 200 even though I have max-height set to 150...
Answer: Use max-height and max-width. Beware that they are broken in older versions of IE. You can do
#myImage: {
    max-height: 150px;
    max-width: 200px;
}

EDIT: @tokiowp: try this. It should work (it surely does for me). So the problem with your layout comes from additional properties you may have set.
<!DOCTYPE html>

EDIT: it turns out, looking at your source, that you are actually declaring your images with something like

Of course what you need is to remove these declarations of width and height.
Comment: @Andrea.  I did that, but it still does not seem to be resizing proportionally.
Comment: @tokyowp: In what browser are you testing?
Comment: I suggested in the body a minimal working example, where the image is resized proportionally. Probably you have additional rules or JS which break the layout.
Comment: @Andrea unfortunately, I cannot use the img tag like that because it gets the content dynamically.  I have already set the img in css to max-height: 150px and max-width: 200px, but there`s something else that I cannot figure out that is setting the height and width to both 200px.
Comment: @tokiowp: that was just an example to save space. In practice you would be writing the CSS declarations in an external stylesheet. If you try to do so, and create a page with **only** these two rules, your image will be rescaled right. I don't know what other rules are interfering, but you can try to add them one at a time until you find what is breaking your layout.
Comment: @Andrea.  I checked all entries in the css and there`s nothing that sets the height at 200px so I`m quite confused as to what is setting the dimensions.
Comment: @tokiowp: there is nothing in the css. The declaration is in the HTML itself: I have copied and pasted the last example from your site!
Comment: @Andrea.  Thank you for looking into this.  I think it`s this php function that is placing the width and height in the html http://stackoverflow.com/questions/5068274/how-to-code-php-function-or-set-parameters-to-return-no-height-values-for-images
Comment: Really, I have told how to solve it, so we identified the problem, and now you are off to another question. It is just rude.
Comment: @Andrea.  Please understand that I did not know my problem was a two part question.  If I solve the other one, I will be able to test your solution here.  Unfortunately, I have not been able to solve either yet and thus feel I should not accept your answer otherwise I would be lying.
Comment: @tokiowp: that's ok, anyway have a look at my (updated) answer on your other question.
Answer: css:
#thumb {width:200px; height:150px;}
#thumb img {height:100%; width:100%; margin:0 auto;}

html:


Are there differences in the frequency certain champion/rare affixes occur?

Question: Last night I noticed that almost every champion/rare pack I came across had Mortar as one of their prefixes.  I believe, out of the dozen or two I fought, only 3-4 packs did not have Mortar.
It seemed like more than half had Plagued.
Yet only two had illusionist.  Only one had Horde.  Only one had Invulnerable Minions (thank goodness!). Only two had Avenger.
In all the time I've spent playing (I'm up to Act II Inferno), I've only ever seen Missle Dampening once.
I know that some affixes only become available at higher difficulties (e.g. Invulnerable Minions only appears in Hell or Inferno), and some are only possible on rares or champion packs, but not both (e.g. Horde only appears on rares, and Health Link only appears on champion packs).  But setting aside those restrictions, are some affixes "rare" on their own?
Is there any information about the relative frequency with which each affix appears?  Is Missle Dampening really just uber-rare?  Did I just get ridiculously unlucky with the RNG last night with all the Mortar Jailer Plagued X monsters I fought?
Comment: I seem to never see Missile Dampening, but I swear if Arcane Enchanted and/or Desecrator isn't on a champ/rare pack, I'd assume my game was broken.
Comment: I can't confirm this, but it seems like when one affix is on a monster in that area, other monsters in that area have a higher chance of having that same affix.  I only notice this usually when there's an affix on a monster that I absolutely hate (teleporter, waller, etc) so it could be just selective memory working.
Comment: I have yet to see a missile dampening monster and I've seen (and killed) a heck lot of uniques/champions.
Comment: Yeah, Missile Dampening is very rare; I've only seen it 2 or 3 times, ever. By contrast, Arcane Enchanted is all over the place, and Mortar is also very common.
Comment: I'm only on nightmare, and I've seen Missile Dampening twice... maybe I am just unlucky :(
Comment: I've encountered more fire chains/health links than missile dampening. I'd say that dampening is one of the rarer effects.
Comment: now that patch 1.03 is out, I've encountered missile dampening a lot (because they fixed the nether tentacles thing).
Comment: @yx. I had two missile dampening in a single run the day the patch came out, doubling my total encounters with them. But it wasn't mentioned in the patch notes, so I'm sure they didn't actually change anything, and it is merely a "coincidence" ;)
Answer: As Ben says, there are three types of affixes.  These are broken up as follows:

Strong CC (limit of one):

Knockback
Nightmarish
Vortex

Defensive (limit of one):

Avenger (Champion pack only)
Extra Health
Health Link (Champion pack only)
Horde (Boss only)
Illusionist
Missile Dampening (Boss only)
Invulnerable Minions (Boss only)
Shielding
Vampiric

Aggressive (no limit):

Arcane Enchanted
Descrator
Electrified
Fast
Fire Chains (Champion pack only)
Frozen
Jailer
Molten
Mortar
Plagued
Reflects Damage
Teleporter
Waller

So any affixes from the Aggressive category has a much higher chance of being seen, i.e. Mortar and Plagued, while an affix like Missile Dampening will only appear for Boss packs (not Champion packs) and only has a one in seven chance if they have a Defensive ability.  This results in a much lower chance of being seen.
Note that while CC and defensive categories have a limit of one from each of them, that doesn't mean that a group must have one of each of them.  I believe they can roll with only one of two, or even neither of the two, i.e. solely aggressive affixes.
Answer: There are three categories of affixes:

defensive
offensive
CC

Each champion pack can only have one defensive, one CC and as many offensive as they want. I cannot get my hand on Bashiok's post about this but I remember there were about three defensive affixes, three or four CC and around seven or eight offensive.
So a champion could come in with four offensive affixes or three offensive and one defensive. You get the point.
So if there can only be one defensive and one cc there has to be way more offensive affixes on a mob, which would explain why we see offensive affixes more than other.
Comment: Here, have the source: http://us.battle.net/d3/en/forum/topic/6079707996#1


if statement not working and stopping the whole function from working

Question: Hi can't get my "if" statement to work. When I write my if the whole function stops working. Without the if, everything works fine.
I tried everything, at least everything I could come up with, which means the use of parseInt, if/else, I read the code again and again, I changed parenthesis, I researched on google. Still nothing. I need a little help!

function myF() {

    var num1 = document.getElementById("a").value;
    var num2 = document.getElementById("b").value;
    var num3 = document.getElementById("c").value;
    var num4 = document.getElementById("d").value;
    var num5 = document.getElementById("e").value;
    var num6 = document.getElementById("f").value;
    var num7 = document.getElementById("g").value;
    var num8 = document.getElementById("h").value;
    var num9 = document.getElementById("i").value;

    if (isNaN(num1) || num1 = "") {
        num1 === 0;
    }

    var total = parseFloat(num1)+ parseFloat(num2)+parseFloat(num3)+parseFloat(num4)+parseFloat(num5)+parseFloat(num6)+parseFloat(num7)+parseFloat(num8)+parseFloat(num9);

    var floating2 = document.getElementById("result").value = total.toFixed(2);

    }
body {
     background: url(img/Construction-Wallpaper-8.jpg) repeat-y center center;
    background-size: 100% 100%;
}

form {
    width: 530px;
    align-content: center;
    margin:45px auto 5px;
    border: solid 1px darkslategrey;
    padding: 10px 0px 10px 5px;
    display: block;
}

input {
    float: right;
    clear: both;
    position: relative;
    top: -4;
}

label {
    padding: 8px 10px;
    font-family: Montauk, arial, sans-serif;
    font-size: 18px;
    font-weight: bolder;
    color: black;
    display: block;
}

input#result {
    position: relative;
    right: 10px;
    top: 6px;
}

button#Total {
    position: relative;
    left: 10px;
    top: 2px;
    background: linear-gradient(to right, darkslategrey, white);
    font-family: Montauk, arial, sans-serif;
    font-size: 29px;
    font-weight: bold;
    width: 100px;
    height: 30;
    text-align: left;
    line-height: 100%;
    box-shadow: 1px 1px 3px;
    border: solid 1px black;
}

button#total:active {
    position: relative;
    top: 1px;
    right: 1px;
}

button#total:hover {
    cursor: pointer;
}

p#title {
    font-size: 50px;
    text-align: center;
    margin: 10px;
    font-family: Montauk, arial, sans-serif; color: #333;
    font-weight: bolder
}

img#Logo {
    width: 70px;
    display: inline-block;
    position: absolute;
    top:15px;
    right: 9px;
}

p#Logo {
    font-family: "Montauk", arial, sans-serif;
    font-size: 20px;
    display: inline-block;
    width: 50px;
    height: 30px;
    position: absolute;
    top:-2px;
    right: 105px;
}

label::after {
    float: right;
    content: "$";
    font-size: 25px;
    display: inline-block;
    position: relative;
    right: 3px;
    bottom: 5px;
}

#total::before {
    content: "$";
    font-size: 25px;
    position: relative;
    left:290px;
    font-family: Montauk, arial, sans-serif;
    font-weight: bolder;
}

        <title>Payment Schedule</title>
        <link rel="stylesheet" href="zzz.css" type="text/css">

        <link rel="stylesheet" href="normalize.css" type="text/css">

• Payment Schedule •

Christopher
            Crawford
            Const.

        <form id="sumNumbers">

            I.Downpayment 5/14 <input id="a" type="text">

            II.Progress payment end of week2, @15% <input id="b" type="text">

            III.Progress payment end of week4, @15%  <input id="c" type="text">

            IV.Progress payment end of week6, @15% <input id="d" type="text">

            V.Progress payment end of week8, @15% <input id="e" type="text">

            VI.Progress payment end of week10, @15%  <input id="f" type="text">

            VII.Progress payment end of week11, @7.5%  <input id="g" type="text">

            VIII.Progress payment end of week12, @7.5% <input id="h" type="text">

            IX.Final Payment @10% <input id="i" type="text">

            <button id="total" onclick="myF();" type="button">Total</button>
            <input type="text" id="result">
        </form>

Comment: `num1 = ""` assigns `num1` the value `""` - perhaps you meant to test for equality rather than assign to a value?
Comment: Did you look up what `=` does? (It is not comparison)
Comment: Additionally, `num1 === 0;` is not a very useful expression-statement
Answer: In the if statement, you should use === to test for equality.  = is the assignment operator, which you should in the line below, i.e. num1 = 0;.
Comment: Don't bother answering trivial typo questions like this. It makes it harder to delete the question after it's closed.
Comment: But stll it works only for the first input. Infact when I leave the second or the third or the other inputs empty, the result I get is NaN.
Comment: No problemo - glad you learned!  What's happening there is that you're trying to `parseFloat()` something that's not a number (something empty,) which returns "NaN".  You tested num1, but none of the numbers to make sure of this.  What I would do is write a `for` loop to run that if statement for every `numx`.  Does that make sense?


Swift - jonkykong SideMenu UISideMenuNavigationController not found

Question: I have downloaded jonkykong SideMenu using Carthage and I imported the framework inside my project as the image below

When I try to define the custom class of the navigation controller in my storyboard to UISideMenuNavigationController as I need to do following the instructions of the library on GitHub the class doesn't is not found as image below:

The framework in working fine when I import it inside a swift file.
How can I reference this class inside the storyboard
Comment: Did you set the `Module` to `SideMenu`?
Comment: Yes I did. And it didn't work.
Comment: I think you should check their example:
https://github.com/jonkykong/SideMenu/tree/master/Example
Also try relaunch xcode and check if the library could be imported to some view controller.
Comment: I am able to import the library to a view controller programmatically but it doesn't appear as a custom class in the storyboard.
Answer: It worked when I set up the configuration manually even the XCode not finding it.
Image below:


Boost tokenizer to treat quoted string as one token

Question: Is there a way to make Boost tokenizer to split below string without splitting quoted part?
string s = "1st 2nd \"3rd with some comment\" 4th";

Exptected output:
1st
2nd
3rd with some comment
4th

Comment: This task may be more appropriate for Boost.Spirit.
Answer: You can use an escaped_list_separator from the tokenizer library. See this question for more details on how to apply it to your problem.
Answer: C++11 solution
#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> tokenize(const std::string& str) {
    std::vector<std::string> tokens;
    std::string buffer;
    std::string::const_iterator iter = str.cbegin();

    bool in_string = false;

    while (iter != str.cend()) {
        char c = *iter;
        if (c == '"') {
            if (in_string) {
                tokens.push_back(buffer);
                buffer.clear();
            }
            in_string = !in_string;
        } else if (c == ' ') {
            if (in_string) {
                buffer.push_back(c);
            } else {
                if (!buffer.empty()) {
                    tokens.push_back(buffer);
                    buffer.clear();
                }
            }
        } else {
            buffer.push_back(c);
        }

        ++iter;
    }

    if (!buffer.empty()) {
        tokens.push_back(buffer);
    }

    return tokens;
}

int main() {
    std::string s = "1st 2nd \"3rd with some comment\" 4th";
    std::vector<std::string> tokens = tokenize(s);
    for (auto iter = tokens.cbegin(); iter != tokens.cend(); ++iter) {
        std::cout << *iter << "\n";
    }
}

Answer: Try this code and this way you can avoid using Boost.Tokenizer and Boost.Spirit libs
#include <vector>
#include <string>
#include <iostream>

const char Separators[] = { ' ', 9 };

bool Str_IsSeparator( const char Ch )
{
    for ( size_t i = 0; i != sizeof( Separators ); i++ )
    {
        if ( Separators[i] == Ch ) { return true; }
    }

    return false;
}

void SplitLine( size_t FromToken, size_t ToToken, const std::string& Str, std::vector<std::string>& Components /*, bool ShouldTrimSpaces*/ )
{
    size_t TokenNum = 0;
    size_t Offset   = FromToken - 1;

    const char* CStr  = Str.c_str();
    const char* CStrj = Str.c_str();

    while ( *CStr )
    {
        // bypass spaces & delimiting chars
        while ( *CStr && Str_IsSeparator( *CStr ) ) { CStr++; }

        if ( !*CStr ) { return; }

        bool InsideQuotes = ( *CStr == '\"' );

        if ( InsideQuotes )
        {
            for ( CStrj = ++CStr; *CStrj && *CStrj != '\"'; CStrj++ );
        }
        else
        {
            for ( CStrj = CStr; *CStrj && !Str_IsSeparator( *CStrj ); CStrj++ );
        }

        // extract token
        if ( CStr != CStrj )
        {
            TokenNum++;

            // store each token found
            if ( TokenNum >= FromToken )
            {
                  Components[ TokenNum-Offset ].assign( CStr, CStrj );
                  // if ( ShouldTrimSpaces ) { Str_TrimSpaces( &Components[ TokenNum-Offset ] ); }
                  // proceed to next token
                  if ( TokenNum >= ToToken ) { return; }
            }
            CStr = CStrj;

            // exclude last " from token, handle EOL
            if ( *CStr ) { CStr++; }
        }
    }
}

int main()
{
    std::string test = "1st 2nd \"3rd with some comment\" 4th";
    std::vector<std::string> Out;

    Out.resize(5);
    SplitLine(1, 4, test, Out);

    for(size_t j = 0 ; j != Out.size() ; j++) { std::cout << Out[j] << std::endl; }

    return 0;
}

It uses a preallocated string array (it is not zero-based, but that's easily fixable) and it's pretty simple.


Is it possible to wrap a type for use only within an expression in C#?

Question: I am trying to implement a repository pattern and to do so I want to abstract the data provider, but still retain the ability to join tables.
I have decided to achieve this with an expression tree and would like my syntax to look like this:
var repo = new Repository<Role>();
repo.JoinData(
        r => r
            .Join(r => r.RolePermissions)
            .Join(rp => rp.Permission),
        r => r
            .Join(r => r.RoleCategories)
            .Join(rc => rc.Category),
        r => r
            .Join(r => r.RoleCategories)
            .Join(rc => rc.CategoryType)
    )

My problem is that the lamda's parameters 'r', which is of type 'Role' doesnt have a Join method on it. I would like to extend the type, but only have that extension usable from with the context of this method. The Join method does not actually have to perform anything as I will be taking apart the expression and using it for other means.
Is this possible?
Comment: Right, EF's `DbSet` class *is* a repository, and the `DbContext` is the unit-of-work.
Comment: Not to argue but the fact DbContext implements x or y doesn't address that using EF and its Entity classes directly in upper layers is also a bad design decision unless of course being vendor locked is a desirable outcome.
Comment: I'm not sure about your experience level or what problem you're trying to solve, but I would caution you about adding a repository layer on top of entity framework. Before diving I would suggest doing a lot of research on it: https://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework-core/.
Comment: `I would like to extend the type, but only have that extension usable from with the context of this method.`  I don't think this is possible.
Comment: @ChiefTwoPencils vendor locking, and separation of concerns for unit testing is why I have gone this route, but If I cant figure this one out I may have to give up on it.

Ideally if I could abstract data manipulation away from controllers that would be best I think since there will be complete standardisation.
Answer: Seems it is not possible, the closest I got was Oliver's answer
Answer: In a static class, declare these extension methods:
public static class JoinExtensions
{
    public static U Join<T, U>(this T input, Func<T, U> project)
    {
        throw new InvalidOperationException("Can only be used in expression lambdas");
    }

    public static U Join<T, U>(this ICollection<T> input, Func<T, U> project)
    {
        throw new InvalidOperationException("Can only be used in expression lambdas");
    }
}

The throw statements in the body of the extension methods ensure that you cannot call them in another context than in an Expression<T>. Unfortunately, you cannot enforce it at compile-time.
The JoinData method looks like this
public static void JoinData(params Expression<Func<Role, object>>[] joins)
{
    foreach (var join in joins) {
        Console.WriteLine(join); // You would evaluate the Expressions here.
    }
    Console.ReadKey();
}

With this call
JoinData(
    r => r
        .Join(r => r.RolePermissions)
        .Join(rp => rp.Permission),
    r => r
        .Join(r => r.RoleCategories)
        .Join(rc => rc.Category),
    r => r
        .Join(r => r.RoleCategories)
        .Join(rc => rc.CategoryType)
);

you get the following output in the console:

r => r.Join(r => r.RolePermissions).Join(rp => rp.Permission)
  r => r.Join(r => r.RoleCategories).Join(rc => rc.Category)
  r => r.Join(r => r.RoleCategories).Join(rc => rc.CategoryType)

This proves, that the expressions reflect the lambdas as expected.

I have tested with these entity classes:
public class Role
{
    public ICollection<RolePermission> RolePermissions { get; }
    public ICollection<RoleCategory> RoleCategories { get; }
}

public class RolePermission
{
    public Permission Permission { get; }
}

public class RoleCategory
{
    public Category Category { get; }
    public CategoryType CategoryType { get; }
}

public class Category { }
public class CategoryType { }
public class Permission { }

Comment: This doesn't answer the question. He doesn't want an extension method that can be used in lambda expressions. He wants an extension that can ONLY be used in lambda expressions, which is not possible.
Comment: @DetectivePikachu: You can solve this very simply by having a `throw` statement into the extension methods, since in an `Expression<>` the methods are never called.
Comment: This answer is very helpful, after all I dont actually need to run the delegate, just evaluate the expression.

I think with your edit this is way better than what I have. Thanks!


Error : Unable to start the zeroconf: Permission denied

Question: I am trying to use Barrier-kvm for sharing Keyboard and mouse but can't start it. I'm getting this error.
Zero Configuration service
Unable to start the zeroconf: Permission denied.
Comment: What command are you running? Is this the only output?
Comment: I downloaded barrier-kvm from the Ubuntu Store. When I launch it, and select the server option, I'm getting this error.
Answer: Permissions issue regarding installation with Ubuntu app store the fix is to reinstall with command-line permissions.
$ sudo apt install rclone barrier

Comment: Why is this installing a package called `rclone`?
Comment: @nobar: It is because... the command says to install it. The reason you want to is because it triggers a dependency that barrier needs (libavahi-compat-libdnssd1).
Answer: I had installed on 18.04 using snap and saw that error on startup.
I resolved this by disabling all security confinement -- reinstalling with...
snap install --devmode barrier-kvm

Installing KVM software implies a certain level of trust.

Another clue for me was that the setup screen said:
IP addresses: unknown

Comment: ...or you can try building from source: https://github.com/debauchee/barrier/wiki
Comment: ...although, when trying to build from source on 18.04, I ran into `Missing library: Xtst` -- which hasn't had an obvious solution for me.
Comment: The build worked on 18.10, where barrier is already in the apt repository.
Comment: This install approach is currently broken on 18.04: https://github.com/debauchee/barrier/issues/231
Comment: ... and there doesn't seem to be an older channel available.  Boo `snap`.  `sudo snap install barrier-kvm --devmode --channel 2.1.1/stable`
Comment: The issue '231' has been fixed on GitHub (see that thread).  I was able to install using the "flatpak" approach described therein.
Comment: I couldn't find the instructions that I indicated above.  Generic instructions here: http://docs.flatpak.org/en/latest/using-flatpak.html
Answer:

Use a Devmode ::
as advised already by @nobar above

# *** Warning! ***
# *** Below snap install drops all Security Confinements! ***
# ** USE AT YOUR OWN RISK! **
# ===========================

sudo snap install --devmode barrier-kvm

Try Barrier Beta Snap -- as it uses a different build options::

sudo snap install barrier-kvm --beta

Third option ::  Build your own Snap!

source yaml file merged in official Barrier's Git repo
https://github.com/debauchee/barrier

To build a snap might be also pain in the a$$...
Same issues as with Flatpak and/or building from source ;)


mt.exe unable to terminate

Question: Sometimes when I compile C++ code using nmake, the build process gets stuck at the manifest tool mt.exe (see the bottom of this screenshot - https://i.stack.imgur.com/pgyzT.png). It just never finishes, but if I cancel the build process and start again, it may run past the last point but get stuck again at another seemingly random mt.exe process. This makes building big software very cumbersome, as I need to "monitor" the build process to know when to cancel and start again from the beginning.
I'm clueless as to what could be the reason to this behavior. Has anybody encountered this problem before?
Edit: I'm using Windows 8 x64, the mt.exe comes from Windows SDK 6.0A.
Answer: I had similar problems with msbuild getting stuck at random points. Never found out what caused it, but a workaround that worked for me was to disable parallel building of projects.
Answer: Trying disabling your anti-virus on-demand scanning when building. I have seen some anti-virus software block access to a file using mt.exe, though usually you get an error instead of a hang.

mt.exe unable to terminate


Render a field based on boolean without package

Question: I am trying to make a Text field visible when a boolean is toggled true WITHOUT having to install a dependency. Does anyone know how to implement this? Is there a way to watch the request for changes to a particular field and conditionally render based on that?
<code>Boolean::make('Blocked', 'isBlocked')
            ->hideFromIndex(),

Textarea::make('Reason', 'blockedReason')
            ->withMeta([
                'extraAttributes' => [
                    'placeholder' => 'Make it less than 255 characters',
                ]
            ])
            ->rules('required', 'max:255')
            ->rows(3)
            ->hideFromIndex(),

</code>
Comment: Please provide enough code so others can better understand or reproduce the problem.
Comment: Can you not just put it in an `if` statement?
Answer: Bad solution
One solution you could use is to update the resource with the boolean to true or false. Once the page is reloaded depending on the boolean the text field is displayed.
This, however, would invalidate Nova's dynamism, I strongly advise against it.
Probably a bad solution
Another solution could be to create an event emitter in the change of the boolean value. Once the event is fired change the readonly value of the text field.
Probably the best choice
You haven't specified the reason why you can't use a package, but if you need to use the nova-dependecy-container package.
Comment: I am trying to figure out if there was any possible way to implement this without installing a package, but it seems installing a package is the optimal solution for this kind of behavior.


GridView_RowUpdating returning old values

Question: I have a grid view in which there is functionality to update/delete rows. I am storing the data to SQL using stored procedure. When I click on Edit button and change the existing value and after clicking Update button I am getting old values.
My code is :
protected void grdNatureFormation_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
    ConnectionString = GetConnectionString();
    LinkButton link = (LinkButton)grdNatureFormation.Rows[e.RowIndex].FindControl("btnUpdate");
    int id = Convert.ToInt32(link.CommandArgument);
    TextBox title = (TextBox)grdNatureFormation.Rows[e.RowIndex].FindControl("txtTitle");
    if(title != null)
    {
        using (SqlConnection Sqlcon = new SqlConnection(ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                Sqlcon.Open();
                cmd.Connection = Sqlcon;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "NatureOfFormation";
                cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = id;
                cmd.Parameters.Add(new SqlParameter("@Title", SqlDbType.VarChar)).Value = title.Text.Trim();
                cmd.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar)).Value = "update";
                cmd.ExecuteNonQuery();
                grdNatureFormation.EditIndex = -1;
                LoadData();
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        LoadData();
    }
}

private void LoadData()
{
    ConnectionString = GeneralMethods.GetConnectionString();
    SqlConnection Sqlcon = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand();
    try
    {
        Sqlcon.Open();
        cmd.Connection = Sqlcon;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "xxx";
        cmd.Parameters.Add(new SqlParameter("@Action", SqlDbType.VarChar, 50));
        cmd.Parameters["@Action"].Value = "select";
        SqlAda = new SqlDataAdapter(cmd);
        ds = new DataSet();
        SqlAda.Fill(ds);
        grdNatureFormation.DataSource = ds;
        grdNatureFormation.DataBind();
    }
    catch
    {
    }
    finally
    {
        if (Sqlcon.State == ConnectionState.Open)
            Sqlcon.Close();
        Sqlcon.Dispose();
        cmd.Dispose();
    }

}

I searched over internet for the issue and most of the posts suggest to place the data binding method in the (!Page.IsPostBack) , but in my case it is already in the same condition but not getting value.
What should I do to get new value in RowUpdating event?
Comment: share your `LoadData()` code..
Comment: Is there anything wrong done by me?@SidM
Comment: no i don't think anything is wrong with your code, i'm also trying the same example as your code on my machine.. can you tell me your that `LoadData()` is being called after your`grdNatureFormation_RowUpdating` ? set debugger on `LoadData()` and let me know.
Answer: RowUpdating is called before the gridview values are updated. You need to put your code into the RowUpdated event handler.
For more info, see the manual: GridView Events
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowUpdated - Occurs when a row's Update button is clicked, but after the GridView control updates the row.


Simple_Form and Bootstrap 3 Form Validation Notification Stopped Working

Question: I'm still learning RoR and have followed various tutorials online. In that process I believe I have messed up the nice flash notifications that Bootstrap 2 showed when validating Simple_Form submissions. I have tried to update my code, but without success. Here is what I have so far...
Running:
Rails 3.2.13
Ruby 2.0.0
I just upgraded to Bootstrap 3 using this gem in my gemfile:
gem 'bootstrap-sass-rails'

In my application.html.erb I have:
<%= render 'layouts/messages' %>

In my _messages partial I have:
<% flash.each do |type, message| %>
  <div class="alert <%= bootstrap_class_for(type) %> fade in">
    <button class="close" data-dismiss="alert">×</button>
    <%= message %>

<% end %>

In my application_helper.rb I have:
def bootstrap_class_for flash_type
    case flash_type
      when :success
        "alert-success"
      when :error
        "alert-error"
      when :alert
        "alert-block"
      when :notice
        "alert-info"
      else
        flash_type.to_s
    end
  end

In my users_controller.rb I have:
def update
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'Account successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

And in my edit.html.erb view I have:
<%= simple_form_for(@user) do |f| %>
    <%= f.input :firstname %>
    <%= f.input :lastname %>
    <%= f.input :email %>
    <%= f.input :password %>
    <%= f.input :password_confirmation %>
    <%= f.submit "Save changes", class: "btn btn-lg btn-primary" %>
<% end %>

The validation works, but when returned to the edit view, no formatting (red for errors) or flash message appears. Only a very hard to spot message outside each field is displayed. I must be missing some link between Simple_Form and Bootstrap 3, just don't know what.
I found another post where poster suggested to add:
config.input_class = "form-control"

to my simple_form initializer, but that gave me an error (think I might not have the latest version?):
undefined method `input_class=' for SimpleForm:Module (NoMethodError)

I wish I knew what was going on but I really hope someone can help me get the formatting and flash messages back. Apologies if this is a total newbie question, but I feel a little lost and possibly regretting that I upgraded too soon to Bootstrap 3 maybe.
A thousand thanks in advance to anyone reading all this :)
Comment: When you inspect the code in the browser, is the HTML for the flash message there?
Comment: Thanks for your comment, I got flash to work with the help from @prodigerati comment. I'm still trying to figure out how to get the formatting of my simple_form elements (used to show up in red text and red outlined form field).
Answer: I got the following mix of code from railscasts.com and other websites.
<% flash.each do |name, msg| %>
<div class="alert alert-<%= name == :notice ? "success" : "error" %>">
   ×
      <%= msg %>

<% end %>

Add this to the top of your controller:
respond_to :html, :json

Put this in each controller action:
def create
  ...
  flash[:notice] = 'User was successfully created.'
  respond_with(@user)
end

works with rails 3.2+ and 4.0 and twitter bootstrap rails 2, untested in tbsr 3 but will probably work fine.
Comment: Thanks this actually got my flash messages working! I changed the "> to just  so I can use the other bootstrap alerts. Now I have to change all my redirect_to url, notice: to set the flash before redirect. I'm still trying to figure out why my simple_form elements are not colored after upgrading to TBS3, but will accept this as an answer if I don't get an answer about that :)
Answer: This worked for me far much better than others as it;s shorter and includes all alert cases -> error, success, alert & notice provided by Bootstrap.
N.B: I renamed your _messages partial to _flash_messages because that is what most people use.
And for those who may be wondering where to generate the _flash_messages partial, it's pretty easy, just right-click your layouts folder in views and 'add new file'. You can call it _flash_messages as I've done, and ensure you have that first underscore (_) before 'flash...'. Tap 'Save'
Now in your _flash_messages.html.erb partial, use this
    <% unless flash.blank? %>
       <% flash.each do |type, message| %>
          <div class="alert <%= flash_class(type.to_s) %>">
             <button class="close" data-dismiss="alert">x</button>
          <%= message %>

       <% end %>
    <% end %>

And in your application_helper.rb use this
       def flash_class (type)
          case type
             when 'error'
                 "alert-error"
             when 'notice'
                 "alert-info"
             when 'alert'
                 "alert-block"
             when 'success'
                 "alert-success
          else
             type.to_s
          end
     end

Then in your application.html.erb, add this as your first line in your first div
<%= render partial: 'layouts/flash_messages', flash: flash %>

Notice that we render the partial (any partial that is), without the 'starter' underscore(_), i.e before the word 'flash..'
You can check out this answer from teamtreehouse on displaying different alert cases.
Hope this helps!


Play audio from video in lock screen

Question: I have an app where I want to play audio in the background. The trick is that there are NO audio tracks by them selves. There is only video, which is where the associated audio is coming from.
I added the following to my App Delegate:
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance]
                setCategory: AVAudioSessionCategoryPlayback
                error: &setCategoryError];

and this to my plist:
<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
</array>

However, Apple rejected my app this morning for having "background audio" in my info.plist. Even after I explained to them it was so I could play the videos via headphones/airplay when the device is locked.
I've researched this subject a number of times now and this is the only way I have found that looks like it would get approved by the app store yet, here I am getting rejected. What's the problem? Does anyone know how to accomplish background audio (from video) in a way that will get me approved?
Answer: Once the screen is "off" you double tap the home button and hit play. This will 1) play audio or 2) play video/audio to apple tv. After explaining this to Apple (irony) they let me resubmit the app and accepted it.

Play audio from video in lock screen


Dpkg keep saying that need to --configure -a while trying for network issues on Inspiron 1545

Question: I've just installed ubuntu for the first time on a computer (version 12.10). I can't figure out how to get a wired connection to work OR a wireless connection.
I've read similar problems, and I've tried the other recommended fixes (at least those that I could figure out), and none of them have worked. Most of the time the terminal just gives me an error when I try to type in the message others recommend.
I see a lot of people recommending to type this in:
sudo apt-get remove bcmwl-kernel-source

This gives me an error message that says:

E: dpkg wasa interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

So, outside of recommending that fix, what are some other options? I'm using another computer to ask this question.
Also, I'm running from a flash driver right now. Is that a problem? Should I try to install an older version. I'd like to install on my computer, but I can't without an internet connection...
Thanks!
Answer: To do what ever else first you have to resolve the home issue. just open your terminal and type as
sudo dpkg --configure -a

What it will do ?
 --configure package...|-a|--pending
          Reconfigure an unpacked package. If -a  or  --pending  is  given
          instead  of  package, all unpacked but unconfigured packages are
          configured.

          Configuring consists of the following steps:

          1. Unpack the conffiles, and at the same time back  up  the  old
          conffiles, so that they can be restored if something goes wrong.

          2. Run postinst script, if provided by the package.

after fixing the above issue,  you can install/remove
sudo apt-get remove bcmwl-kernel-source

Comment: Thank you so much for your quick response. It's taken me a few days to get back to working on this, and your recommendations did something, but I still can't add the Broadcom STA Wireless driver. When I try to activate it, it says "Sorry, the installation of this driver failed. Please have a look at the log file for details: /var/log/jockey.log" After running your recommendations I got two warnings. "failed to detect canonical device of overlayfs" and "could not determine root device from /etc/fstab." I'm not sure what either of those means.

Should I just try to install an older version?
Comment: Seems to be yes. Something Went wrongly. Check that log file for more details.
Answer: If nothing works then just try this:
open a terminal(CTRL+ALT+T) and execute:
    $ sudo (jockey-gtk &)

It will automatically search all available proprietary drivers and try to fix it and then  don't forget to restart your system.
Comment: and don't forget to restart your system.


Add utterances to a LUIS app using C#

Question: I'm trying to implement a C# code which can add utterances in my Luis API like it is showed in this tutorial.
So I'm only interested in the function AddUtterances() and to test it I put it in the function ShowLuisResult() to be sure it will be used each time I send a message to the chatbot but when I take a look in the API I see no utterance is added...
I put the file utterances.json at the same place as BasicLuisDialog.cs and in /d/home in the kudu console to be sure it works.
Here is the code :
using System;
using System.Configuration;
using System.Threading.Tasks;

using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;

using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net.Http;
using System.Xml.Linq;

namespace Microsoft.Bot.Sample.LuisBot
{
    // For more information about this template visit http://aka.ms/azurebots-csharp-luis
    [Serializable]
    public class BasicLuisDialog : LuisDialog<object>
    {

        // NOTE: Replace this example LUIS application ID with the ID of your LUIS application.
        static string appID = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

        // NOTE: Replace this example LUIS application version number with the version number of your LUIS application.
        static string appVersion = "0.1";

        // NOTE: Replace this example LUIS authoring key with a valid key.
        static string authoringKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

        static string host = "https://westus.api.cognitive.microsoft.com";
        static string path = "/luis/api/v2.0/apps/" + appID + "/versions/" + appVersion + "/";

    public BasicLuisDialog() : base(new LuisService(new LuisModelAttribute(
        ConfigurationManager.AppSettings["LuisAppId"],
        ConfigurationManager.AppSettings["LuisAPIKey"],
        domain: ConfigurationManager.AppSettings["LuisAPIHostName"])))
    {
    }

    [LuisIntent("None")]
    public async Task NoneIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }

    // Go to https://luis.ai and create a new intent, then train/publish your luis app.
    // Finally replace "Greeting" with the name of your newly created intent in the following handler
    [LuisIntent("Greeting")]
    public async Task GreetingIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }

    [LuisIntent("Cancel")]
    public async Task CancelIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }

    [LuisIntent("Help")]
    public async Task HelpIntent(IDialogContext context, LuisResult result)
    {
        await this.ShowLuisResult(context, result);
    }

    private async Task ShowLuisResult(IDialogContext context, LuisResult result)
    {
        AddUtterances("utterances.json");
        await context.PostAsync($"You have reached {result.Intents[0].Intent}. You said: {result.Query}");
        context.Wait(MessageReceived);
    }

    async static Task AddUtterances(string input_file)
    {
        string uri = host + path + "examples";
        string requestBody = File.ReadAllText(input_file);
        var response = await SendPost(uri, requestBody);
        var result = await response.Content.ReadAsStringAsync();
    }

    async static Task<HttpResponseMessage> SendPost(string uri, string requestBody)
    {
        using (var client = new HttpClient())
        using (var request = new HttpRequestMessage())
        {
            request.Method = HttpMethod.Post;
            request.RequestUri = new Uri(uri);
            request.Content = new StringContent(requestBody, Encoding.UTF8, "text/json");
            request.Headers.Add("Ocp-Apim-Subscription-Key", authoringKey);
            return await client.SendAsync(request);
        }
    }

}

}
And here is the content of utterances.json :
[
    {
        "text": "go to Seattle",
        "intentName": "Help",
        "entityLabels": []
    },
    {
        "text": "book a flight",
        "intentName": "Greeting",
        "entityLabels": []
    }
]

Comment: You did change out the app id and authoring key for your own, correct?
Comment: How exactly you do "I take a look in the API I see no utterance is added..."? Could you confirm there are no changes even if you are logged into https://www.luis.ai/applications/yourAppId/versions/yourVersion/build/intents ?
Comment: @DFBerry Yes, I did. Sorry I didn't mention it.
Comment: @FerdinandFejskid There are no changes. I logged into the API using your link and I changed "yourAppId" and "yourVersion" with mine but I see no difference in the intents and no utterances is added.
Comment: Do you know that the code to update utterances works outside the bot framework? Perhaps in just a console app?
Answer: I haven't tested your code, but did notice that you are not awaiting the call to AddUtterances from within ShowLuisResult:
private async Task ShowLuisResult(IDialogContext context, LuisResult result)
{
    AddUtterances("utterances.json"); //<-- NOTE: this line should be awaited
    await context.PostAsync($"You have reached {result.Intents[0].Intent}. You said: {result.Query}");
    context.Wait(MessageReceived);
}

Answer: For whatever reason the Botbuilder tools for Luis are gone from Github as seen that they were here 2 weeks ago -
Google cache of Luis Bot Builder tools git
Image capture of the git with all functionality of Luis CLI form - no need for full program
I cant post images yet so heres a link to a picture https://i.stack.imgur.com/ZNguf.jpg

Add utterances to a LUIS app using C#


Need help migrating from AngularJS to Angular 6

Question: I have an old AngularJS app and I want to migrate to Angular 6 using the hybrid app method.
Before I do so, I wanted to follow the upgrade tutorial:
Phonecat upgrade tutorial
So I cloned the Phonecat AngularJS app and followed the steps. I'm stuck at the "Upgrading Phone service" step.
The problem is by having an "import {...} from '...';" in the "phone-list.component.ts" file. When I remove the import and replace the types by "any", it works. As soon as I add the import, I have the following error in Chrome:

exports is not defined

I have search all night yesterday and found some solutions but none of them works. Maybe it's because must of the documentation I found was for angular versions before 6.
Some people say that recent browsers should handle the import, some other says that we should not use SystemJS... I'm a little bit lost.
Thanks for your help. If you need futher details or files, I'll be pleased to update my question.
Here's the phone-list.component.ts
// import { Phone, PhoneData } from '../core/phone/phone.service';
declare var angular: angular.IAngularStatic;

class PhoneListController {
  phones: any[];
  orderProp: string;

  static $inject = ['phone'];
  constructor(phone: any) {
    phone.query().subscribe(phones => {
      this.phones = phones;
    });
    this.orderProp = 'age';
  }
}

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: PhoneListController
  });

Here's the phone-list.component.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PhoneListController = /** @class */ (function () {
    function PhoneListController(phone) {
        var _this = this;
        phone.query().subscribe(function (phones) {
            _this.phones = phones;
        });
        this.orderProp = 'age';
    }
    PhoneListController.$inject = ['phone'];
    return PhoneListController;
}());
angular.
    module('phoneList').
    component('phoneList', {
    templateUrl: 'phone-list/phone-list.template.html',
    controller: PhoneListController
});
//# sourceMappingURL=phone-list.component.js.map

Here's my tsconfig.json
{
    "compileOnSave": false,
    "compilerOptions": {
        "baseUrl": "./",
        "sourceMap": true,
        "declaration": false,
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2017",
            "dom",
            "es5",
            "es6"
        ]
    }
}

Here's my system.config.js
/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
    System.config({
        paths: {
            // paths serve as alias
            'npm:': '/node_modules/'
        },
        // map tells the System loader where to look for things
        map: {
            // 'ng-loader': '../../../systemjs-angular-loader.js',
            // our app is within the app folder
            'app': '/app',

            // angular bundles
            '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
            '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
            '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
            '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
            '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
            '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
            '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
            '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
            //'@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
            '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

            'core-js': 'npm:core-js',
            'zone.js': 'npm:zone.js',
            'rxjs': 'npm:rxjs',
            'tslib': 'npm:tslib/tslib.js',

            // other libraries
            'rxjs': 'npm:rxjs',
            'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
        },
        // packages tells the System loader how to load when no filename and/or no extension
        packages: {
            app: {
                main: './main.js',
                defaultExtension: 'js'
            },
            rxjs: {
                main: 'index.js',
                defaultExtension: 'js'
            },
            'rxjs/operators': { main: 'index.js', defaultExtension: 'js' }
        }
    });
})(this);

Here's my html file
<!doctype html>

    <base href="/app/">
    <meta charset="utf-8">
    <title>Google Phone Gallery</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="app.css" />
    <link rel="stylesheet" href="app.animations.css" />

Answer: Have you tried using another module in your tsconfig.json, like umd instead of commonjs? I think this fixed the issue for me


pushViewController in viewWillAppear failed after popToRootViewController

Question: there have 3 view controllers, A,B,C, all designed in storyboard.
in all pushViewController: controllers were got from [self.navigationController instantiateViewControllerWithIdentifier:@"A/B/C_Controller"];
In A_ViewController ( root controller ):
-(void)viewWillAppear
{
   [self.navigationController pushViewController:B_Controller animated:YES];
}

In B_ViewController:
-(IBAction)someButtonClick
{
   [self.navigationController pushViewController:C_Controller animated:YES];
}

In C_ViewController:
-(IBAction)someButtonClick
{
   [self.navigationController popToRootViewControllerAnimated:YES];
}

Problem:
A_viewController -> B_viewController -> C_viewController is fine.
but after popToRootViewController to A From C, A can't push to B anymore.
and other pushViewController: all can't works, popViewControllerAnimated: also cause crash.
Note.
have tried
// in A view
dispatch_async(dispatch_get_main_queue(),^{
    [self.navigationController pushViewController:B_viewController animated:YES];
 })

in this post, but it doesn't works for me.
does anyone know what happens in view controller stacks?
have struggling in this issue all day, any help will be appreciated!
Comment: What exactly did you try from the referenced question ? The only suspicious part of your code is `animated` argument at `viewWillAppear`, are you actually aiming for some kind of stacked animations ?
Comment: just edit the question, sorry for the confusion, my bad
Comment: Please describe what you aim to achieve, then we might be able to guide you.
Comment: Interestingly, I can't reproduce it, might be the differences at the code as there're some strange parts like missing argument at `viewWillAppear` and using `instantiateViewControllerWithIdentifier` on `UINavigationController`.
Answer: When you When you popToViewController from C, the viewWillAppear method will in A be called just before the animation. Now, at this point, since the transition is in progress, you might get some kind of warning in the debugger like:
"Warning: Attempting to push .... while a transition is in progress"

You need to call the navigation controller methods in such a way that they do not overlap each other.
Calling pushViewController in the viewDidAppear method of A would be better in this context.


Fundamental group of a sphere with straight line joining the north and south poles

Question: This problem comes from the book Topology and Geometry of Bredon :

Let $X$ be the union of the unit sphere in 3-space with the straight line segment from the north pole to the south pole. Find $\pi_1(X)$.

I am reading Atcher's book at the same time. He gives a CW-complex structure to this space, and since the line is contractible, he identifies this space to $S^2 \vee S^1$ from which we can compute the fundamental group using Seifert-van Kampen's theorem and we get
\begin{equation*}
\pi_1(X) \approx \mathbb{Z}.
\end{equation*}
Nevertheless, one should be able to use Seifert-van Kampen's theorem directly to this space without relying on some CW-complex structure as it is not yet introduced in the book of Bredon at this stage.
I have tried the following :
Consider the open cover $\{U, V\}$ where $U$ is a thickened neighborhood of the union of the north hemisphere and the middle-top part of the straight line, and where $V$ is a thickened neighborhood of the union of the south hemisphere and the middle-bottom part of the straight line. But, the way I understand it, they are both contractible (they contract to the north and south pole respectively), and thus the fundamental group vanishes by Seifert-van Kampen's theorem.
Where is the error in this argument?
Comment: The intersection of $U$ and $V$ is not path connected! You have two connected components, namely some intersection along the equator of the sphere and the intersection of the two parts of the line.
Comment: I tend to forget that one too :) I am currently playing around with different open sets $U$ and $V$, to see if your idea can be fixed, but I keep running into the same issue.
Comment: Thank you @guidoar for pointing it out! I forgot about this hypothesis in the theorem.
Answer: Consider $U$ and $V$ to be semispheres, i.e. $U$ goes from the north pole to a bit past the equator, and $V$ from a bit above the equator to the south pole. But don't imagine the line to be perpendicular to the equator plane but rather contained in it. Or if you will, construct $U$ and $V$ relative to Greenwich's meridian :)
If you stare at $U$ and $V$ for a while, they are (homotopic to) disks with a cord attached to two points of the boundary. Collapsing the disks, one gets moreover a homotopy equivalence with $S^1$ in both cases.
The intersection is now a band along the equation together with the line. Via a deformation retraction, this is homotopy equivalent to just the equator - i.e. $S^1$ - and the line, which is like a figure $8$ (collapse the line).
Hence by van Kampen we have $\pi_1(X) = \pi_1(U) \ast \pi_1(V) / \langle \langle  \iota_1(\omega)\iota_2(\omega)^{-1} : \omega \in \pi_1(U \cap V)\rangle\rangle$, and $\pi_1(U) = \pi_1(V) = \Bbb Z$.
The intersection $U \cap V$, as we have said, is homotopy equivalent to a figure $8$, whose fundamental group is the free group on two generators, one for each loop. Chasing the homotopies, we obtain that the generators for $\pi_1(U \cap V)$ correspond to going through the line and then to one half of each semicircle of the equator. If $a$ and $b$ are the generators of $\pi_1(U)$ and $\pi_1(V)$, then these loops correspond to $a$ and $b$ so the relation introduced is $a = b$.
Finally, this gives $\pi_1(X) = \langle a,b : a = b\rangle \simeq \Bbb Z$, as desired. Maybe a different choice of orientations changes the presentation a little bit (e.g. the relation could be $ab = 1$, which still yields the correct group).


Is a five-block horizontal jump in minecraft legitimately real?

Question: I saw videos of people doing five-block horizontal jumps, but I can't do it in Minecraft. How?
Comment: Can you link to your sources? Are you sure they weren't using mods?
Comment: Apparently it's possible without mods but requires some very strange and specific precision and circumstances that's difficult for many players to pull off. Though as far as we know, five blocks are the limit for this.
Comment: 5 block jump vertically, or horizontally?
Comment: Speed boost, jump boost (be it from potions or beacons), or just glide the gap on elytra. Combining the three you can cover a 10 block gap
Answer: It is with certain potions, with this jump the least you will need is Speed 1, but any higher and the jump gets a little easy although, it takes time to adjust to the new speed. If you're making a server please consider using the /effect command by giving yourself a command block by using:
<code>/give @s command_block 1
</code>


Translate iptables rule to UFW

Question: I need to translate these rules:
iptables -A firewall -p udp –dest 126.96.36.199/16 -j ACCEPT
iptables -A firewall -p igmp –dest 18.104.22.168/16 -j ACCEPT

To UFW rules. Don't know how to set -A -dest -j. I have tried this rules but doesn't work.
sudo ufw allow proto udp to 18.104.22.168/16

How should be the command for UFW?
Comment: It adds rules to `Chain ufw-user-input`. What do you mean by "doesn't work"?  Is it some forwarding?
Answer: After a lot of search and asking around, I was advised to switch from UFW to nftables. And then I used iptables-translate command to create the rules that I needed, so it was something like:
iptables-translate -A firewall -p igmp --destination 220.127.116.11/16 -j ACCEPT

And I was able to solve the issue like that...

Translate iptables rule to UFW


Purely inseparable dominant rational map of irreducible affine varieties induces homeomorphism of open-dense subsets.

Question:
Let $f:X\dashrightarrow Y$ be a dominant rational map of irreducible affine
  varieties which induces a purely inseparable field extension $k(Y)\to k(X)$. Prove that there is an open-dense subset $V\subset Y$ such that $f$ defines a homeomorphism $f^{-1}V\to V$.

This is an exercise from an algebraic geometry course notes. There is a hint: show first that it suffices to treat the case when $k(X)$ is obtained from $k(Y)$ by adjoining the $p$th root of an element $g\in k(Y)$ (which I have checked). Then observe that if $g$ is regular on the affine open-dense $V\subset Y$, then $Y$ contains as an open dense subset an open sense subset of the locus of $(x,t)\in V\times \mathbb{A}^1$ satisfying $t^p=g$ (which I find confusing).
Comment: it should read then $X$ contains an(copy of) open dense subset of $V \times \mathbb{A}^1$.
Comment: @random123 I still couldn't understand...could you explain in detail, thanks
Answer: We are reduced to the case $k(X) = k(Y)[X]/(X^p - g)$, where $g\in k(Y)$. Also we can assume that $f$ is surjective otherwise we can replace $Y$ by a suitable open dense subset.
Let $g$ be defined on some affine open dense subset say V of $Y$. Consider the subvariety of $V \times \mathbb{A}^1$ defined by the equations $g-t^p$, call it $W$. Note that since $g$ is defined on $f$, the $p-$th root of image of $g$ in $k(X)$ is defined over $f^{-1}(V)$.
Now, $k[W] = k[V][t]/(t^p - g)$, thus we see that the canonical inclusion $k[W] \hookrightarrow k[f^{-1}(V)]$ induces isomorphism on rational functions $k(W) \xrightarrow{\cong} k(X)$. Thus the induced map on varities $\tilde{f} : f^{-1}(V) \rightarrow W$ is a birational map. Hence there exists an open subset $W' \subset W$ such that $\tilde{f}|_{\tilde{f}^{-1}(W')} : \tilde{f}^{-1}(W') \rightarrow W'$ is an isomorphism. Note that here we can take the open set $\tilde{f}^{-1}(W')$in $X$ since $\tilde{f}$ is defined on all of $f^{-1}(V)$. Hence this is a homeomorphism.
Consider the first projection $pr_1 : V \times \mathbb{A}^1 \rightarrow V$. Note that $pr_1 \circ \tilde{f} = f|_{f^{-1}(V)}$. Hence our main task is now to prove $pr_1|_W$ is a homeomorphism.
Claim : The map $pr_1|_W$ is a homeomorphism onto $V$.
Assuming the claim we first prove the required statement. Let $V'$ be an open affine subset of $pr_1(W')$, we can do this since $pr_1$ is an open map and $W'$ is open in $V \times \mathbb{A}^1$. Then we replace $W'$ by $pr_1^{-1}(V')$. Now it is clear that $f|_{f^{-1}(V')} : f^{-1}(V') \rightarrow V'$ is a homeomorphism.
Proof of claim : Note that $k[V] \hookrightarrow k[V][t]/(t^p - g)$ is an integral extension and hence it satisfies going up property and thus induces a closed map on spectra that is $pr_1$ is a closed mapping. Also since the extension is purely inseparable the map on spec is bijective. This is an exercise from Atiyah's Commutative Algebra chapter 5, Exercise 15. A bijective closed map is a homeomorphism. Hence the proof of the claim.


how to correlate onclick mouse position to exact DOM element content?

Question: Using jquery I try to create a plugin which can do the following: given an arbitrary webpage which is mostly text-based like wikipedia or such. Basically I'm talking about plain HTML rendered by the browser. Now, if the user clicks somewhere on the website, like in the middle of an interesting sentence (or word) of a text passage, the plugin detects this click - at this point I think I'm talking about a simple onclick event.
What I now want to do is: the plugin not only knows that the user clicked but also exactly where within the DOM tree. this means for example that i want to know that the click is correlated to a span-element which contains a string AND within that string the user clicked between character 4 and 5.
I found an image which shows pretty good what I try to do.
With such a plugin there are plenty of things one can do like: highlight some text like you do when learning from a book or create highlighted correlations between text passages on different websites, ...
but currently i'm just thinking about how I could gather the data needed for visualization within the browser
thx for any hint on this
Answer: You can listen for clicks anywhere in a document by starting with something like:
$(function() {
    $(document).click(function(evt) {
        var elementClicked = evt.target;
        var xCoordinate = evt.pageX;
        var yCoordinate = evt.pageY;

        alert('You clicked a ' + elementClicked.tagName +
            ' at {' + xCoordinate + ',' + yCoordinate + '}');

        // Do work to figure out what the element was and where within it was clicked
        switch (elementClicked.tagName.toLowerCase()) {
            case "input":
            case "span":
            case "button":
            case "label":
            case "select":
            case "textarea":
            case "p":
            ...
        }
    });
});

The problem there is anything else that had an onclick event needs to prevent the event from propagating to your "master" click handler.
Here's a JSFiddle to get you started.
Comment: the usage of getSelection from your JSFiddle seems worth a look. At least Firefox's window.getSelection() provides a few interesting properties - not yet sure which will do it