How to convert a stacked long dataframe to wide format

Question: I am trying to process a json file and halfway through I end up with this
data1

name
value

data_id1
8538u40952

data_id2
40942094i2

data_text1
la la la

data_text2
we love pie eating and pie making

data_metrics_likes1
0

data_metrics_likes2
5

data_users_id1
284u94u20942

data_users_id2
094200220030

How do I get the data to look like this

text id
text
likes
userid

8538u40952
la la la
0
284u94u20942

40942094i2
we love pie eating and pie making
5
094200220030
Answer: library(tidyverse)

data <- tribble(
  ~name, ~value,
  "data_id1", "8538u40952",
  "data_id2", "40942094i2",
  "data_text1", "la la la",
  "data_text2", "we love pie eating and pie making",
  "data_metrics_likes1", "0",
  "data_metrics_likes2", "5",
  "data_users_id1", "284u94u20942",
  "data_users_id2", "094200220030"
)

data %>%
  mutate(
    id2 = name %>% str_extract("[0-9]+$"), # ensure unique rows
    name = name %>% str_remove("[0-9]+$") %>% str_remove("^data_")
  ) %>%
  pivot_wider(names_from = name, values_from = value) %>%
  select(`text id` = id, text, likes=metrics_likes, userid=users_id) %>%
  type_convert()
#>
#> ── Column specification ────────────────────────────────────────────────────────
#> cols(
#>   `text id` = col_character(),
#>   text = col_character(),
#>   likes = col_double(),
#>   userid = col_character()
#> )
#> # A tibble: 2 × 4
#>   `text id`  text                              likes userid
#>   <chr>      <chr>                             <dbl> <chr>
#> 1 8538u40952 la la la                              0 284u94u20942
#> 2 40942094i2 we love pie eating and pie making     5 094200220030

Created on 2022-05-05 by the reprex package (v2.0.0)
Answer: With tidyr, You can separate the name column by extract() and then transform the data to a wide form.
library(tidyr)

data %>%
  extract(name, c("name", "row"), "data_(.+)(\\d+)") %>%
  pivot_wider()

# # A tibble: 2 x 5
#   row   id         text                              metrics_likes users_id
#   <chr> <chr>      <chr>                             <chr>         <chr>
# 1 1     8538u40952 la la la                          0             284u94u20942
# 2 2     40942094i2 we love pie eating and pie making 5             094200220030

Answer: A base R option using reshape
reshape(
    transform(
        df,
        id = gsub(".*(\\d+)$", "\\1", name),
        name = gsub(".*?_(.*)\\d+$", "\\1", name)
    ),
    direction = "wide",
    idvar = "id",
    timevar = "name"
)

gives
  id   value.id                        value.text value.metrics_likes
1  1 8538u40952                          la la la                   0
2  2 40942094i2 we love pie eating and pie making                   5
  value.users_id
1   284u94u20942
2   094200220030


Should I use single quotation mark or double to describe jquery?

Question:
Possible Duplicate:
When to Use Double or Single Quotes in JavaScript

I'm confusing what I should use in jQuery.
Some use single some use double quotation mark.
For example
<code>$('.class1').removeClass('class1')
$(".class1").removeClass("class1")
</code>
Also, alert as well
<code>alert("aa");
alert('aa');
</code>
which one is correct?
Comment: you must see:
[http://stackoverflow.com/questions/3149192/difference-between-single-quotes-and-double-quotes-in-javascript][1]

  [1]: http://stackoverflow.com/questions/3149192/difference-between-single-quotes-and-double-quotes-in-javascript
Answer: This is more a matter of preference than correctness.  See this question for more details: When to use double or single quotes in JavaScript?


undesirable empty space between status bar and custom snackbar

Question: my activity xml layout file:
<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.votingsystem.tsiro.mainClasses.LoginActivity">

<!-- Framelayout to display Fragments -->
<com.rey.material.widget.FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <io.codetail.widget.RevealFrameLayout
        android:id="@+id/revealContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/themeImgv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:contentDescription="@string/theme" />

    </io.codetail.widget.RevealFrameLayout>

    <RelativeLayout
        android:id="@+id/loginActivityFgmtContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" />

    <com.rey.material.widget.FrameLayout
        android:id="@+id/errorContainerRlt"
        android:layout_width="match_parent"
        android:layout_height="@dimen/errorContainer_Rlt_height" />

    <com.rey.material.widget.SnackBar
        android:id="@+id/loginActivitySnkBar"
        android:layout_width="match_parent"
        android:layout_height="@dimen/loginActivity_SnkBar_height"
        android:visibility="invisible"
        android:layout_gravity="bottom" />

</com.rey.material.widget.FrameLayout>
</code>

setting windowTranslucentStatus to true to main Application theme eliminates the empty space shown in the picture. Can anybody tell me what's is going wrong if windowTranslucentStatus is set to false?
Answer: well, after a second careful look at my code i found out that i was setting programmatically padding to my custom snackbars container layout...i removed it and empty space 'magically' removed...sorry for being so careless and post such stupid question..


Getting attributes from queryset in django-admin

Question: I would like to use a queryset(queryset) in django-admin to get all the objects. Based on the queryset achieved, i would like to display certain attributes of the queryset for viewing. For example, I would like to show the person's id, the person's parent, the person's parentname,email and so on.
The example provided in Django docs is:
class MyModelAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

I would definitely like to improve on this.
I have tried something like this:
class ChildParentAdmin(admin.ModelAdmin):
    list_display = ('displayname', 'StudentID',)
    search_fields = ['displayname',]

    def queryset(self, request):
        qs = super(MyModelAdmin, self).queryset(request)
    def StudentID(self,queryset):
        for student in queryset:
            return student.pk

The point i am stuck in how do you use the queryset and perform further actions like getting the id of each child, name of parent of each child and so on... Would like some guidance on going about doing this.Would really appreciate any help on this.. Thanks...
Comment: The django admin already displays attributes in the `change_list` view (i.e. /admin/app/model/). To change which attributes to display in each row, just use  [`list_display`](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display)
Comment: the model that i have is linked with other models(like Parent) through ForeignKey so i need to get data from the other model and display it.. e.g       def Parent_First_Name(self):
      adult = student.relationships.filter(role=StudentAdultRelationship.PARENT)[0].adult
            return '%s' % adult.profile.firstname
        Parent_First_Name.short_description = 'Parent First Name'
Comment: and i want to do it to every item in the queryset.
Comment: Posible duplicate of [Django Admin: how to display fields from two different models in same view?](http://stackoverflow.com/questions/3409970/django-admin-how-to-display-fields-from-two-different-models-in-same-view) **Check the comment in the accepted answer** :-)
Answer: def StudentID(self, obj):
  return '%s' % obj.pk
StudentID.short_description = 'StudentID'
def Student_Name(self, obj):
    return '%s' % obj.name

This is the correct way of doing it..  You don't have to query over all the objects in queryset. Just need to pass the obj. It will run it for all objects. There are other ways of doing this, which doesn't involve the class itself..To read more on this, please look at list_display Django Admin. The examples are very clear.


MySQL Function Oddness When Using IN Operator

Question: I have the below query which runs ok and returns the string 2,3. FN_GET_PLAN_UPGRADE_OPTIONS is returning a VARCHAR.
SELECT FN_GET_PLAN_UPGRADE_OPTIONS(1);

Now when I add this function call into a WHERE clause using the IN operator it only returns the result where act_id contains 2 and no results where act_id contains 3, there is data for both so both should be returned, any suggestions or ideas, no errors are thrown!?
SELECT act_id
, act_name
FROM account_types
WHERE act_id IN (FN_GET_PLAN_UPGRADE_OPTIONS(1));

Comment: The argument to `IN` must be a literal list, not a string with comma-separated values. Use `FIND_IN_SET` with a string.
Comment: Fairplay, I wasn't aware of the literal list constraint on the `IN` operator.
Answer: The query you want to run is this:
SELECT ... WHERE act_id IN (2,3)

but the query you are actually running is this:
SELECT ... WHERE act_id IN ('2,3')

because your function returns a STRING (not a list of values), and since you are comparing a string with a NUMBER (act_id), MySQL will automatically cast this string to a number, so you end up running this:
 SELECT ... WHERE act_id IN (2)

you can use FIND_IN_SET to solve your problem:
SELECT ... WHERE FIND_IN_SET(act_id, FN_GET_PLAN_UPGRADE_OPTIONS(1))>0

Answer: You should use find_in_set():
WHERE find_in_set(act_id, FN_GET_PLAN_UPGRADE_OPTIONS(1))

In interprets the returned value, say '1,2' as a single string of length three -- rather than two different values.
Answer: The result is desired, in fact you are saying
SELECT act_id
, act_name
FROM account_types
WHERE act_id IN ('2,3');

Notice, the WHERE act_id IN ('2,3') is completely different than WHERE act_id IN (2,3).
You can also use REGEXP function:
SELECT act_id
, act_name
FROM account_types
WHERE FN_GET_PLAN_UPGRADE_OPTIONS(1) REGEXP act_id;


Intercepting a filestream...Impossible?

Question: No doubt this isn't possible but i would like to see if anyone has an ingenious suggestion. We have a third party assembly which can output an image stored internally within a bespoke database to file using an internal method 'SaveToFile', an example:
3rdParty.Scripting.ImageManager man = new 3rdParty.Scripting.ImageManager("ref");

3rdParty.Scripting.Image itemImg = man.GetImage(orderNumber);

itemImg.SaveToFile("c:\file.jpg")

ItemImg.SaveToFile has no return type and just creates a bitmap internally and writes that to a filestream. We have absolutely no access to the compiled method.
What i need to do is somehow intercept the filestream and read the bitmap, i know this probably isn't possible but i'm no absolute expert so wanted to see if there is a magical way to do this.
If all else fails i'll save the file then read it back, i just want to avoid saving to disk where i might be able to obtain the data directly and eventually convert that to a base64 string value.
Comment: `3rdParty.Scripting.Image itemImg = man.GetImage(orderNumber);` -- This is the image here in memory, is it not? Surely they give more access to the image than only being able to save it to file, e.g., if you have access to all the pixel data then can't you just construct the "base64 string value" from `itemImg`?
Comment: Use a MemoryStream.
Comment: Im with @Quantic on this. Do some debugging and see what the private members are for this `Image` type. If there is something loaded in managed memory you could use reflection to get that stream from the private members of that type. The code though will be very fragile and should be retested with any version changes made by that library.
Comment: Unfortunately that is just a constructor, there are no methods to return the stream...only to export to file :(
Comment: Probably you're looking for something like [Can I get a path for a Memory Mapped File?](http://stackoverflow.com/q/1114786/18192).  Unfortunately, the answer to that question is no.
Answer: Unfortunately unless the 3rd party library provides a SaveToStream method where you could provide the stream from the outside there's no way to achieve what you are after. You will have to save the contents to a temporary file and then read the contents back.
That's why it's usually best practice when designing a library to provide methods taking Streams as I/O parameters as this would give the consumer the control of whether he wants to save it to a file, memory or network stream.
Comment: Thanks Darin, my thoughts exactly...it's a terrible library but we have no choice but to use it. Thanks.

Intercepting a filestream...Impossible?


Can I disable Chromium's in-browser mp3 player?

Question: When I click on a link in Chromium to an mp3, can I make the default behavior be to download it and not to start playing it with some in-browser thing?
I've disabled all of my plugins, so it's not one of them trying to play the file.  And I suppose I could always right-click or control-click or what have you -- but the problem isn't that I don't know how to download the file (if I were desperate and/or crazy I would just curl it), the problem is that Chromium seems to think that one of its roles is to play mp3s for me.  I just want to set it straight.
Chromium Version:  18.0.1025.168 (Developer Build 134367 Linux) Ubuntu 11.10
Answer: This option does not exist, and from what I gather it is intentionally left out and will not be added.
You can alt-click any link to store the file directly, disregarding its type (mp3, avi, pdf, html, ...).
It was of course not confirmed, but supposedly, this is done to keep the user inside the browser and extend the browsers control of the user. Reading the EULA supports this.
Comment: Further reading: https://code.google.com/p/chromium/issues/detail?id=176790
Answer: You should be able to, but I think its a bug.  If you type about:plugins in the address bar, and disabled the mp3 plugin it will not work.  I have tried it.  You can try it yourself and see.  In the mean time a workaround is to right-click the file and choose save link as, and that will do it.
Comment: I didn't have an mp3 plugin entry, but I just moved everything out of /usr/lib/mozilla/plugins to be certain.  This leaves "Remoting Viewer" as the sole entry in about:plugins, but the problem persists.
Comment: I completely agree with you, though, that this is buggy behavior - any idea where the bugreport is?


React-Redux: mapStateToProps not updating with individual properties, but does connect when I map entire state/store

Question: When I map a state to props for a specific component, the individual props don't seem to update even though the state changed. And when I map the entire state to the component, I get the behaviour I want (because the state has changed).  See below.
const Dashboard = ({ state, justMarkets, justItems }) => {
  console.log('state', state);
  console.log('state markets', state.markets);
  console.log('just markets', justMarkets);

  console.log('state items', state.items);
  console.log('justItems', justItems)
  const markets = state.markets,
        items = state.items;
  return (

      {
        markets
           .filter(market => market.hasItems)
           .map(market => {
                const {
                    marketname: name,
                    id,
                    Products,
                    Address,
                    GoogleLink
                } = market;

                return (

{name}

{Address}

                        View in Google Maps

                      <Items items={items} products={Products} />

                );
            })
         }

    );
};

const mapStateToProps = state => ({
     state,
     justMarkets: state.markets,
     justItems: state.items
});
export default connect(mapStateToProps, null)(Dashboard);

If you see this image, you will notice that when the state is updated, I can only access the updated state from within the component with state.markets and state.items. I can't seem to get access to them directly in the mapStateToProps (both justMarkets and justItems remain empty arrays after state is updated).  Would appreciate any insight into this matter!!!
Comment: Seems pretty odd. Is it possible that you're accidentally overwriting the props somewhere else? I mean if you for some reason has code like ``.
Comment: I figured it out!  I forgot that redux shallow checks.  In the reducer, I had return Object.assign(state, newPropObj) instead of Object.assign({}, state, newPropObj), so technically it was as if the pointer to the state object had never changed.  Thank you for your help!
Comment: Oh, I see. Tricky! Nice that you found the bug! I recommend that you post that as an answer and (after 48 hours) accept your own answer, for future readers. https://stackoverflow.com/help/self-answer
Answer: Figured it out!  The problem was actually in the reducer.  In the reducer, my code was written as:
return Object.assign(state, action.propObj)

when it should have been
return Object.assign({}, state, action.propObj)

Ahh, semantics.  I thought Object.assign returned a new object on its own, but, having read the docs, I now know that it returns the first argument.
So this was essentially a classic mutability bug.  I was overwriting the properties of the state object and returning the previous state with the updated property.  As redux shallow checks for changes and the pointer to the state object had not changed, my state updates were not being registered in the mapStateToProps, but I could access the property directly off the state in my component.
Comment: Thanks bro... this thing was killing me


Make JAWS read page title programmatically when loading new content

Question: I've inherited a project that uses a lot of click-triggered JS to change page content instead of linking to different actual HTML pages. I'm being asked to make JAWS read the page title when this happens, as if a new page is being loaded.
From my observations and a bit of light testing, reading the page title (meaning the contents of the <title> tag) is standard behavior for JAWS when linking to a new, separate page (as in a foo.html file), but not what happens when a same-page link or button is clicked.
How can I cause JAWS to read a page's title after a link or button is clicked that changes the existing page's content in a way that seems like a new page to the user but is actually the same file under the hood?
For this question, please assume that refactoring what I have to use an actual new page instead of JS content replacement is not an option. And if something is wrong with my initial assumptions, please let me know that as well.
Answer: It sounds like you have a single page app (SPA).  You can't force the <title> element itself to be read but if you also put the same text into an aria-live="polite" container (a visually hidden
 or  (*)), it'll be read.
You still want to update the title, even if it's not read, because the screen reader user can use a shortcut key (INS+T with jaws) to read the page title.  And when the user switches between the browser and another app and then back again, they'll hear the title, so it's still important to update the title.
There are some decent blogs regarding accessible SPAs:

Accessible page titles in a Single Page App talks specifically
about the page title in SPAs
Building Accessible Single Page
Apps talks about general principles but doesn't really have any
code examples
Single page applications, Angular.js and accessibility talks specifically about using angular but the concepts and code examples can be applied generically.

(*) Note, when visually hiding the aria-live region, don't use CSS display:none because that'll hide it from the screen reader too.  Use a sr-only type class.  See What is sr-only in Bootstrap 3?
Comment: Just another instance of what should be out of the box / configurable screen reader behaviour falling into the laps of web developers to implement ugly code-polluting workarounds.
Answer: There's good info in slugolicious's answer. The specific issue has a simpler solution, though: <title> elements can be ARIA-ified.
<title role="banner" aria-live="polite">Default title here</title>

in conjunction with
$(function() {
    // existing logic here

    $(title).html("New title here");
});

being called when the new content loads.
Comment: This needs to be unmarked as the answer: https://w3c.github.io/html-aria/#el-title


Relation between components

Question: I have two stateful components:Grid and Item.Item is rendering by Grid and have props which reference to method (handler) defined in Grid <Item example={this.props.inGridHandler} />
Ok. But what if I have third stateful component let's name it Handy and I want that inGridHandler is defined not in Grid component as before but in Handy. How to achieve this with preserving all this structure ?
class Grid extends Component{

ingridHandler=()=>{
console.log('I want to be  defined in Handy Component, not here');
}

Render(){
Return(
`<Item example={this.inGridHandler} />`
);

}
};
export default Grid;

class Handy extends Component{

inGridHandlerWantToBeDefinedHere=()=>{
console.log("I want to be defined here and pass to Grid component as props of Item component which is rendered there'
}

render(){

return(

)
}

}

Comment: Hello. As its current shape, your question does not mean much for the ones who want to help you. Please share some code with us. It is better if it would be a working example. If you don't provide those possibly your question will be voted for closing.
Comment: Your question is ambiguous. How is `Handy` going to look like. Is `Grid` always going to render `Item`. From what you are saying `Item` should be reusable in both `Grid` and `Handy`. Thats the only thing i see.
Comment: Let me try to understand you. You want to define `ingridHandler` handler in the `Handy` component and pass this to the `Grid` component, right? If this is what you want you should render `Grid` in the `Handy` component.
Comment: @devserkan Not exactly. I want to define ingridHandler handler in Handy component and use it in Item component BUT Item Component must be rendered inside Grid Component. All my problem comes with that I want to use handler from another Component to this in which my Item is rendered.
Comment: Again, you can pass it to `Item` from `Grid`. `Handy` renders `Grid` and pass the handler, `Grid` renders `Item` and pass the handler as `handler={this.props.ingridHandler}`. I don't know what is the point of this logic but if you don't want to pass the props all the way down like here, you can change your logic maybe. Using a container component, using context API or maybe using render props. If you are learning React and new to this, just try to think a little bit simple at first.
Comment: @devserkan thank you very much. I'm new to React and I wanted create main component in which I will be render all other components without much logic but it turned out one of them need to use handler which comes from another component, I didn't want to write it in that "grid" component.
Comment: You are welcome. Yes, sometimes we need to pass some props a few levels deep. This is a common issue in React and there are some good approaches for this. As you study and look at other people's code, tutorials you can see those. But first, just digest the basics. Oh, by the way, try to use a linter :) Good luck.
Answer: Here is what you want if I understand you right. This is a very simple process. You are just passing the props all the way down. But, as I try to explain in my comments in the future you should think better approaches if you don't want to pass the props like this.

class Handy extends React.Component {
  inGridHandler = () => {
    console.log("ingridhandler");
  };

  render() {
    return <Grid inGridHandler={this.inGridHandler} />;
  }
}

class Grid extends React.Component {
  render() {
    return <Item inGridHandler={this.props.inGridHandler} />;
  }
}

const Item = props => (
  <button onClick={props.inGridHandler}>Click me and look the console.</button>
);

ReactDOM.render(
  <Handy />,
  document.getElementById("root")
);

Relation between components


How to know if there are real solutions or not?

Question: Consider the following system of equations:
$$\begin{cases}
1 + 6(x+y) + 8xy = 0 \\ y = 6x^2 - 8 xy^2
\end{cases}
$$
If for example from the first one I solve for $x$, and then I substitute into the second one I get a fourth-degree equation, even a bit painful since it's also complete.
I checked with some program, and I found out that there are four solutions in $\mathbb{C}$, and I mean strictly complex conjugate.
My question is: is there some smart way to figure out in advance, and without programs, if there are no real solutions in this case?
Comment: Regarding a question you posted and then deleted, about a solution to $xy-yx=1$ in quaternions, see [this](https://math.stackexchange.com/questions/994931/in-a-noncommutative-ring-is-there-always-a-pair-x-y-such-that-xy-yx-1)
Answer: Substituting $y=-\frac{2(4x+3)}{6x+1}$ the system reduces to one equation, namely to
$$
0=64x^4 + 48x^3 + 28x^2 + 6x + 1=(16x^2 + 4x + 1)(4x^2 + 2x + 1).
$$
It is easy to see that the two quadratic equations don't have real solutions. The decomposition can be found by writing $(16x^2+ax+b)(4x^2+cx+d)$ and comparing coefficients.
Comment: Ah, I have to learn to fatorise like this... Thank you!
Answer: After seeing OP's comment to the answer posted by @DietrichBurde, we decided to show how to do the same without factorising. Please note that this is not an attempt to belittle the mentioned answer.
The two equation can be written as,
$$1+8xy=-6\left(x+y\right)\qquad\text{and}\tag{1}$$
$$y\left(1+8xy\right)=-6x^2.\qquad\qquad\enspace\tag{2}$$
After substituting (1) in (2), we can simplify it to get,
$$x^2+y^2+xy=0.\tag{3}$$
After adding $xy$ to both sides of (3), we have,
$$\left(x+y\right)^2=xy.\tag{4}$$
We can use (4) to replace $xy$-term in (1).
$$8\left(x+y\right)^2+6\left(x+y\right)+1=0\tag{5}$$
From (5), we obtain
$$x+y=-\dfrac{1}{4} \quad\text{or}\qquad  x+y=-\dfrac{1}{2}.$$
Using these values of $x+y$ in (4) gives,
$$xy=\dfrac{1}{16} \quad\text{or}\qquad  xy=\dfrac{1}{4}.$$
Assuming $x, y\ne 0$, we can obtain the following pair of equations.
$$x+\dfrac{1}{16x}+\dfrac{1}{4}=0\quad\longrightarrow\quad 16x^2+4x+1=0$$
$$x+\dfrac{1}{4x}+\dfrac{1}{2}=0\quad\enspace\longrightarrow\quad\enspace 4x^2+2x+1=0$$
These are the two quadratic factors Dietrich Burde has given in his answer.
Comment: Note that from $x^2+y^2+xy = 0$, you can conclude that the only real solutions are $x = y = 0$, which doesn't satisfy the original system, hence there are no real solutions. So your observation about $1+8xy$ greatly simplifies the problem, without having a bunch of tedious algebraic calculations.
Answer: Let $(x,y)$ a solution. If we assume $y=0$, we easily arrive at a contradiction so $$y\neq 0$$
We have $$\begin{cases} -8xy=1+6x+6y \\ -8xy^2=y-6x^2 \end{cases}\implies \begin{cases} -8xy^2=y+6xy+6y^2 \\ -8xy^2=y-6x^2 \end{cases}$$
So finally , $2y=x$ And I'll let you go on
Comment: Ooops : I made a mistake: we can't get $x=2y.$ Maybe we can save anyway.


Custom NSURLProtocol slower after switching NSURLConnection to NSURLSession

Question: I have a custom NSURLProtocol ("UrlProtocol") written to intercept requests from a UIWebView when navigating to specific websites, and apply an extra HTTP header before being sent. I followed https://www.raywenderlich.com/59982/nsurlprotocol-tutorial for a working class. My problem comes with switching from the deprecated NSURLConnection to NSURLSession: I tested an extremely simple one-file html page, which loaded successfully. However, slightly more complex sites with resources like js files, images, etc. will timeout, whereas using NSURLConnection the entire site will load within a few seconds.
I'll paste the original UrlProtocol using NSURLConnection, then the new class using NSURLSession. The original:
#import "UrlProtocol.h"
#import "Globals.h"

@implementation UrlProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    if (![request.URL.absoluteString hasPrefix:@"http"]) return NO; //No need to intercept non-http requests

    if ([NSURLProtocol propertyForKey:@"handled" inRequest:request]) {
        return NO;
    }

    return YES;
}

+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    NSString* key = @"custom-auth-header";
    Globals* globals = [Globals getInstance];
    NSString* token = [globals token];

    NSMutableURLRequest *newRequest = [request mutableCopy]; //Create a mutable copy that can be modified
    [newRequest setValue:token forHTTPHeaderField:key];

    return [newRequest copy]; //return a non-mutable copy
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b {
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading {
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:@"handled" inRequest:newRequest];

    self.connection = [NSURLConnection connectionWithRequest:newRequest delegate:self];
}

- (void)stopLoading {
    NSLog(@"stopLoading");
    [self.connection cancel];
    self.connection = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.client URLProtocolDidFinishLoading:self];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    [self.client URLProtocol:self didFailWithError:error];
}

@end

The new UrlProtocol using NSURLSessionDataTasks for every request:
#import "UrlProtocol.h"
#import "Globals.h"

@implementation UrlProtocol

+ (BOOL)canInitWithRequest:(NSURLRequest * _Nonnull) request {
    if (![request.URL.absoluteString hasPrefix:@"http"]) return NO; //No need to intercept non-http requests

    if ([NSURLProtocol propertyForKey:@"handled" inRequest:request]) {
        return NO;
    }

    return YES;
}

+ (NSURLRequest * _Nonnull)canonicalRequestForRequest:(NSURLRequest * _Nonnull)request {
    NSString* key = @"custom-auth-header";
    Globals* globals = [Globals getInstance];
    NSString* token = [globals token];

    NSMutableURLRequest *newRequest = [request mutableCopy]; //Create a mutable copy that can be modified
    [newRequest setValue:token forHTTPHeaderField:key];
    return [newRequest copy]; //return a non-mutable copy
}

+ (BOOL)requestIsCacheEquivalent:(NSURLRequest * _Nonnull)a toRequest:(NSURLRequest * _Nonnull)b {
    return [super requestIsCacheEquivalent:a toRequest:b];
}

- (void)startLoading {
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:@"handled" inRequest:newRequest];
    [Globals setUrlSessionDelegate:self];
    Globals* globals = [Globals getInstance];
    self.dataTask = [globals.session dataTaskWithRequest:newRequest];
    [self.dataTask resume];
}

- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nullable)dataTask didReceiveData:(NSData * _Nullable)data{
    [self.client URLProtocol:self didLoadData:data];
}

- (void)URLSession:(NSURLSession * _Nonnull)session dataTask:(NSURLSessionDataTask * _Nullable)dataTask didReceiveResponse:(NSURLResponse * _Nullable)response
                 completionHandler:(void (^ _Nullable)(NSURLSessionResponseDisposition))completionHandler{
    [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task didCompleteWithError:(NSError * _Nullable)error{
    if (error){
        [self.client URLProtocol:self didFailWithError:error];
    } else {
        [self.client URLProtocolDidFinishLoading:self];
    }
}

- (void)URLSession:(NSURLSession * _Nonnull)session task:(NSURLSessionTask * _Nonnull)task willPerformHTTPRedirection:(NSHTTPURLResponse * _Nonnull)response
                        newRequest:(NSURLRequest * _Nonnull)request completionHandler:(void (^ _Nonnull)(NSURLRequest * _Nullable))completionHandler {
    completionHandler(request);
}

- (void)stopLoading {
    [self.dataTask cancel];
    self.dataTask = nil;
}

@end

"Globals" is a singleton where I have initialized one NSURLSession meant to be used throughout the runtime of the app. It also contains the token I set as a custom HTTP header for all requests:
#import "Globals.h"
#import "UrlProtocol.h"

@implementation Globals
@synthesize token;
@synthesize session;

static Globals *instance = nil;

+(Globals*) getInstance
{
    @synchronized(self)
    {
        if (instance == nil)
        {
            instance = [Globals new];
        }
    }
    return instance;
}

//UrlProtocol class has no init method, so the NSURLSession delegate is being set on url load. We will ensure only one NSURLSession is created.
+(void) setUrlSessionDelegate:(UrlProtocol*) urlProtocol{
    Globals* globals = [Globals getInstance];
    if (!globals.session){
        globals.session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration  delegate:urlProtocol delegateQueue:nil];
    }
}

@end

Answer: Solved my problem by creating a new default NSURLSession for each NSURLSessionDataTask. Something was wrong with the way I was trying to share one NSURLSession for all my tasks. URLProtocol's startLoading method is now as follows:
- (void)startLoading {
    NSMutableURLRequest *newRequest = [self.request mutableCopy];
    [NSURLProtocol setProperty:@YES forKey:@"handled" inRequest:newRequest];
    NSURLSessionConfiguration* config = NSURLSessionConfiguration.defaultSessionConfiguration;
    NSURLSession* session = [NSURLSession sessionWithConfiguration:config  delegate:self delegateQueue:nil];
    self.dataTask = [session dataTaskWithRequest:newRequest];
    [self.dataTask resume];
}

The simple HTML page test before must have worked because only one task was needed to load the page


Different behaviour on iPhone and iPad

Question: I have a UITextView for which I want left/right/top/bottom content margins and the code I used is:
<code>// Set the paddings
UIEdgeInsets aUIEdge = [aTextView contentInset];
aUIEdge.left = 15;
aUIEdge.right = 15;
aUIEdge.top = 10;
aUIEdge.bottom = 10;
aTextView.contentInset = aUIEdge;
</code>
But this gives me correct output in iPhone and not in iPad. What to do, give some clue?
Comment: Just select the code parts and press the `010` button to get it formatted. Use the *preview* to check it before posting.
Comment: What do you mean by right or wrong?
Answer: It worked with a IF statement:
    // Set the paddings
    UIEdgeInsets aUIEdge = [aTextView contentInset];
    if (<>) {
        aUIEdge.left = 15;
        aUIEdge.right = 10;
    }
    else {
        aUIEdge.left = 5;
        aUIEdge.right = 15;
    }

Different behaviour on iPhone and iPad


Using one jumper wire between two light switches connections please

Question: Which screw do I use ( top or bottom) for a jumper wire connecting two light switches
Comment: Are you trying to operate a light fixture from two independent switches? If so, you need to understand 3 way switches.
Answer: You need to use the one with the permanent live.
The switches don't care which end you use, but if you connect to the switched live side you'll be switching both circuits at once, the second switch would then only work when the first was on.
I'm assuming this is in one switch unit, feeding two lamps from the same incoming live. If it's for a 2/3/4-way switch, you need to clarify.
Answer: If it is a single pole switch you can use either screw.  The switch simply opens or closes a circuit.
Answer: The switches do not care.
Top or bottom or even top to bottom on the other switch.
I believe most simple switches use the bottom for hot and top for switch hot.  Switch is on when flipped/pushed up.


How are django templates parsed?

Question: I have been trying to learn more about Django's templating engine as it's always seemed like a bit of a black box to me. The documentation gives a good outline of the general steps involved and indicates that the template is loaded and parsed, creating a tree of nodes that are rendered (in a cascade?) with a context and appended together to give the result.
What I don't understand is the approach to parsing, and under what criteria the nodes are created? What constitutes a particular node after parsing, and how does this effect the creation of custom template tags (i.e. is there a better and more efficient way to write template tags that would lead to less nodes?).
Comment: I started reading `django.template.base` but got out as soon as I sensed powerful, time bending magic (like goto 5am). I'll upvote and check in the morning instead :)
Answer: One way of understanding more about the process is to run django with the werkzeug debugger, and trigger an exception in a template. That way, you will be able to view (and interact) with the whole stack up to that point.
Answer: A node is created out of every tag. You can get an idea how it works by reading through how to write custom tags. Anything which is inside the tag will be its children. Here is an example of a comment tag from django docs:
def do_comment(parser, token):
    nodelist = parser.parse(('endcomment',))
    parser.delete_first_token()
    return CommentNode()

as you see comment tag will parse everything until the "endcomment" and will throw it away. Other tags would pass nodelist to SometagNode() and will use it for rendering.
Rendering is done recursively. When a render() is called on node it runs render on its children and so on.
Parsing is done recursively as well this is why you can get nested tags and parser.parse() will manage to find the proper matching closing tag, because when it does parsing and stumbles on a tag it calls do_tag() thing, which in turn will call the parser.parse() again to find the nearest closing tag and will wrap everything into a node, return a node, the higher parser.parse() will put it on a node list and will continue to search for the closing tag.
Context object in nodes is a kind of list of dicts structure. Extra context is pushed on top of existing context and passed to children nodes and popped out after node is rendered so that it wouldn't effecting upper scope.
For tags which don't have children the parser.parse() is not used, and so node instance is returned without any children.
Answer: I think that first thing you should look at is code.djangoproject.com
with django/template/base.py - the first (as Yuji Tomita stated before). Or download sources and look through it with your favorite editor or IDE.
Answer: I guess they use tokenizing and parsing
a simple way to discribe is:
Tokenizing:
break appart the code to types like:
integer foo = "bar" + 15;

this consists of
T_VARIABLETYPE  + T_VARIABLENAME  + T_EQUALS + T_STRING + T_PLUS + T_DIGIT + T_SEMI

after this you can parse by trying to find patterns with a parser
parsing:
find the pattern:
T_VARIABLETYPE  + T_VARIABLENAME  + T_EQUALS + {A recursive thing} + T_SEMI

This way you can execute a command
If you like to experiment with this i could recomend to use "ANTLR" http://www.antlr.org/
Its available in lot of different languages like Java or C# and even PHP and JS

How are django templates parsed?


Java internal panels not opening when menuItems clicked

Question: I'm trying to build a small little program that has 3 menu items on it, Student, University, and Exit. I have it pretty much finished, it compiles but the student and university menu items fail to open the Internal java panel.
Its an extra credit question for my Java 2 Review (I really need the points)
The Assignment question reads as:
Write a program that builds a desktop application with a menu that has a panel for University and a panel for Student. The University panel has name and state code.  The Student panel has name and id.   The user can type in the name and either the code or id for University or Student, respectively.  Each panel has a submit button that accepts the data, clears the fields, and resets focus.  Each panel has a check input method.  Id is an integer.  The university or student data is placed in their respective arraylist.
I have a working example that I based this one off of, and can't figure out where I've gone wrong. The panels will not open when Student and University are clicked.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

public class Question4 extends JFrame
{
    private JDesktopPane theDesktop;
    ArrayList<Student> studentList = new ArrayList<Student>();
    ArrayList<University> universityList = new ArrayList<University>();

    public static void main(String args[])
    {
        Question4 q4 = new Question4();
        q4.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        q4.setSize(400,400);
        q4.setLocationRelativeTo(null);
        q4.setVisible(true);
    }

    public Question4()
    {
        super("Question 4");
        theDesktop = new JDesktopPane();
        JMenuBar bar = new JMenuBar();
        JMenu menu = new JMenu("Menu");
        JMenuItem studentItem = new JMenuItem("Student");
        JMenuItem universityItem = new JMenuItem("University");
        JMenuItem exitItem = new JMenuItem("Exit");

        exitItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                System.exit(0);
            }
        });

        studentItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JInternalFrame sFrame = new JInternalFrame("Student",true,true,true);
                AddStudentPanel sPanel = new AddStudentPanel();
                sFrame.add(sPanel);
                sFrame.pack();
                theDesktop.add(sFrame);
                sFrame.setVisible(true);
            }
        });

        universityItem.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                JInternalFrame uFrame = new JInternalFrame("University",true,true,true);
                AddUniversityPanel uPanel = new AddUniversityPanel();
                uFrame.add(uPanel);
                uFrame.pack();
                theDesktop.add(uFrame);
                uFrame.setVisible(true);
            }
        });

        menu.add(studentItem);
        menu.add(universityItem);
        menu.add(exitItem);

        bar.add(menu);

        setJMenuBar(bar);
        add(theDesktop);
    }

    private class AddStudentPanel extends JPanel
    {
        private JLabel nameLabel;
        private JLabel idLabel;
        private JLabel submitLabel;
        private JTextField nameField;
        private JTextField idField;
        private JButton submitButton;

        public AddStudentPanel()
        {
            setLayout(new GridLayout (3,2));

            nameLabel = new JLabel("Enter Name");
            idLabel = new JLabel("Enter ID");
            submitLabel = new JLabel("Submit");

            nameField = new JTextField(15);
            idField = new JTextField(15);

            StudentHandler sHandler = new StudentHandler();
            submitButton.addActionListener(sHandler);

            add(nameLabel);
            add(nameField);
            add(idLabel);
            add(idField);
            add(submitLabel);
            add(submitButton);
        }

        class StudentHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent ae)
            {

                if(ae.getSource() == submitButton)
                {
                    if(checkStudentInput())
                    {

                        studentList.add(new Student(nameField.getText(),Integer.parseInt(idField.getText())));
                        nameField.setText("");
                        idField.setText("");
                        nameField.requestFocus();
                    }
                }
            }

            public boolean checkStudentInput()
            {
                boolean input = true;

                if(nameField.getText().isEmpty())
                {
                    JOptionPane.showMessageDialog(null,"Please enter a name");
                    nameField.requestFocus();
                    input = false;
                }
                else if(idField.getText().isEmpty())
                {
                    JOptionPane.showMessageDialog(null,"Please enter an id");
                    idField.requestFocus();
                    input = false;
                }
                else
                {
                    try
                    {
                        Integer.parseInt(idField.getText());
                    }catch(NumberFormatException nfe)
                    {
                        JOptionPane.showMessageDialog(null,"Please enter an integer for id");
                        idField.setText("");
                        idField.requestFocus();
                        input = false;
                    }
                }

                return input;
            }
        }
    }

    private class AddUniversityPanel extends JPanel
    {
        private JLabel nameLabel;
        private JLabel codeLabel;
        private JLabel submitLabel;
        private JTextField nameField;
        private JTextField codeField;
        private JButton submitButton;

        public AddUniversityPanel()
        {
            setLayout(new GridLayout (3,2));

            nameLabel = new JLabel("Enter Name");
            codeLabel = new JLabel("Enter State Code");
            submitLabel = new JLabel("Submit");

            nameField = new JTextField(15);
            codeField = new JTextField(15);

            UniversityHandler uHandler = new UniversityHandler();
            submitButton.addActionListener(uHandler);

            add(nameLabel);
            add(nameField);
            add(codeLabel);
            add(codeField);
            add(submitLabel);
            add(submitButton);
        }

        class UniversityHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent ae)
            {

                if(ae.getSource() == submitButton)
                {
                    if(checkUniversityInput())
                    {

                        universityList.add(new University(nameField.getText(),Integer.parseInt(codeField.getText())));
                        nameField.setText("");
                        codeField.setText("");
                        nameField.requestFocus();
                    }
                }
            }

            public boolean checkUniversityInput()
            {
                boolean input = true;

                if(nameField.getText().isEmpty())
                {
                    JOptionPane.showMessageDialog(null,"Please enter a name");
                    nameField.requestFocus();
                    input = false;
                }
                else if(codeField.getText().isEmpty())
                {
                    JOptionPane.showMessageDialog(null,"Please enter an State Code");
                    codeField.requestFocus();
                    input = false;
                }
                else
                {
                    try
                    {
                        Integer.parseInt(codeField.getText());
                    }catch(NumberFormatException nfe)
                    {
                        JOptionPane.showMessageDialog(null,"Please enter an integer for State Code");
                        codeField.setText("");
                        codeField.requestFocus();
                        input = false;
                    }
                }

                return input;
            }
        }
    }
}

Answer: Change the line
add(theDesktop);

to
setContentPane(theDesktop);

and you should be able to continue.
You will also need to initialize the submitButton in both AddStudentPanel and AddUniversityPanel to avoid a NullPointerException.
submitButton = new JButton()

Hope this helps you along the way to finish your assignment.
Comment: The submit button was the issue, I can't believe I overlooked initializing it. Just needed a second set of eyes.

Thank you!
Comment: You're welcome. I thought you had to use `setContentPane`, but apparently `add` works as well. :)


Generator of the fundamental group of $ \mathbb RP^{2}$.

Question: Take a closed hemisphere and identify the antipodal points on the equator ,we get $\mathbb RP^{2}$ and inside $ \mathbb RP^{2}$ we have copy of $ \mathbb RP^{1}$.So, what will be the induced map on fundamental group induced by inclusion?
I think ,if we know which homotopy class of loop in $\mathbb RP^{2}$ is generator,then some conclusion can be said easily.
Comment: Draw a line of longitude on the hemisphere.  Notice that since you're identifying points on the equator, this is actually a closed curve.  *That* is the generator of $\pi_1$.
Comment: @JasonDeVito: Thanks a lot.
Answer: I guess I might as well answer here to keep this from being bumped:
If you draw a line of longitude on the hemisphere, this is actually a closed curve due to the identification you make on the equator.  It will generate $\pi_1(\mathbb{R}P^2$.
Comment: It seems intuitive to me, but how do you show that it is not path homotopic to the constant loop?
Comment: The easiest way, I think, is to note that it lifts to a non-closed curve in $S^2$.


While loop does not update value

Question: I'm new to Python and recently cannot work well with while loop - the variable did not update new value!
I created a while loop within which URL shall be updated when found another URL. I also add a 'times' variable to test the number of time the loop do. (count = 4 => the last version times = 4). However, 'times' did change but URL just change 1 time.
URL = input('Enter - ')
count = input('Enter count: ')
pos = input('Enter position: ')

times = 0
links = list()
while times < int(count):
    html = urlopen(URL, context=ctx).read()
    soup = BeautifulSoup(html, "html.parser")

    tags = soup('a')
    for tag in tags:
        link = tag.get('href',None)
        links.append(link)
    URL = links[int(pos) - 1]
    times = times + 1
name = re.findall('known_by_(.+).html',URL)
print(name)

I expect the URL to be updated and the loop ran again for 4 times but only get the result of the first loop run time. Meanwhile the 'times' variable got added enough 4 times.
Comment: I also suggest you to use more 'Pythonic' loops:

`for _ in range(int(count)):`

It will allow you not to use `times` variable, so you will have less places where you can have a potential error.
Answer: Your loop looks like it should run count times, doing the exact same thing each time. However, the last two lines are not indented, so they are outside the loop. That means they will only run once, when the loop has finished.
If you want to run the last two lines each time the loop runs, you need to indent them to the same level as times = times + 1.

While loop does not update value


Comparing percentages of a sample to that of the population.

Question: This might be stupid question, but I'm in this sort of situation:
60% of people in a city have a pet cat, but the national rate is 50%.
So, assuming we have the required bits of information about the population/sample, are there any meaningful ways are there to compare these two percentages?
Answer: One direct comparison: an average person in this city is 20% more likely to have a pet cat than the average national


Lazy.js based fibonacci to map Bacon.js interval?

Question: I have a code to generate fib sequences with lazy.js
var fibF = function()
{
  var seq = []; //build sequence array in this closure
  var f = function(n)
  {
    var val;
    if (n <= 1)
    {
      val = 1; // as the Fib definition in Math
    }
    else
    {
      val = seq[n - 2] + seq[n - 1]; // as the Fib definition in Math
    }
    seq[n] = val;
    return val;
  };
  return f;
}();

var fibSequence = _.generate(fibF);

/*  just for test
var fib_1000 =
  fibSequence
  .take(1000)
  .toArray();

console.log(fib_1000);
//[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,...........,4.346655768693743e+208 ]

*/

At the same time, I have a code of timer with Bacon.js
var B = require('baconjs');

var timeSequence = B
      .interval(1000); //every second

timeSequence
    .onValue(function()
      {
        console.log(require('moment')().format('MMMM Do YYYY, h:mm:ss'));
        // print timestamps every second
      });

Then,
I want to map the the fibSequence onto timeSequence  such as
var mySequence = fibSequence.map(timeSequence);
or
var mySequence = timeSequence.map(fibSequence);
Is it possible?
If so, please show me the way.
Any workaround solution is welcome.
Thanks.
EDIT working code:
//to simplify use Natrual, instead of Fib

var _ = require('lazy.js');
var __ = require('baconjs');

var natural = function(n)
{
  return n;
};

var _natural = _.generate(natural); //natural numbers
var __timer = __.interval(1000); //every second

var map_to__ = function(_seq, __seq)
{
  var it = _seq.getIterator();

  var sequence =
    __seq
    .map(function()
    {
      it.moveNext();
      return it.current();
    });

  return sequence;
};

var __mappedTimer = map_to__(_natural, __timer);

__mappedTimer
  .onValue(function(x)
  {
    console.log(x); // print every second
  });

Answer: I'm not sure whether this is the intended use of iterators, but it should work:
var it = fibSequence.getIterator()
var mySequence = timeSequence.map(function() {
    return it.moveNext() && it.current();
});

Comment: Thanks I sort of get the idea, but still not working , please see my Q edit.
Comment: Hm, I've tested it online now and it works. What exactly is the error you get?
Comment: .onValue(function(x)
   ^
TypeError: Object object has no method 'onValue'
Comment: So, seems `mySequence` is not Bacon object, I thought.
Comment: As I said, [I cannot reproduce](http://jsfiddle.net/V9h83/) (with your code). There must be something else you're doing wrong, yes.
Comment: You said, you've tested in online now and it works, but the jsFiddle http://jsfiddle.net/V9h83/ does not work since it uses hotlink of github.
Comment: So, I upload lazy, bacon lib files to my own github.io page, and linked them. Now it works. http://jsfiddle.net/Uq2Jt/ Thanks.
Comment: However, the strange thing is once I made the same code to node.js, the error occurred. I do not know why.
Comment: Sorry, I deifined Obj.map in another place, and which conflicts in the code. works. I update my Q. Appreciated.


External HDMI monitor blinking after upgrade to 16.04

Question: I'm getting many issues after upgrade to 16.04 in my Dell 15R 5537.
Today I was unable to watch movies as I used to do with 15.10 in my Sony 42' TV with resolution of 1290x1080 using HDMI cable.
Now as soon as I move to the external display the tv starts to blink. :(
I tried to lower the tv resolution to 1280x720. It worked only when both displays are active. When I set the mode where only the tv is active it also blinks.
Another way to make the tv stop to blink was selecting the mirror mode.

lspci | grep VGA :

00:02.0 VGA compatible controller: Intel Corporation Haswell-ULT Integrated Graphics Controller (rev 09)
03:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Venus PRO [Radeon HD 8850M / R9 M265X] (rev ff)

xrandr -q

Screen 0: minimum 8 x 8, current 1366 x 768, maximum 32767 x 32767
eDP1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1366x768      60.04*+  40.05
   1360x768      59.80    59.96
   1280x720      60.00
   1024x768      60.00
   1024x576      60.00
   960x540       60.00
   800x600       60.32    56.25
   864x486       60.00
   640x480       59.94
   720x405       60.00
   680x384       60.00
   640x360       60.00
DP1 disconnected (normal left inverted right x axis y axis)
HDMI1 connected (normal left inverted right x axis y axis)
   1920x1080     60.00 +  50.00    59.94    30.00    24.00    29.97    23.98
   1920x1080i    60.00    50.00    59.94
   1280x1024     60.02
   1280x720      60.00    50.00    30.00    59.94    29.97    24.00    23.98
   1024x768      60.00
   800x600       60.32
   720x576       50.00
   720x576i      50.00
   720x480       60.00    59.94
   720x480i      60.00    59.94
   640x480       60.00    59.94

could someone give a clue what is going on?
thanks
Comment: Can you post the output of `xrandr -q`?
Comment: @fakedad. Hi, I edit and added what you have requested.
Comment: Have you tried [adjusting the refresh rate](http://askubuntu.com/questions/147580/how-to-see-change-screen-refresh-rate-or-monitor-frequency)?
Comment: @fakedad. no, but I will. do you suggest any value?
Comment: I tried this: xrandr --output HDMI1 -s 1920x1080 -r 50
but I can't see the '+' or '*' to change. Am I doing it right?
Comment: I would see what the maximum supported refresh rate for the TV you're using is by looking at the specs online. Many older TVs (and, I imagine, some newer ones) don't support very high refresh rates. Also, you may want to try lower resolutions, like 1280x720 (as you mentioned earlier) in addition to lower refresh rates.
Comment: But what I'm not understanding is that this have been working since version 14.04. I never need to use xrandr before.
Is the command that I'm using right?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/44021/discussion-between-fakedad-and-cristiano).
Answer: Don't know what was changed in version 16.04, but I found that the blink is cause by an unsupported resolution.
I found that setting resolution/rate values using randxr is not doing any effect. Don't know the reason.
What I had to do was change resolution and rate values in the ~/.config/monitors.xml file and then restart the machine.
After that I was able to watch my movies in my tv again.
Thanks to @fakedad !!!
Comment: Xfce configuration file location: `~/.config/xfce4/xfconf/xfce-perchannel-xml/displays.xml`


Docker-compose volume doesn't work as expected

Question: I'm trying to mount a volume via docker-composer but after running docker-compose up the directory is empty.
Dockerfile
FROM alpine:3.8

COPY test.txt ./app/

docker-compose.yml
version: "3.7"

services:
  test:
    image: myrep/image:latest
    volumes:
      -  "./app/:/app/"

My procedure:

Build docker image on client (docker build .)
Push docker image to my registry (docker tag xxx myrep/image && docker push myrep/image)
On the server I pull the image (docker pull myrep/image)
Run docker-compose up (docker-compose up)
Then when I look into the app folder there is no test.txt file

Any idea what I'm doing wrong?
Answer: You copied the file into the image, but when you start the container you overwrite it with your directory when mounting it.
If you want the file to be there don't mount the volume.
You can verify this by running the image without a volume and executing:
docker-compose exec test ls -l /app

Comment: You should install [dive](https://github.com/wagoodman/dive) so you can easily debug your images.
Comment: could you explain more how the app older is overwritten by the directory? which directory are u referring to?
Answer: May be you should try to add ./ before test.txt as it is not copying the file to the root directory
Hope it will work for you
    FROM alpine:3.8
    COPY ./test.txt ./app/


Am I an Interactive Designer yet?

Question: What kind of portfolio do I need before I can start calling myself an "Interactive Designer"? I currently design websites, and I've been redesigning our company's flagship sites to improve User Experience... but when can I start calling myself an "Interactive/UX Designer"?
Answer: There is a government agency that you must apply to to receive permission.  Otherwise, the UX police will come and get you.
Seriously, you can say it now.  Wait...  Ok now.
Welcome to the craft.  Read alot.  Spread the word.  Help train others.  Love the user.
Comment: Ha ha. Wait!? What about fees? Are there yearly fees?
Comment: Good news - some one must reviewed the form because you don't have to fill it out in triplicate anymore.
Comment: There's a secret handshake... oh, wait I'm not supposed to say that.
Comment: The handshake is great - you say ACK, they say SYN.  If you say ACKACK you qualify as an alien in "Mars Attacks" :)
Answer: I reckon you can say it once people start paying you for that service. So if you have clients that are buying "interactive design" services from you, you're all set. Mind you, I like Glen's notion of the UX police. I bet they have very nice uniforms.
Answer: You've done some, you have been paid for it, so call yourself it, and be prepared to backup the claim that you are an Interactive Designer when questioned.
Oh, and accept some answers???

Am I an Interactive Designer yet?


Link to file on different server

Question: I am working on a invoice report with my companies intranet. I would like to be able to link the invoice number to the actual invoice. My problem is that the file resides on a different server and not the web server.
When I'm on the computer I have to use the remote desktop connection to access the server to get to the files.
I've tried \SERVER\file_path.pdf and file:\\SERVER\file_path.pdf and neither works.
Comment: Which protocol is the file server using? CIFS?
Comment: SFTP, i think. Does that sound right?
Answer: What you are doing is disabled by design.  This sort of link to a local file will work in some browsers as long as the HTML is also called from a local file (ie file:///pageContainingLink). If not, it's a security vulnerability. It won't work at all in webkit based browsers.
See nchor Link to Local File? (DEAD LINK not working in FireFox but in IE)
And Cross-browser link to file on local system
If you want to get this to work, you'll need the other server to be a web-server too so that you can link to http://intranet2/fileYouWant.pdf
Comment: +1 to Dany who got me thinking, you can't link to the file as is, but if you create a virtual directory and point at the other server, you can provide a plain old link from your webserver.  I don't know what you are running.  I'm out of practice in Apache, but in IIS it's trivial, just right-click on your site root and create a virtual directory.  It's a little old, but here's a link for IIS: http://www.hosting.com/support/dedicated/iis/virtualdirectory
Comment: I'll take a look at the link and try it out.
Answer: Try creating a symbolic link from the network share \SERVER\ to your machine --> X:\pathtoyourapacheroot\distantdocuments on your server machine
Then you should be able to use it just has if your file was on your machine x:\pathtoyourapacheroot\distantdocuments\file_path.pdf.
Comment: Actually, this still won't work as long as the webpage is served anywhere but locally, and only in a couple browsers if it is served locally.  That said, Dany you got my thinker-upper running in a new direction.

Link to file on different server


Why I can't override handleMessage method when I initialize a Handler object?

Question:
It should be like this :
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    }
};

However,in my IDE,it must be overrided like this:
    Handler handler = new Handler() {

    @Override
    public void close() {

    }

    @Override
    public void flush() {

    }

    @Override
    public void publish(LogRecord logRecord) {

    }
};

And it seems that the Handler object here doesn't support such method called "handleMessage".
What should I do?
Comment: Also be sure that you imported the right Handler. There's a `Handler` in java which has a method `handleMessage()` and you'll have to `import javax.xml.ws.handler.Handler;` in order to use that!
Comment: have you tried manually ovveriding handleMessage()? I guess the other 3 methods are automatically created by your IDE because you have to implement them but try to write the override manually
Comment: Could you write the entire import for Handler, it seems like you are implementing java.util.logging.Handler and you want to implement something like javax.xml.ws.handler.Handler
Comment: check your import of Handler
Answer: That's a name conflict between different Handler classes.
The first Handler you mention seems to be a javax.xml.ws.handler.Handler docs or a android.os.Handler doc, both of which have a handleMessage method to override.
The second Handler seems like it is a java.util.logging.Handler docs that has the methods you mention


SQL division by zero when order by price

Question: Why i get division by zero in this SQL?
I tried so much, like cast, NULLIF and that things but nothing works.
$sql = "SELECT *, (cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount FROM products ORDER BY CAST(price AS Float) asc LIMIT $no_of_records_per_page OFFSET $offset";

If i kick out
(cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount

than its working.
But its also working if i kick out
ORDER BY CAST(price AS Float) asc

But i need them all two... i tried so much but cannot fix it...
Comment: Using postgresql
Answer: I'm not sure if this is the most elegant solution, but checking for pricebefore = 0 at the start should fix it...
SELECT *, case when pricebefore = 0
    then 0 --or you might want 1 or 100 here?
    else (cast(price as numeric(20, 4))*100)
 /cast(pricebefore as numeric(20, 4)) - 100 end AS discount
FROM products ORDER BY CAST(price AS Float) asc

Comment: Thank you, that fixed it :)
Answer: you'll get it if pricebefore is zero-ish (anything that gets cast to 0, like "0" or 0 or NULL or "") - if you just want to get rid of the crash, you can use the GREATEST function with 1, like /GREATEST(cast(pricebefore as numeric(20, 4)),1)  - or because of 4 possible decimals, you can use ,0.0001 too, i suppose.. but i doubt your calculations will be accurate afterwards.


Run Python Code to capture live network traffic accessing all users rights

Question: I am working on a virtual Machine by Oracle in Linux and my Linux version is 20.04 LTS and python version is 3.8. I have a python code which is used to capture live network traffic and save in a pcap file. The issue I am facing is that I want to run this code without any root or administrative or without sudo command.
test.py:
import time
from scapy.all import *
import uuid

# IP address to capture packets for
ip_address = "0.0.0.0"

start_time = time.time()
end_time = start_time + 10  # Capture for 10 seconds

# Create an empty list to store the packets
packets = []

def packet_callback(packet):
    if IP in packet:
        packets.append(packet)

# Create a capture filter to capture only packets from the specified IP address
capture_filter = "ip host " + ip_address

sniff(prn=packet_callback, timeout=end_time-start_time, filter= capture_filter)

# Write all the packets to a single pcap file
filename = "/path_to_capture/capture_" + str(uuid.uuid1()) + ".pcap"
wrpcap(filename, packets)
print(len(packets))

I run my code in terminal by writing the following cmd:
sudo python3 test.py

By running this command, my code executes and capture the network traffic and save in a pcap file. But I want to execute my code without sudo or root privileges by writing a simple cmd:
python3 test.py

Kindly provide me the solution to resolve this issue.
Comment: what error do you get when you run it without sudo?
Comment: sniff(prn=packet_callback, timeout=end_time-start_time, filter= capture_filter)
  File "/home/sqit/.local/lib/python3.8/site-packages/scapy/sendrecv.py", line 1263, in sniff
    sniffer._run(*args, **kwargs)

PermissionError: [Errno 1] Operation not permitted
Comment: Sniffing in promiscuous mode requires elevated permissions. You might be able to setup a user group in the OS to allow sniffing but that is not a programming topic anymore.
Comment: So, is there any solution to handle this problem?
Answer: I think that you can use the 'setcap' command in linux.
I have a experience of only 'C' language.
See the below link. (I'm not sure about Python)
https://medium.com/@badbot/safe-packet-capture-python-without-sudo-b08c4c4e531
Comment: Check this link. Good luck. https://stackoverflow.com/questions/36215201/python-scapy-sniff-without-root
Comment: setcap command is used just in case of pcap library but I am using scapy library
Comment: setcap didn't run in case of scapy
Comment: Dear @nevertheless thank you for your cooperation. It really helps me out of this problem


Is it always a tautology?

Question: If any two compound propositions $P$ and $Q$ are equivalent, then is the proposition formed from their biconditional $P \leftrightarrow Q$ always a tautology?
Comment: What is your definition of equivalent propositions?
Comment: @YounisShah What if I told you I asked you a question because I needed you to answer it before I could give you an answer? Also, what if I told you that being sarcastic smart-arse won't get you a lot of friends on this page?
Comment: Yes: $P$ and $Q$ are equivalent when they have the same truth-value : i.e.both are *True* or both are *False*. But in both case the formula $P \leftrightarrow Q$ will be evaluated to *True*; thus, it is a *tautology*.
Comment: @Mauro thanks much. Got it!
Comment: @5xum I'll tell you "my" definition. If you think answering a novice's question with another question and answering with a simple yes or no plus a small explanation are equivalent, then any two compound propositions are equivalent.
Comment: Then you'd be dead wrong.
Comment: @YounisShah Just a warning: it may happen that you will need the help from this site again, maybe even more than once. If you will be rude to one senior user on each of your questions, you may soon notice that you are getting less and less answers from less and less experienced users...
Comment: Alright. I apologize for my behavior.
Answer: Yes; this can be proved using the deduction theorem.
TFAE.

$(P \vdash Q) \wedge (Q \vdash P)$
$(\vdash P \rightarrow Q) \wedge (\vdash Q \rightarrow P)$
$\vdash (P \rightarrow Q) \wedge (Q \rightarrow P)$
$\vdash (P \leftrightarrow Q)$
Comment: The deduction theorem doesn't require that a $\land$ connective exist.  This proof isn't valid for the subsystem of propositional calculus which only has $\rightarrow$ and ↔ as connectives.
Comment: @DougSpoonwood, sounds interesting. Where does one learn about such subsystems? In particular, does the equivalence still hold in the sublanguage/subtheory generated by $\rightarrow$ and $\leftrightarrow$?
Comment: @Goblin To start one's study, one could join any known axiom set for the implicational calculus of propositions to any known axiom set for the equivalential calculus under suitable rules of detachment and uniform substitution... such as the pair {CCCpqrCCrpCsp, EEpqEErqEpr} under the rules {C$\alpha$$\beta$, $\alpha$} $\vdash$ $\beta$, {E$\alpha$$\beta$, $\alpha$} $\vdash$ $\beta$ with uniform substitution for variables.  The equivalence will still hold, since the intended semantics are bivalent.  If the truth value "V" of two propositions is equivalent, then V(p)=V(q).  Now...
Comment: The truth value of an equivalence V(p↔q) is equal to V(p)↔V(q).  So, given that the diagonal of the truth table always evaluates to the designated value, then the equivalence here will hold.  And since the semantics are still two-valued for the subsystem I've described, we have that the diagonal of the truth-table evaluates to the designated value "truth", and thus the equivalence holds.
Answer: No.
I'll define "equivalence" as meaning that two propositions have the same truth-value.
↔ is defined by this table where $F$ indicates falsity, $T$ indicates truth, and $U$ indicates that the truth-value of a proposition takes on some other value than truth or falsity:
<code>↔  F  U  T
F  T  U  F
U  U  U  U
T  F  U  T
</code>
If $P$ has truth value of $U$, and so does $Q$, then $P$ and $Q$ end up equivalent.  $P$ could come as the compound proposition (a↔b) and $Q$ as the compound proposition (a↔b).  However, ($P$↔$Q$) is not a tautology.
Comment: @YounisShah, note that Doug isn't talking about the usual semantics for propositional logic here. Under the usual, classical semantics, the answer to your question is an emphatic "yes."
Comment: Thanks so much for your time. But I didn't understand your answer. Can you please simplify a bit?
Comment: @Goblin what should I learn in order to understand what Doug has answered? Can you point me in the right direction, please?
Comment: @YounisShah, sorry, I do not know much about alternative semantics for the language of propositional logic.
Comment: @Goblin no worries. Cheers.
Comment: @DougSpoonwood can you please help me here?
Comment: @YounisShah Goblin is correct.  If the semantics are bivalent (or equivalently classical), then the answer to your question is an emphatic "yes".  One might consult Merrie Bergmann's book "An Introduction to Many-Valued and Fuzzy Logic" and its references for more on non-classical systems.
Comment: @DougSpoonwood so you mean to say equivalences that hold in classical systems might not hold in fuzzy logic?
Comment: @YounisShah That is true, yes.
Comment: @DougSpoonwood Alright. Isn't there a way to combine the two systems such that equivalences hold in both the systems?
Comment: I mean to say can't we "normalize" a many-valued system to a bivalent system?
Comment: @YounisShah There do exist many-valued systems which have the same tautologies as bivalent systems.  See the Bergmann book and the section on Bochvar's 3-valued systems for an example.  Though, there probably is a greater amount of many-valued systems which have different tautologies than bivalent systems.
Comment: Alright. That really helped. Thank you so much for your time. Proost!

Is it always a tautology?


JQuery: Submiting a form when image clicked doesn't work

Question: I need a form to be submitted when an image with id="searchbutton" is clicked. The HTML code is following:

  <form action="/search" method="get" novalidate="novalidate">
    <input type="hidden" name="in" value="people">
    <input name="for" type="text">
    <input type="submit" class="hidden">
  </form>

My Jquery code is following

Does anyone see, where the problem is?
Thanks!
Comment: `$(document).ready(function(){...});` is missing.
Comment: Have you tried putting the code inside **`$( document ).ready( handler )`** ??
Comment: Are you able to add a Id to form?
Answer: Try:

Answer: Give a form name say form_name then try this code


Best way to learn the development of windows azure application & WCF services

Question:
I am planning to learn the development of windows azure application & WCF services.
Is there any learning structure (description of subject content) to follow/refer so that we can learn the subject efficiently

Thanks in Advance
Answer: I suggest you take a look at the official Windows Azure training kit (filled with step-by-step guides, presentations, sample code, ...). Besides that you can also learn a lot from sites like Channel9, CodeProject, ... or by looking at sample projects on CodePlex or GitHub.
Comment: +1 The Windows Azure Training Kit covers not only the basics, but I have found many scenarios in real world apps that can adapt solutions in the training kit.


Using Ajax, JavaScript, PHP to delete database entries

Question: I am very new to web programming in general and I have some issues in creating a simple client database. I have to find a way to delete clients from the database using Ajax. I try to find a solution without using jQuery...
So far I managed to set up a script and php code to delete one database entry; However it is not possible to delete another client without refreshing the page first. Could someone help me find out what to do to solve this problem?
Relevant parts from my index.php
<?php
    require_once "CRM_DB.php";
    $clients = CRM_DB::showAll();
?>

...

All Entries

                    ID
                    Name
                    E-Mail
                    Comment
                    Created At
                    Updated At
                    Delete
                    Edit

                <? foreach($clients as $client): ?>

                        <?= $client->id ?>
                        <?= $client->name ?>
                        <?= $client->email ?>
                        <?= $client->text ?>
                        <?= $client->created_at ?>
                        <?= $client->updated_at ?>

                            <form action="" class="delete-form m-0" method="post">
                                <input type="hidden" id="del-id" name="id" value="<?= $client->id ?>">
                                <input type="hidden" name="delete" id="delete" value="1">
                                <button type="submit" class="btn btn-danger btn-sm" id="delete_btn" onclick="deleteID(); return false">Delete</button>
                            </form>

                <? endforeach; ?>

....

crm.php
if(isset($_POST["delete"]) && isset($_POST["id"])) {
    $id = $_POST["id"];
    CRM_DB::deleteClient($id);
}

CRM_DB.php
    public static function deleteClient($id) {
        $db = self::db();

        $query = "DELETE FROM clients WHERE id = ?";
        $result = $db->query($query, [$id]);
        return $result;
    }

    public static function showAll() {
        $db = self::db();

        $query = "SELECT * FROM clients";
        $result = $db->query($query);

        $clientArray = [];

        for($i = 0; $i < $result->num_rows; $i++) {
            $row = $result->fetch_array();

            $client = self::convertToObject($row);
            $clientArray[] = $client;
        }
        return $clientArray;
    }

    public static function convertToObject($row) {
        return new Client($row["id"], $row["name"], $row["email"], $row["text"], $row["created_at"], $row["updated_at"]);
    }

}

Comment: use `parent / sibling selectors` to find the correct form elements rather than trying ( and failing ) to use ID attributes which must be unique
Answer: I think the problem might be, that you are assigning the same element ID for multiple elements at <input type="hidden" id="del-id" name="id" value="<?= $client->id ?>">. At first, this is not valid HTML. Element IDs have to be unique in HTML. Secondly, the function deleteID() doesn't know, which client should be deleted. It just picks the first (of many) HTML elements with the ID "del-id".
Solution: remove the hidden field "del-id" and pass the ID of the client as a function argument, e.g.
<button type="submit" class="btn btn-danger btn-sm" id="delete_btn" onclick="deleteID(<?= $client->id ?>); return false">Delete</button>

...

function deleteID(clientID) {
    var del = document.getElementById('delete').value;
    var params = 'delete='+encodeURIComponent(del)+'&id='+encodeURIComponent(clientID);
    var url = 'crm.php';
...
}

You also don't need to pass the parameter "delete", since the function context is already about deleting a client. You can hardcore this value.
Also: NEVER EVER trust user input. You should check, if the clientID is a valid integer and if the user has the permission to delete the client!
Comment: Thank you for your input! But unfortunately the problem still remains even if I do implement your changes :(
Answer: ID attributes must be unique and will often cause issues like the one you faced here if not dealt with correctly. For the most part they have superior alternatives in my opinion - it is entirely feasible to traverse the DOM using parent/child/sibling types selectors which can be further enhanced with the use of document.querySelector and document.querySelectorAll to target specific nodes or collections of nodes.
If you modify the portion of HTML in the loop - assign a dataset attribute to the table row and remove the form as below - note the table row has it's ID changed to a class attribute so changes to the css might be needed. The FORM essentially does nothing as the input elements are hidden so the user cannot legitimately modify the values - so it could be removed as the request is being sent by ajax.

            <? foreach($clients as $client): ?>
                <tr class="table-row" data-id='<?=$client->id;?>'>
                    <?= $client->id ?>
                    <?= $client->name ?>
                    <?= $client->email ?>
                    <?= $client->text ?>
                    <?= $client->created_at ?>
                    <?= $client->updated_at ?>

                        <button type="button" class="btn btn-danger btn-sm">Delete</button>

            <? endforeach; ?>

You could then modify the javascript to remove the inline event handlers and create a a separate ajax function

update:
to remove the row from which the button was clicked ( and not display any feedback etc ) you could try:
const callback=function(r,id){
    let tr=document.querySelector('tr[data-id="'+id+'"]');
    tr.parentNode.removeChild( tr );
};

updated
In light of the above being untested, the need to remove the table row from the display on deletion and the issues remaining I put together a mockup of the above with a slight modification to the javascript. It doesn't show the php record selection/query but otherwise is fully functional.
The ajax function takes a fourth argument - a reference to the table row itself on which the button was clicked. Passing this argument makes it easy to delete the row rather than rely upon using the param.id with querySelector as a lookup mechanism.
<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['id'], $_POST['task'] ) ){
        ob_clean();

        /* pseudo sql only for illustration */
        switch( $_POST['task'] ){
            case 'edit':
                $sql=sprintf('update `clients` set `name`=?, `email`=? where `id`="%d"', intval( $_POST['id'] ) );
            break;
            case 'delete':
                $sql=sprintf('delete from `clients` where `id`="%d"', intval( $_POST['id'] ) );
            break;
        }

        exit( $sql );
    }
?>
<!DOCTYPE html>

        <meta charset='utf-8' />
        <title>CRM Contact Management</title>

All Entries

                                ID
                                Name
                                E-Mail
                                Comment
                                Created At
                                Updated At
                                Delete
                                Edit

                        <?php
                            while( $rs=$res->fetch_object() ){
                                printf(
                                    '

                                        %d
                                        %s
                                        %s
                                        %s
                                        %s
                                        %s

                                            <button data-task="delete" type="button" class="btn btn-danger btn-del btn-sm">Delete</button>

                                            <button data-task="edit" type="button" class="btn btn-edit btn-sm">Edit</button>

',
                                    $rs->id,
                                    $rs->id,
                                    $rs->name,
                                    $rs->email,
                                    $rs->text,
                                    $rs->created_at,
                                    $rs->updated_at
                                );
                            }
                        ?>

Comment: Thank you! Deleting the client from the database works now. But I still need the table to refresh after deleting a row. When I press the delete button nothing seems to happen, but after refreshing the page you see that it actually deleted the client from the database. But i would need just the table to refresh after deleting a client without refreshing the whole page. I hope that wasn't too confusing....
Comment: I must have missed that requirement from the question  - I do tend to skip-read ( aka: tldr )
see edit for how to delete row
Comment: Hm Thanks! But it did not work. Still showing the row after I clicked on the button :(
Comment: any errors in the console? None of the above was tested so there could well be errors or I may have missed some piece of the puzzle?!
Comment: Yes I checked the console: Uncaught ReferenceError: id is not defined
    at XMLHttpRequest.xmlhttp.onload; This happens when calling the function callback  ```callback( this.response, id );```
Comment: yep: that should have been `param.id`


Can't select list object by class

Question: My jQuery is a little rusty, hence this noob question:
I have this unordered list,

which I populate from a JSON-object:
function updateChecklists(){
    requestAllForms = $.get("/list-all-forms");

    requestAllForms.promise().done(function(data){
        $.each(data,function(key, val){
            $("
" + val.name +"
").appendTo("#list-all-forms");
        });
        $('ul').listview('refresh');
    });
};

However, when I try to get the click event from a link with the class checklistObject in the list, nothing happens...
$(".checklistObject").on("click", function(){
    console.log("click on list object!");

});

How can I get that function to fire?
Comment: See duplicate. `$(document).on('click','.checklistObject', function()...` will work.
Comment: try like this $("li a.checklistObject")
Answer: Depending on when you are creating the event handler those object may or may not exist and so the event isn't being attached properly. You could either wait until after they are created to add that event handler or use an event delegate and change your code to be something like:
$('#list-all-forms').on('click', '.checkListObject', function() {
    console.log($(this), "click on list object");
});

Which will work before and after your items are added to the DOM.
Or as mentioned in the comments, something like this: Event binding on dynamically created elements?
Answer: Are you sure you're adding the jQuery listener after the elements are there? If not, the selector will just add a click listener to nothing. If you want to load list items later to the list, you can do event delegation.
$("#list-all-forms").on("click", ".checklistObject", function() {
    console.log("click on list object!");
});

Can't select list object by class


Keyword search algorithm

Question: I'm developing an android application where the user needs to key in a string/sentence of strings as a keyword(s) and based on that input, some string should be retrieved from a database. I am looking for a suitable algorithm for this purpose. I have gone through many answers and many algorithms such as tfidf and Boyer-Moore but I am still confused of choosing the most efficient algorithm. Anyone has a suggestion?
(the purpose is to retrieve some string based on entered keywords)
Thanks
Comment: If the question is unclear, please let me know !
Answer: I wrote autocomplete search (by phrases/subphrases), you can see
performance and dictionaries size on my demo:
http://olegh.ftp.sh/autocomplete.html
This is Celeron-300 machine, FreeBSD OS. And loadin less than 1% CPU during active search.
But, written on C++, and uses mmap/pread system calls. So, I not sure, will it works on Android. I can share sources upon request.
Regarding algorithm: Used preindexed hash-index file,
based on all possible prefixes from phrases from dictionary.
By mmapped hash-table found bucket, which fetch into memory by pread.
Indexing relatively slow operation:
indexing of 15,000,000 dictionary entries can consume ~1hour on PERL script.
But search/retrieve extremely quick, and performance is not dependent on dictionary size.
Answer: I wouldn't recommend writing your own algorithm; rather, you should use an existing library like Apache Lucene.

Keyword search algorithm


Set of tuples (i, v) such that all tuples have different values of i

Question: I'm trying to construct a set of tuples (i, v), where i is an int and v is a double. The set cannot contain two tuples with the same value of i.
To do this, I think I should use a std::set of std:tuples. Something like:
#include <tuple>
#include <set>
using namespace std;

set<tuple<int, double>> mySet;

The std::set class allows me to specify a comparator, and I think I should use this to avoid different tuples with the same value of i, but I don't know how to do it??
Comment: Sounds like `map` to me.
Comment: See http://stackoverflow.com/questions/2620862/using-custom-stdset-comparator
Comment: @IgorTandetnik You're right! I didn't know about `map`. But I'd still like to understand how to do this with `set`
Answer: std::tuple already provides a operator< that you can use for comparisons, but it compares all elements of the tuple. You simply need to provide a comparator that compares the first element of the tuple and ignores the second.
struct comparator
{
    bool operator()(const tuple<int, double> & lhs, const tuple<int, double> &  rhs)
    {
        return get<0>(lhs) < get<0>(rhs);
    }
};

Comment: but how do I make `set` use the comparator I implemented?
Comment: @becko you just add a second template parameter to the set: `set,comparator> mySet`.
Comment: when I do this, I get an 'Error: function template "comparator" is not a type name'.
Comment: @becko, sorry - every time I've needed a functor a plain function was able to work. I've made an edit that should work better.
Answer: A map may be a better choice std::map<int, double>. The interesting thing is that the value_type of the map is std::pair<const int, double> which can be used like a tuple : std::get ...


Landscape orientation is not supported in ios7

Question: I want to make a screen in landscape mode only. It is work fine unto ios5. But in iOS 7 it is not working. I used following code to give support in ios7.
<code>-(BOOL)shouldAutorotate{return TRUE;}
-(NSUInteger)supportedInterfaceOrientations{return UIInterfaceOrientationMaskLandscape;}
</code>
It won't get call for all screens.
Thanks.
AKS.
Comment: the system will ask the root viewController to get the orientation info. make sure your code is in the rootVC
Comment: i wrote this code in view controller.m. It got call in first time. But didn't get call after navigating to next screen.
Comment: you use UINavigationController to move from A to B? if so, you should subclass UINavigationController, and write the code there. the code you write in A won't work
Answer: If anyone else is having this issue, I wrote a blog post about it. I was having a lot of trouble with this too. http://www.jmeveryday.com/ios7-device-orientation/
Answer: <code>- (BOOL)shouldAutorotate
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

    if (orientation==UIDeviceOrientationLandscapeRight || orientation==UIDeviceOrientationLandscapeLeft) {

        return YES;
    }
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}
</code>
Comment: But the problem is it is not getting call when navigate to next screen.
Comment: From your root controller, call shouldAutorotate in your viewController. if you are using a navigationcontroller you can get the controller showed with [self.navigationcontroller topViewController]. In your shouldAutorotate in rootViewController write "[topviewcontroller shouldAutorotate];"


Pass parameters to Facebook App Link from Android App

Question: I am sharing content (such as text, image and app link) to Facebook with following code:
Step 1:
public void setupFacebookShareIntent() {

    ShareDialog shareDialog;

    FacebookSdk.sdkInitialize(getApplicationContext());
    shareDialog = new ShareDialog(this);

    ShareLinkContent linkContent = new ShareLinkContent.Builder()
            .setContentTitle(title)
            .setContentDescription(
                    text1+ " " +text2)
            .setContentUrl(Uri.parse("http://example/folder"))
            .setImageUrl(Uri.parse(path1))
            .build();

    shareDialog.show(linkContent);
}

Also here the app link metadata:
Step 2:

    <meta property="al:android:url" content="sharesample://story/1234">
    <meta property="al:android:package" content="com.mypackage">
    <meta property="al:android:app_name" content="ShareSample">
    <meta property="og:title" content="example page title" />
    <meta property="og:type" content="website" />

And here the code to handle incoming app link in Activity:
Step 3:
Uri targetUrl = AppLinks.getTargetUrlFromInboundIntent(this, getIntent());

        if (targetUrl != null) {

            // If you need to access data that you are passing from the meta tag from your website or from opening app you can get them from AppLinkData.
            Bundle applinkData = AppLinks.getAppLinkData(getIntent());
            String id = applinkData.getString("id");

            // You can also get referrer data from AppLinkData
            Bundle referrerAppData = applinkData.getBundle("referer_app_link");

        } else {
            // Not an applink, your existing code goes here.
        }

How can I pass data to app link url properly in step 1, such as simple string parameters and then get back in step 3?
Comment: nobody has an idea? :)
Answer: Just in case someone has the same "issue", I'll post my solution:
When I share a link to FB from my app I pass the param in url like that:
http://my-app.com/xxxx/xxx.php?id=10

and then if user clicks the link on FB, then my app starts and I get the parameter as following:
 Uri targetUrl = AppLinks.getTargetUrlFromInboundIntent(this, getIntent());
 String s = targetUrl.getQueryParameter("id");

Comment: Thanks a lot Sin. As i was using facebook app linking service, so really wondering how could i pass it argument. But your solution works perfect. (y)
Comment: I am getting the below error in 11.3.0 https://stackoverflow.com/questions/69460312/error-cannot-find-symbol-applinks-gettargeturlfrominboundintent-in-com-facebook


How to do long-polling AJAX requests in ASP.NET MVC?

Question: Does anyone know how to code up long-polling AJAX requests (for server PUSH notifications) in ASP.NET MVC?  Whenever I do it, it seems that only the last browser to open up a window gets the notifications.  As if IIS/ASP.NET were canceling the last request because it was hung or something.
Answer: I recently wrote a simple example of a Long Polling Chat Server using MVC 3 Async Controllers based on a great article by Clay Lenhart
You can use the example on a AppHarbor deployment I set up based on the source from the BitBucket project.
Also, more information available from my blog post explaining the project.


SQL - ORDER BY Timestamp Array Data does not work

Question: I have a table with schema as below
fields. TIME_256Hz  TIMESTAMP   REPEATED
fields. SAC_ACCELX  FLOAT   REPEATED
fields. SAC_ACCELY  FLOAT   REPEATED
fields. SAC_ACCELZ  FLOAT   REPEATED
fields. SAC_GYROX   FLOAT   REPEATED
fields. SAC_GYROY   FLOAT   REPEATED
fields. SAC_GYROZ   FLOAT   REPEATED
fields. SAC_PRESSURE    FLOAT   REPEATED
fields. TARGET  STRING  REPEATED

The table looks like

I try to sort the data with timestamp using this command
select * from liftpdm.liftpdm_2.acc8
order by fields.TIME_256Hz desc

BUT
I keep getting the following error:
ORDER BY does not support expressions of type ARRAY<TIMESTAMP> at [2:10]

I tried to change the Datatype to Datetime, string but same error.
Please suggest how to sort out this data
Thanks
Comment: Do you actually *need* to have the fields `REPEATED`?
Comment: It is the mode. I tried Nullable but that is wrong
Comment: I get following error when I change to Nullable                                                                              {
  "errors" : [ {
    "debugInfo" : "",
    "location" : "fields.time_256hz",
    "message" : "Array specified for non-repeated field.",
    "reason" : "invalid"
  } ],
  "index" : 0
}
Answer: Reproducible error:
WITH data AS (
  SELECT [1,2] arr UNION ALL
  SELECT [2,1] UNION ALL
  SELECT [4,5,6]
)

SELECT * FROM data
ORDER BY arr

# ORDER BY does not support expressions of type ARRAY<INT64> at [8:10]

First you need to decide what do you really want to ORDER BY, as ordering by an array doesn't make much sense.
Some alternatives:
SELECT * FROM data
ORDER BY arr[SAFE_OFFSET(0)]

SELECT * FROM data
ORDER BY arr[SAFE_OFFSET(1)]

SELECT * FROM data
ORDER BY ARRAY_LENGTH(arr) DESC

Comment: Thanks, a very important pointer. You are right, why would I need to order by arrays. Actually I need to order the entire column but the column has arrays of 256 records per row. So I need to somehow have the table like this from your example                       Rows =[1,2,3,4,5,6,7] and arr=[1,2,2,1,4,5,6] then I need to do order by on it. Can you suggest a way of doing it? thanks
Comment: Post a new question please!