Q:

R - deconvoluting complex intervals into position & location information

This question is an extension of this one.
There is now an additional column in fileA that needs to be taken into account when extracting position information from the interval. For instance, in the example below, positions 123-78000 at location X are labelled romeo whereas the same positions 123-78000 at location Y are labelled mario:
location  start     end      value    label
X         123       78000    0        romeo    #value 0 at positions X(123 to 77999 included).
X         78000     78004    56       romeo
X         78004     78005    12       romeo    #value 12 at position X(78004).
X         78006     78008    21       juliet
X         78008     78056    8        juliet
Y         123       78000    1        mario    #value 1 at positions Y(123 to 77999 included).
Y         78000     78004    24       mario
Y         78004     78005    4        mario    #value 4 at position Y(78004).
Y         78006     78008    12       luigi
Y         78008     78056    14       luigi

On the other hand fileB defines the intervals that actually interest me:
location  start     end      label
X         77998     78005    romeo
X         78007     78012    juliet
Y         77998     78005    mario
Y         78007     78012    luigi

The labels in fileA were originally pulled in from fileB, so it is safe to assume that the labels are always equivalent for overlapping intervals.
I am trying to extract the information for all the individual positions in fileA that correspond to the intervals in fileB – a process which I will call deconvolution for lack of a better word. This time, I would like to do that while at the same time taking location into account - it's dangerous to extract location back from position as the same position numbers may appear in several locations. The output fileC should come up like this:
location  position  value   label
X         77998     0       romeo
X         77999     0       romeo
X         78000     56      romeo
X         78001     56      romeo
X         78002     56      romeo
X         78003     56      romeo
X         78004     12      romeo
X         78007     21      juliet
X         78008     8       juliet
X         78009     8       juliet
X         78010     8       juliet
X         78011     8       juliet
Y         77998     1       mario
Y         77999     1       mario
Y         78000     24      mario
Y         78001     24      mario
Y         78002     24      mario
Y         78003     24      mario
Y         78004     4       mario
Y         78007     12      luigi
Y         78008     14      luigi
Y         78009     14      luigi
Y         78010     14      luigi
Y         78011     14      luigi

I thought I would be able to implement this myself from the solution to my previous question, but I am stuck, especially on this part, I don't know how I can incorporate the location information to the position information:
# create sequence of positions
s <- unlist(apply(B, MARGIN=1, FUN=function(x) seq(x[2], as.numeric(x[3])-1)))

Thank you for your time.

A:

This seems to produce your sample output.
# It is essential that there be NO FACTORS
A<-read.table("fileA.txt",header=T,stringsAsFactors=F)
B<-read.table("fileB.txt",header=T,stringsAsFactors=F)

# build template with position in the appropriate ranges
template <- do.call(rbind,lapply(1:nrow(B),
                    function(i) cbind(location=B[i,]$location,
                                      position=seq(B[i,]$start,B[i,]$end-1),
                                      label=B[i,]$label)
))
template <- data.frame(template, stringsAsFactors=F)
# add position column to A, return as C
C <- merge(A,template,by=c("location","label"),all=T)

is.between <- function(x,low,hi) return(x>=low & x<=hi)
C <- C[is.between(C$position,C$start,C$end-1),]
C <- C[,c("location","position",value="value","label")]
C
#    location position value  label
# 1         X    78007    21 juliet
# 7         X    78008     8 juliet
# 8         X    78009     8 juliet
# 9         X    78010     8 juliet
# 10        X    78011     8 juliet
# 11        X    77998     0  romeo
# 12        X    77999     0  romeo
# 20        X    78000    56  romeo
# 21        X    78001    56  romeo
# 22        X    78002    56  romeo
# 23        X    78003    56  romeo
# 31        X    78004    12  romeo
# ...


Q:

my application is crashed due to thread use how can i fix it

I'm using thread onClick method. It run successfully but after while crashed. I did not know why ... put the code is here
@Override
        public void onClick(View v) {
            // invisible first image
            // imgVScrub.setVisibility(View.INVISIBLE);
            imgMoveCream.setVisibility(View.VISIBLE);
            // translate the particle by anim

            forCreamAnim.start();
            // imgVTemp.startAnimation(creamParticleAnim);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        // : handle exception
                        e.printStackTrace();
                    } finally {
                        // back animation of cream
                        imgVScrub.startAnimation(showerBackRotateAnimCream);

                    }
                }
            }).start();
        }

and log trace is here
05-27 04:30:29.732: E/AndroidRuntime(1682): FATAL EXCEPTION: Thread-90
05-27 04:30:29.732: E/AndroidRuntime(1682):   android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4039)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.ViewRootImpl.invalidateChild(ViewRootImpl.java:722)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:771)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:4005)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.View.invalidate(View.java:8576)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at android.view.View.startAnimation(View.java:12980)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at dwt.wasif.manicure.CreamActivity$1$1.run(CreamActivity.java:102)
05-27 04:30:29.732: E/AndroidRuntime(1682):     at java.lang.Thread.run(Thread.java:856)

A:

Just start your animation in ui thread..all the ui related changes need to be done in ui thread
use below code
ActiviyName.this.runOnUiThread(new Runnable() {

    public void run() {

        // back animation of cream
         imgVScrub.startAnimation(showerBackRotateAnimCream);

    }
});


Q:

difference between code coverage and profiling

What is difference between code code coverage and profiling.
Which is the best open source tool for code coverage.

A:

Code coverage is an assessment of how much of your code has been run.  This is used to see how well your tests have exercised your code.
Profiling is used to see how various parts of your code perform.
The tools depend on the language and platform you are using.  I'm guessing that you are using Java, so recommend CodeCover.  Though you may find NoUnit easier to use.

A:

Coverage is important to see which parts of the code have not been run.
In my experience it has to be accumulated over multiple use cases, because any single run of the software will only use some of the code.
Profiling means different things at different times. Sometimes it means measuring performance. Sometimes it means diagnosing memory leaks. Sometimes it means getting visibility into multi-threading or other low-level activities.
When the goal is to improve software performance, by finding so-called "bottlenecks" and fixing them, don't just settle for any profiler, not even necessarily a highly-recommended or venerable one.
It is essential to use the kind that gets the right kind of information and presents it to you the right way, because there is a lot of confusion about this.
More on that subject.
Added:
For a coverage tool, I've always done it myself. In nearly every routine and basic block, I insert a call like this: Utils.CovTest("file name, routine name, comment that tells what's being done here").
The routine records the fact that it was called, and when the program finishes, all those comments are appended to a text file.
Then there's a post-processing step where that file is "subtracted" from a complete list (gotten by a grep-like program).
The result is a list of what hasn't been tested, requiring additional test cases.
When not doing coverage testing, Utils.CovTest does nothing. I leave it out of the innermost loops anyway, so it doesn't affect performance much.
In C and C++, I do it with a macro that, during normal use, expands to nothing.


Q:

gnuplot bashshell several curves and fitted curves in one fig

This is a followup of my earlier question here: "gnuplot bashshell to plot several curves in one window" which Christoph kindly helped with it. However, I had simplified my question assuming I would be able to advance from there on my own. No need to say, I couldn't! :( what I really want to plot in one fig frame is a set of data files and for each of the data files a curve(exponential function) fitted to it. Unfortunately I'm stuck with gnuplot 4.2 which doesn't allow me to use for loop and iterations. I would greatly appreciate any advice. The following bash cript prints nine curves and their fitted lines on separate files.
#!/bin/bash

for Counter in {1..9}; do
FILE="dataFile"$Counter".data"
gnuplot <<EOF
set xlabel "k"
set ylabel "p(k)"
set term png
set output "${FILE}.png"
title_fexp(a,b) = sprintf('exp(x) = %.2f * e(%.2f)', a, b)
expon(x) = c * exp(-x*d)
fit [10:100] expon(x) '${FILE}' via c,d
plot [1:50] expon(x)t title_fexp(c,d), '${FILE}'
EOF
done

A:

Before you write a bash script to generate a gnuplot script, you should think about what your gnuplot script should look like. After that, you can write a bash/whatever script to generate the same gnuplot code.
So, what you want is this:
set xlabel "k"
set ylabel "p(k)"
set term png
set output "MySingleFile.png"

# Note that I've added c and d to the declaration
expon(x, c, d) = c * exp(-x*d)

# This allows to store the fit parameters for each datafile separately
fit expon(x, c1, d1) "dataFile1.data" via c1, d1
fit expon(x, c2, d2) "dataFile2.data" via c2, d2
fit expon(x, c3, d3) "dataFile3.data" via c3, d3

# now plot it. Note: The backslash allows multi line commands
plot \
    "dataFile1.data" notitle pt 1, \
    expon(x, c1, d1) title sprintf('exp(x) = %.2f * e(%.2f)', c1, d1) lt 1,\
    "dataFile2.data" notitle pt 2, \
    expon(x, c2, d2) title  sprintf('exp(x) = %.2f * e(%.2f)', c2, d2) lt 2,\
    "dataFile3.data" notitle pt 3, \
    expon(x, c3, d3) title  sprintf('exp(x) = %.2f * e(%.2f)', c3, d3) lt 3

unset output

Now you can write a bash script based on yours which generates code like mine.
However, consider to pipe the gnuplot commands into a separate file and then call gnuplot with this file as parameter. This allows to debug the output of the bash script.
Note that there is no comma at the end of the last line of the command plot. Depending on what you need, your bash script hast to care about, or you just edit your gnuplot file and remove the last comma.


Q:

Reference and call object issue?

I have a doubt about javascript references. So, if I have something like this:
a = function(){console.log('a')};
a['b'] = function(){console.log('b')}

Are these functions somehow related?

A:

You only have one variable there: a. But you've created a property on the function a refers to, called b, that refers to another function.
That's the only relationship the two functions have: One is referenced by a property on the other. Other than that, they're unrelated.
As Unicode-art:

      +−−−−−−−−−−−−−−−+
a−−−−>|  (function)   |
      +−−−−−−−−−−−−−−−+
      | ...stuff...   |
      | length: 0     |     +−−−−−−−−−−−−−−−+
      | b             |−−−−>|  (function)   |
      +−−−−−−−−−−−−−−−+     +−−−−−−−−−−−−−−−+
                            | ...stuff...   |
                            | length: 0     |
                            +−−−−−−−−−−−−−−−+

...with two different functions with this referring to window ?

As deceze pointed out, the value of this within calls to those functions will depend entirely on how they're called, as with most JavaScript functions. (The exceptions being bound functions, which have a value for this bound to them, and ES2015+ arrow functions, which close over the this where they're defined.)
In loose mode, doing a() will indeed call the first function with this referring to the global object (which is the window object on browsers). In strict mode, a() would call it with this set to undefined. You can also use a.call(anyValueHere) to call it with this set to any value (in strict mode; in loose mode, anyValueHere has to be an object or you get that global object again). If you assign a to an object property (var o = {a: a};) then call it via o.a(), this within the call with equal o. If you do new a, the first function will be called with this referring to the new object from new. Etc.
In fact, with what you have in your question, a.b() would call the second function with this referring to the first function!

var a = function(){console.log('a')};
a['b'] = function(){console.log("this is: ", this)}; // Note change
a.b();


Q:

SQL Setting Week Numbers For Months From Monday to Sunday

I am trying to set the week number for months in a table. The logic is the first week starts on the first day of the month until the first Sunday and the rest of the weeks start on every Monday following that. I am having trouble implementing this though. Any Ideas? My code looks something like this.
I had previously received help here to set the week numbers for the entire years in a similar way. It looks like the following:
UPDATE [DimTime]
SET [WeekNumberOfYear] = DATEPART(WEEK,[Date]) - CASE WHEN DATEPART(WEEKDAY,[Date])     in (1) THEN 1 ELSE 0 END

A:

This should give you a correct result:
UPDATE [HMDBDataMartBOS].[dbo].[Dimension.DimTime]
SET [NaturalWeekNumberOfYear] = datediff(d, datediff(d, 0,
dateadd(m, datediff(m, 0, [Date]), 0))/7*7 - 7,[Date])/7


Q:

Does the file is being downloaded to site even if it's not supposed to be downloaded?

I am sure this is the one of the most epic titles ever. So, I have upload form like here. I made that people could upload their files only up to 1 MB. But, if I try to upload for example 1 GB file, it takes ages before it gives me an error. So, here comes a question. Before checking file's size, does that file is being downloaded in my hosting or does it takes resources from my hosting? Why it takes ages and ages before it gives me an error although if I try to upload 2 MB file it gives me an error in 1 second?
Thank you for your explanations.

A:

If you're checking the file size on the server then, yes, it will have to upload to the server in order to just run the if statement that checks the size.
Anything you do on the client side to check will, of course, be at the mercy of the client.  So there is no 100% reliable way to do it.  Artefacto pointed out one good way to catch most users.  There's also a JavaScript ActiveX object that might help (http://www.kavoir.com/2009/01/check-for-file-size-with-javascript-before-uploading.html) but, again, users can easily disable it (even quite unintentionally) or have browsers that don't support it at all.


Q:

Programmatically create Redirects in Wagtail

Is there a way to programmatically create functioning Redirect objects in Wagtail?
I am trying the obvious (naively creating the object):
Redirect.objects.create(old_path='/test', redirect_link='https://stackoverflow.com')
This creates a Redirect that is visible in the Wagtail admin panel, however navigating to /test simply 404s without redirecting.
However, if I then save the Redirect from the admin panel, it suddenly works.
Is there some special post-save logic I need to run in order to activate the redirect? I looked through the source and could not find anything.

A:

User error - I believe I was running into DNS caching issues that prevented the redirect from working. My original code seems to work fine now.


Q:

Redirect users to a new page with ASP classic

I am new to ASP.
In my current project I want to add a banner and by clicking on the banner we are showing a page which has login and new user options.
If the user is new, then clicking on the NewUser link redirects to a registration page which I already have in the project, and creates a user.
After registration I want to redirect the same user to a page (ex. xyz.asp).
Please help me to solve this.
Thanks in advance.

A:

You can redirect a user with Response.Redirect.
Examples
If you want to send them to page in the same folder:
<%
Response.Redirect "xyz.asp"
%>

If you want to send them to page in the parent folder:
<%
Response.Redirect "../xyz.asp"
%>

If you want to send them to page on a differect site:
<%
Response.Redirect "http://www.example.com/"
%>


Q:

Удаление двойных и более слов

Не понимаю, я в условие написал {1,} это значит, если повторяется больше одного раза, то это всё удалить, но почему не во всех случаях удаляет?
echo preg_replace('#([\w]+)\s\1{1,}#', '$1', 'hello my my  my  my my world');

/hello world world - работает
//hello world  world  world - не работает
//hello world  world  world  world - не работает
//hello hello world - работает
//hello hello hello hello world - плохо работает
//hello my my world - работает
//hello my my my world - плохо работает
//hello my my  my  my my world - hello my my  my  my my world

A:

#(\w+)(\s+\1)+#

(\w+) - 1-ая группа захвата, можно сказать что слово, хотя тут можно поспорить;
(\s+\1)+ - 2-ая повторяющаяся группа захвата, от которой вы хотите избавиться и состоит она из 1-го или более пробельных символов и слова из первой группы захвата, так как между словами пробелы все-таки должны быть!
Пример https://regex101.com/r/q1OhHr/1
P.S. Можно еще и флаг i добавить, чтобы регистронезависимая проверка была и флаг u для Юникода.


Q:

RightToLeft DatagridviewCell

How can i sert the property RightToLeft to a DatagridviewCell? I tried to set
Alignement property to "MiddleRight" but since my DatagridviewCell value is
Arabic and English it is not displayed as i want from right to left.

A:

I found a solution with Cell_Painting event and it works. This is the code:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex == 2 && e.RowIndex >= 0)
        {
            e.PaintBackground(e.CellBounds, true);
            TextRenderer.DrawText(e.Graphics, e.FormattedValue.ToString(), e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor, TextFormatFlags.RightToLeft | TextFormatFlags.Right);
            e.Handled = true;
        }
    }


Q:

type .git\HEAD doesn't work in Git Bash of Windows 10

I want to use this command type .git\HEAD in the Git Bash of Windows 10, but I just got this:-
bash: type: .gitHEAD: not found

But the head file really exists under the folder .git. I tried type .git/HEAD and type .git\\HEAD as well, with no luck.
How can I got that fixed?

A:

In a bash session, try instead:
cat .git/HEAD

That should return something like:
ref: refs/heads/master

cat is the analogous Unix command of type, which originated as an internal command in 86-DOS.
The default path in a git bash session does not include system32 commands, as described in "type command not working as expected on Git Bash"


Q:

Designing react- reducer of a social site

I have three different components in my app.
ie. 1. Newsfeed (here i am fetching all the posts)
    2. Trending (posts with of popular hashtags)
    3. UserProfile (fetching all the posts of that user)
const postReducer = (state = postReducerDefaultState, action) => {
switch(action.type){
    case 'ADD_POST':{
        return[
             action.post,
             ...state
         ]
    }
     case 'FIND_POST':
        return action.post
    case 'REMOVE_POST':
        return state.filter(post => post._id !== action.id)
    case 'EDIT_POST':
        return state.map(post => {
            if (post._id === action.id){
               return{
                   ...post,
                   ...action.updates
               };
            }else{
                return post;
            }
        });
    case 'LIKE_POST':
       return state.map(post => {
           if(post._id === action.id){
               return{
                  ...post,
                  likes:[...post.likes,action.likedBy]
               }
           }else{
               return post;
           }
       });
    case 'UNLIKE_POST':
        return state.map(post => {
            if(post._id === action.id){
                return {
                    ...post,
                    likes : post.likes.filter(liker => liker !==
 action.likedBy)
                }

            }else{
                return post;
            }
        })
    case 'ADD_COMMENT':
       return state.map(post => {
           if(post._id === action.pid){
               return{
                   ...post,
                   comments:[...post.comments,action.comment]
               }
           }else{
               return post;
           }
       });
    case 'SET_POST':
          return action.posts;
    case 'HASHTAG_POST':
          return action.posts;
    default:
          return state;
}
};

in this design if i go from one component to other component, (dashboard to trending), I lost all the data of the dashboard. But if want to keep the like,comment functionalty for dashboard and trending posts, then i have to write the like-comment functionality separately for all the mentioned three components. This approach will work, but i am not satisfied with as i have to write same thing thrice. Can anyone suggest the best approach?

A:

The recommended way to solve this problem is with higher order components, which are React components that "wrap" another component to provide common functionality. You should be able to find plenty of resources explaining this, but a typical higher order component looks something like this:
import React from 'react';

const higherOrderComponent = (WrappedComponent) =>
{
  class HOC extends React.Component {
    render() {
      return <WrappedComponent />;
    }
  }

  return HOC;
};

You can then add whatever functionality needs to be shared to the higher order component. Then, you can use it something like this:
const SimpleHOC = higherOrderComponent(MyComponent);

EDIT: If you want the same functionality to apply for different reducer actions, that's straightforward. Just have the same callback fall through for different cases, as in this example:
case 'ACTION_1':
case 'ACTION_2':
case 'ACTION_3':
    // callback here

For your application, it will be something like this:
case 'EDIT_POST':
case 'LIKE_POST':
case 'UNLIKE_POST':
    return state.map(post => {
        if (post._id === action.id){
           return{
               ...post,
               ...action.updates
           };
        }else{
            return post;
        }
    });


Q:

Persisting and retrieving serialized entity property with Entity Framework 6.1 code first

Example: Let's say I have these three classes. Foo is a proper Entity Framework entity with a DbSet whereas I want my EF DbContext to be unaware of Bar and Baz because I have flagged Foo's Bar property with my made up SerializedColumn attribute. By applying that attribute, I want EF to serialize the instance of Bar with its Bazes into a single string field, and transparently deserialize Bar to a Bar object when a Foo is materialized by EF.
public class Foo
{
    public Guid Id { get; set; }
    [SerializedColumn]
    public Bar Bar { get; set; }
    // ..
}

public class Bar
{
    public string Name { get; set; }
    public Baz[] Baz { get; set; }
    // ..
}

public class Baz
{
    public string Name { get; set; }
    // ..
}

So Foo's table columns would look like:
[Id] [uniqueidentifier] NOT NULL
[Bar] [nvarchar](max) NULL

And when I query a Foo I get back one with the Bar property already deserialized. When I insert or update a Foo the Bar property gets serialized by EF without me having to think about it. The only thing I have to do is add the [SerializeColumn] attribute to properties.
Goals:

I'm not necessarily looking for a full blown solution (although I would accept it) but for guidance on where to jump into EF's pipeline, and how to do that. I.E. what EF classes, configurations, conventions, etc. do I need to take into account?
I want Migrations to be generated as one would expect. Which is to say, I wouldn't want my Bar property to turn into a "Bar_Id" field that points to a "Bar" table. Instead I want a nvarchar(max) "Bar" field that will contain the serialized version of a Bar object. If this simply isn't possible, please say so in your answer.

Notes:

The idea for this came after watching the Building Applications with Entity Framework 6 video by Rowan Miller.
ComplexType does not serve my needs. I need deep serialization and do not need to be able to filter or sort on any properties of what has been serialized.
I plan on serializing with Newtonsoft's JSON library, but how serialization happens doesn't really matter.

A:

The only solution is this,
public class Foo
{
    public Guid Id { get; set; }

    // Not Mapped attribute will make EF
    // ignore this property completely
    [NotMapped]
    public Bar BarObject {
      get;
      set;
    }

    public string Bar{
       get{
          return JsonConvert.Serialize(BarObject);
       }
       set{
          BarObject = JsonConvert.Deserialize<BarObject>(value);
       }
    }
}

Updated as per suggestion by @zds


Q:

How do I add button in each row of column of already bound datagridview in Windows application?

I want to add a button to each row of a column of an already bounded datagridview, and add an event to it (in VS 2005, Windows application).
I have searched a lot but was unable to find a working solution.

A:

before binding to the datasource set :
grd.AutoGenerateColumns = false;

create yourself all DataGridView columns and bind them to the datasource:
DataGridViewTextBoxColumn dgvc = new DataGridViewTextBoxColumn();
dgvc.HeaderText = "column_header";
dgvc.DataPropertyName = "column_name";

create a DataGridViewButtonColumn.
DataGridViewButtonColumn dgvbt = new DataGridViewButtonColumn();

If you want this column not bound, set header text, the same text on all buttons:
dgvbt.HeaderText = "OK?";
dgvbt.Text = "ok";                        // works also when bound
dgvbt.UseColumnTextForButtonValue = true; //

If you want your column to be also bounded and each button have the text of underlying cell, bind it:
dgvbt.DataPropertyName = "column_bt";

Add created columns to the DataGridView:
grd.Columns.Add(dgvc);
grd.Columns.Add(dgvbt);

handle the CellClick event of the DataGridView:
grd.CellClick += new DataGridViewCellEventHandler(grd_CellClick);

void grd_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == index_of_button_column)
    {
        MessageBox.Show(this, e.RowIndex.ToString() + " Clicked!");
        //...
    }
}

for more, see:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewbuttoncolumn.aspx


Q:

Intersection of a dense set with an open set is dense in the open set

Let $A\subset M$ ann open subset, of the metric space  M. If $X\subset M$ is dense in M, then $X\cap A$ is dense in A.

My approach: If $X\subset M$, and $A\subset M$ is a open subset. Let be $U\subset A$ (doesn't empty), then U is open subset in M. Therefore $U\cap X\neq \emptyset$. And now, $U\cap X=(U\cap A)\cap X = U\cap(A\cap X)$, and then $A\cap X$ is dense. But I don't sure is this ok, any help. Regards

A:

Your argument is basically correct. Here is a more careful and mostly equivalent argument.
To show $X \cap A$ is dense in $A$, we need to show that every nonempty open set in $A$ intersects $X \cap A$.
So take $U \subset A$ open in $A$, and nonempty.
Note that $\boldsymbol{U}$ is open in $\boldsymbol{A}$ iff it is open in $\boldsymbol{M}$, so $U$ is open in $M$.
Therefore $U \cap X \neq \varnothing$, and therefore $U \cap (A \cap X) = U \cap X \neq \varnothing$.


Q:

Click Function in JQuery

$("#displayPanel #save #saveForm").live("click", function(){
                   //Move to forms/homepage
    });

What I'm trying is when clicking on the saveForm Button I want to move to a URL(homepage) Where ii had some list of saved forms.
I'm new to JQuery.
Note:
       Where my saveForm is like
       <input id='saveForm' type='Submit' value='Save Form'>

A:

You shouldn't use document.location. It has been replaced by window.location.
From the Mozilla docs:

document.location was originally a
  read-only property, although Gecko
  browsers allow you to assign to it as
  well. For cross-browser safety, use
  window.location instead.

The only cross-browser way to navigate to a new URL from javascript is:
window.location = "http://mysite.com/url";

A:

You mean redirect to page?
document.location = 'http://yourpage';


Q:

Can Pipes be used in Javascript or Typescript?

This is a hopelessly naive question but I've been wrestling with it for a couple of hours now.
Can Pipes be called from JavaScript/TypeScript or are they only meant to be used in templates? All the references and tutorials I've looked at show Pipes being used in the templates only.
I'm don't have a hard use case for this but I'm playing around with the various elements of Angular2 and could imagine that I might have a need to use a Pipe directly and not recode it in JS/TS

A:

Yes, a pipe is just code, so you could use it as code without using it in your template. For example, I have a ProductFilterPipe that filters a list of products. We could use that pipe in code as follows:
filterProducts() : void {
    let productFilterPipe = new ProductFilterPipe();
    let filteredList = productFilterPipe.transform(this.products, "am");
    console.log(filteredList);
}

So it is possible.


Q:

Did the plumber hook up my water heater backwards?

I just had a plumber install a new 50 gallon water heater, but the cold water pipe is installed to the hot side (the left pipe when facing the front of the heater) and the hot water pipe is installed to the cold side (the right pipe when facing the front of the heater).  Is this ok? I thought that the cold water pipe had to go into the cold intake value and the hot water pipe would be connected to the hot value.
So I called the plumber and he said that everything is installed correctly. And he wouldn't change the plumbing.

A:

Yes, reversing them would be a bad thing. The cold water should be entering the bottom of the tank, the hot output at the top:

I'd insist that the plumber fix this. But if they won't, I'd suggest picking up a pipe cutter, some sharkbite connectors, and just fix it yourself. Shouldn't take more than a half hour to do so.


Q:

UIActivityIndicatorView not staring

I am trying to set a 'UIActivityIndicatorView' as an accessoryView in one of my 'UITableViewCell', in a such way as, the ActivityIndicator start animating when the user touch this cell. I add the following code at 'didSelectRowAtIndexPath' method:
UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];

UIActivityIndicatorView * activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

NSThread * newThread1 = [[NSThread alloc]initWithTarget:self selector:@selector(carregarNoticias) object:nil];

switch (indexPath.row) {
    case 0:
        cell.accessoryView = activity;
        [activity startAnimating];
        sleep(0.01);
        [newThread1 start];

        while (![newThread1 isFinished]) {
            //waiting for thread
       }

        [activity stopAnimating];
[self.navigationController pushViewController:noticias animated:YES];
break;

I was expecting 'UIActivityIndicatorView' animating while the newthread1 is running. However, the animating only start when the newThread1 finish (and therefore I don't want the animation anymore). I added 0.01 seconds as sleep time to give time to the animation start. Nevertheless, this also did't solve.
Does anyone know what my error is? I appreciate any help!

A:

I dont really know what you are trying to do adding delay like that.. try this line below, might be the one your look for.. and another thing.. please dont block the main thread like sleep(0.01); that, users wont like it..
cell.accessoryView = activity;

[activity startAnimating];

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

    // the system will wait until this
    dispatch_async(dispatch_get_main_queue(), ^(void){

        [newThread1 start];

    });
    // is finished, maybe you dont need the `[NSThread sleepForTimeInterval:3];`
    // pick the one that suits your implementation..

    [NSThread sleepForTimeInterval:3];

    dispatch_async(dispatch_get_main_queue(), ^(void){

        [activity stopAnimating];

        [self.navigationController pushViewController:noticias animated:YES];

    });
});

[NSThread sleepForTimeInterval:3] sleep the thread like the one you have sleep(0.01);
But using it inside
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){  });

makes it async. and wont block the main thread..
while the dispatch_async(dispatch_get_main_queue(), ^(void){ fires your code at the main thread..
Happy coding, cheers! :)


Q:

Load large csv in hadoop via Hue would only store a 64MB block

Im using the Cloudera quickstart vm 5.1.0-1
Im trying to load my 3GB csv in Hadoop via Hue and what I tried so far is:
- Load the csv into the HDFS and specifically into a folder called datasets positioned at /user/hive/datasets
- Use the Metastore Manager to load it into the default db
Everything works fine meaning that I manage to load it with the right columns. The main problem is that when I query the table with Impala launching the following query:
show table stats new_table
I realize that the size is only 64 MB instead of the actual size of the csv which should be 3GB.
Also, if I do a count(*) via Impala the number of rows is only 70000 against the actual 7 million.
Any help would be deeply appreciated.
Thanks in advance.

A:

I've had the exact same problem.  This is an issue with how Hue imports the file via the web interface, which has a 64MB limit.
I've been importing large datasets by using the Hive CLI and the -f flag against a text file with the DDL code.
Example:
hive -f beer_data_loader.hql

beer_data_loader.hql:
  CREATE DATABASE IF NOT EXISTS beer
  COMMENT "Beer Advocate Database";

CREATE TABLE IF NOT EXISTS beer.beeradvocate_raw(
    beer_name           STRING,
    beer_ID             BIGINT,
    beer_brewerID       INT,
    beer_ABV            FLOAT,
    beer_style          STRING,
    review_appearance   FLOAT,
    review_aroma        FLOAT,
    review_palate       FLOAT,
    review_taste        FLOAT,
    review_overall      FLOAT,
    review_time         BIGINT,
    review_profileName  STRING,
    review_text         STRING
    )
 COMMENT "Beer Advocate Data Raw"
 ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '|'
 STORED AS parquet;

CREATE EXTERNAL TABLE IF NOT EXISTS beer.beeradvocate_temp(
    beer_name           STRING,
    beer_ID             BIGINT,
    beer_brewerID       INT,
    beer_ABV            FLOAT,
    beer_style          STRING,
    review_appearance   FLOAT,
    review_aroma        FLOAT,
    review_palate       FLOAT,
    review_taste        FLOAT,
    review_overall      FLOAT,
    review_time         BIGINT,
    review_profileName  STRING,
    review_text         STRING
    )
 COMMENT "Beer Advocate External Loading Table"
 ROW FORMAT DELIMITED
  FIELDS TERMINATED BY '|'
 LOCATION '/user/name/beeradvocate.data';

INSERT OVERWRITE TABLE beer.beeradvocate_raw SELECT * FROM beer.beeradvocate_temp;
DROP TABLE beer.beeradvocate_temp;


Q:

Circle bounce bug

I'm creating a minigame using HTML5 and jQuery without canvas (!) and, while developing the bounce part (when circle collide with stage limit), I found a bug:
When the circle collides with the bottom or right limits and you keep pressing the down/right arrow key, the circle continues bouncing with the stage limit, but when you do the same thing with the opposite stage limits (top and left), the circle bounce one or two times, and then stops (I want to get the second reaction, when it bounce and then stop). I've also discovered that this bug only occur in Safari. Can someone help me to solve it?
JSFiddle
Demo on site
<!DOCTYPE html>
<html>

<head>
    <title>VelJS 3 Pre-Alpha</title>

    <!-- This app was coded by Tiago Marinho -->
    <!-- Special thanks to Drizr, from the interwebs -->
    <!-- Do not leech it! -->

    <link rel="shortcut icon" href="http://i.imgur.com/Jja8mvg.png">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    var yvel = 0, xvel = 0;
    var up = false, // W or arrow up
            left = false, // A or arrow left
            right = false, // D or arrow right
            down = false; // S or arrow down

            // Keydown:
            document.addEventListener("keydown", function (evt) {
                if (evt.keyCode == 87 || evt.keyCode == 38) { // up
                    up = true;
                }
                if (evt.keyCode == 65 || evt.keyCode == 37) { // left
                    left = true;
                }
                if (evt.keyCode == 68 || evt.keyCode == 39) { // right
                    right = true;
                }
                if (evt.keyCode == 83 || evt.keyCode == 40) { // down
                    down = true;
                }
                if (evt.keyCode == 8 || evt.keyCode == 80) { // del/p
                }
            });
            // Keyup:
            document.addEventListener("keyup", function (evt) {
                if (evt.keyCode == 87 || evt.keyCode == 38) { // up
                    up = false;
                }
                if (evt.keyCode == 65 || evt.keyCode == 37) { // left
                    left = false;
                }
                if (evt.keyCode == 68 || evt.keyCode == 39) { // right
                    right = false;
                }
                if (evt.keyCode == 83 || evt.keyCode == 40) { // down
                    down = false;
                }
            });

            function y(obj){
                return $(obj).offset().top;
            }
            function x(obj){
                return $(obj).offset().left;
            }

            setInterval(function(){

                // Keydown/keyup handler:
                if (up == true) {
                    yvel -= 2;
                } else {
                    if (yvel < 0) {
                        yvel++;
                    }
                }
                if (left == true) {
                    xvel -= 2;
                } else {
                    if (xvel < 0) {
                        xvel++;
                    }
                }
                if (right == true) {
                    xvel += 2;
                } else {
                    if (xvel > 0) {
                        xvel--;
                    }
                }
                if (down == true) {
                    yvel += 2;
                } else {
                    if (yvel > 0) {
                        yvel--;
                    }
                }

                var nextposx = $("circle").offset().left+xvel/16;
                var nextposy = $("circle").offset().top+yvel/16;

                if(nextposy < 0 || nextposy+20 > window.innerHeight){
                    yvel = Math.round(yvel*-0.5);
                }
                if(nextposx < 0 || nextposx+20 > window.innerWidth){
                    console.log(xvel);
                    xvel = Math.round(xvel*-0.5);
                    console.log(xvel);
                }
                $("circle").css({
                    top:$("circle").offset().top+yvel/16,
                    left:$("circle").offset().left+xvel/16
                });
            },8);
    </script>
    <style>
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600' rel='stylesheet' type='text/css'> * {
            margin: 0;
        }
        html,
        body {
            -webkit-text-smoothing: antialiased;
            height:100%;
            overflow:hidden;
            color: #fff;
            background-color: #181818;
        }
        circle{
            position:absolute;

            top:0;
            left:0;

            width:20px;
            height:20px;

            border-radius:10px;
            background:#fff;
        }
        </style>
</head>

<body>
    <circle></circle>
</body>

</html>

I'm not using canvas because I've already tried to create this minigame using EaselJS, but I found lots of problems and there's no reason to use it in my case, since this game doesn't have any images (then there's no need for hardware acceleration).

A:

This answer is a full update of a previous non-working answer.
The complete code of the answer is available at the bottom.
I had to check all browser to see what were the problems:
-On Chrome all were working perfectly so I had nothing to change.
-On Safari the ball was bouncing on the bottom and on the right. I figured out that the problem was caused by a position which was set in float and not in int so I just had to round the displacement.
$("circle").css({
top:Math.round($("circle").offset().top+yvel/16),
left:Math.round($("circle").offset().left+xvel/16)
});

My first answer was resolving the problem by cheating in displacements, this time the answer fix it. This amelioration shouldn't affect Chrome (but I can't test it now).
-On Firefox the ball was stopping before the bottom of the page. I just had to change comparators for collision by the body and add a margin of 0px to it.
In older versions of Firefox, when you press UP the ball was going a little DOWN before going UP, I his this bug is due to the xvel--, xvel++, yvel-- and yvel++ that are faster than  xvel+=2, xvel-=2, yvel+=2 and yvel-=2 so I replace them by two times ++xvel, two times --xvel, two times ++yvel and two times --yvel which should be faster (again I can't test it right now so I hope this is working). These amelioration should't affect Chrome and Safari.
Then I optimise your code to make it more efficient.
Your HTML hasn't change.
Your css is now:
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700,600' rel='stylesheet' type='text/css'> * {
            margin: 0;
        }

        html, body {
            -webkit-text-smoothing: antialiased;
        height:100%;
        overflow:hidden;
            color: #fff;
            background-color: #181818;
            margin: 0px;
        }

    circle {
        position:absolute;
        top:0;
        left:0;
        width:20px;
        height:20px;
        border-radius:10px;
        background:#fff;
    }

Your JavaScript is now:
var yvel = 0, xvel = 0;
    var up = false, // W or arrow up
            left = false, // A or arrow left
            right = false, // D or arrow right
            down = false; // S or arrow down

            // Keydown:
            document.addEventListener("keydown", function (evt) {
                if (evt.keyCode == 87 || evt.keyCode == 38) { // up
                    up = true;
                }
                if (evt.keyCode == 65 || evt.keyCode == 37) { // left
                    left = true;
                }
                if (evt.keyCode == 68 || evt.keyCode == 39) { // right
                    right = true;
                }
                if (evt.keyCode == 83 || evt.keyCode == 40) { // down
                    down = true;
                }
                if (evt.keyCode == 8 || evt.keyCode == 80) { // del/p
                }
            });
            // Keyup:
            document.addEventListener("keyup", function (evt) {
                if (evt.keyCode == 87 || evt.keyCode == 38) { // up
                    up = false;
                }
                if (evt.keyCode == 65 || evt.keyCode == 37) { // left
                    left = false;
                }
                if (evt.keyCode == 68 || evt.keyCode == 39) { // right
                    right = false;
                }
                if (evt.keyCode == 83 || evt.keyCode == 40) { // down
                    down = false;
                }
            });

            function y(obj){
                return $(obj).offset().top;
            }
            function x(obj){
                return $(obj).offset().left;
            }

            setInterval(function(){

                // Keydown/keyup handler:
                if (up) {
                    --yvel;
                    --yvel;
                } else if (yvel < 0) {
                        yvel++;
                }
                if (left) {
                    --xvel;
                    --xvel;
                } else if (xvel < 0) {
                        xvel++;
                }
                if (right) {
                    ++xvel;
                    ++xvel;
                } else if (xvel > 0) {
                        xvel--;
                }
                if (down) {
                    ++yvel;
                    ++yvel;
                } else if (yvel > 0) {
                    yvel--;
                }

                var nextposx = $("circle").offset().left+xvel/16;
                var nextposy = $("circle").offset().top+yvel/16;

                if(nextposy < 0 || nextposy+20 > $('body').height()){
                    yvel = Math.round(yvel*-0.5);
                }
                if(nextposx < 0 || nextposx+20 > $('body').width()){
                    xvel = Math.round(xvel*-0.5);
                }
                $('circle').css({
                    top:Math.round($('circle').offset().top+yvel/16),
                    left:Math.round($('circle').offset().left+xvel/16)
                });
            },8);

You have a JSFiddle of the result here.
The only error that remain is that in Firefox the circle exceeds of few pixels at the right but it's very minimal.
Sorry if my english is bad, I hope you get all what I write.
I think my job here is done...
Have fun with that =D.


Q:

Can I use Materializecss with dart?

Google made some neat presets which can be found on http://materializecss.com/
I am mainly interested in the floating button, but I would like to know about the whole if I can use it with dart. The reason I worry is, because it consists not only of CSS and fonts but also of JS - and that requires JQuery to work, which I don't think I can bring to work with dart.
Or can I simply drop JQuery next to the Materialize-folder?

A:

As I have tried recently, yes it can be used. Any css and javascript framework can be used from dart. jQuery/Materializecss javascript API might be tricky to use so you better get familiar with js interoperability. In my experiment I ended up switching to bootstrap and a css framework on top of it (currently investigating http://fezvrasta.github.io/bootstrap-material-design/ and paper theme from bootswatch). While it might look less "material", I found the elements more mature (that is a pure personal opinion) and I have already a lot of js wrapper for jQuery and bootstrap .


Q:

IIS Express fails when Azure Web Role start

I have Asp.Net MVC web application. It works fine when I run it on Local IIS or IIS Express.
I deployed it as Azure Web Site. It works fine.
Now I want to deploy application as Azure Cloud Service. I add Azure Cloud Service project to my solution. Then I add Web Role from existing web project.
When I run my solution under Azure Emulator it does not work. I have an error "IIS Express Worker Process has stopped working". In Windows event viewer I have only IIS Crashed error, without any details.
In task manager I have Windows Azure Emulator, but I have no IIS express with my web role.
But when I deploy my solution to azure cloud service, it works like a charm. I'm confused what is wrong. One more point. If I create new web-application in my solution and create web role for new project, then it works fine!
I'm confused what is wrong. Any ideas?

A:

I found the problem. I have this block in my web.config file
<applicationInitialization doAppInitAfterRestart="true">
    <add initializationPage="/" />
</applicationInitialization>

This cause the IIS Express crashing when web role started.
Hope this helps anybody else.


Q:

Template deduction failure of template of template (with inheritance in-between), is there a better way ?

The problem
I had the following scheme in my code,
#include <memory>
#include <iostream>

template <class T>
struct A {};

template <class T>
struct Z {};

template <class T, class U>
struct B : A<T>, Z<U> {};

template <class T>
struct C : B<T, T> {};

template <class T>
void foo(const std::shared_ptr<A<T>>& a)
{
    std::cout << "HI !" << std::endl;
}

int main()
{
    auto c = std::make_shared<C<char>>();

    foo(c);

    return 0;
}

But the compiler could not substitute the template parameters properly:
main.cpp: In function 'int main()':
main.cpp:26:10: error: no matching function for call to 'foo(std::shared_ptr<C<char> >&)'
     foo(c);
          ^
main.cpp:17:6: note: candidate: template<class T> void foo(const std::shared_ptr<A<T> >&)
 void foo(const std::shared_ptr<A<T>>& a)
      ^~~
main.cpp:17:6: note:   template argument deduction/substitution failed:
main.cpp:26:10: note:   mismatched types 'A<T>' and 'C<char>'
     foo(c);
          ^

The fix
So I changed foo to this:
template <class T, template <class> class U>
void foo(const std::shared_ptr<U<T>>& a)
{
    std::cout << "HI !" << std::endl;
}

A better way ?
It works, but it doesn't feel right as the template constraints on the types are now really loose which usually end up into more obfuscated error message.
Is there a better way to handle these kind of template deduction failures ?
Play with the example on Coliru
http://coliru.stacked-crooked.com/a/d4ebc14105c184df

A:

There is a way.  You can choose to constrain the template manually with a bit of template metaprogramming so that only pointer types (can be extended to work with all sorts of pointer types, but only works with both unique_ptr and shared_ptr in this case (actually with all smart pointer types that have an element_type type alias)) of derived classes can be used.
#include <memory>
#include <iostream>

namespace {

    /**
     * Get the template type of a template template type
     */
    template <typename T>
    struct GetType;
    template <typename T, template <typename...> class TT>
    struct GetType<TT<T>> {
        using type = T;
    };
} // namespace <anonymous>

template <class T>
struct A {};

template <class T>
struct Z {};

template <class T, class U>
struct B : A<T>, Z<U> {};

template <class T>
struct C : B<T, T> {};

template <class T, typename std::enable_if_t<std::is_base_of<
    A<typename GetType<typename std::decay_t<T>::element_type>::type>,
    typename std::decay_t<T>::element_type>::value>* = nullptr>
void foo(const T&)
{
    std::cout << "HI !" << std::endl;
}

int main()
{
    auto c = std::make_shared<C<char>>();
    auto c_uptr = std::make_unique<C<char>>();

    foo(c);
    foo(c_uptr);

    return 0;
}

This will now work both with unique_ptr and shared_ptr.  You can chose to make it more general by checking the type of pointer contained (element_type in the example) by using decltype with .get() on the smart pointer, and make a trait that detects if the pointer passed is a primitive pointer and if so just uses the type itself.  But you get the point.


Q:

Thread pooling and multi core systems

Do you think threadpooling design pattern is the way to go for the multi-core future?
A threadpooling library for instance, if used extensively, makes/force the application writer
(1) to break the problem into separate parallel jobs hence promoting (enforcing :) ) parallelism
(2) With abstraction from all the low level OS calls, synchronization etc etc makes programmer's life easier. (Especially for C programmers :) )
I have strong belief its the best way (Or One of the "best" ways :) ) for multi-core future...
So, my question is, am I write in thinking so or I am in some delusion :)
Regards,
Microkernel

A:

Thread pooling is a technique that involves a queue and a number of threads taking jobs from the queue and process them. This is in contrast to the technique of just starting new threads whenever a new task arrives.
Benefits are that the maximum number of threads is limited to avoid too much threading and that there is less overhead involved with any new task (Thread is already running and takes task. No threat starting needed).
Whether this is a good design highly depends on your problem. If you have many short jobs that come to your program at a very fast rate, then this is a good idea because the lower overhead is really a benefit. If you have extremely large numbers of concurrent tasks this is a good idea to keep your scheduler from having to do too much work.
There are many areas where thread pooling is just not helpful. So you cannot generalize. Sometimes multi threading at all is not possible. Or not even desired, as multi threading adds an unpredictable element (race conditions) to your code which is extremely hard to debug.
A thread pooling library can hardly "force" you to use it. You still need to think stuff through and if you just start one thread... Won't help.


Q:

Hot to get random date in range

I have two dates as strings (dd-mm-yyyy).
How can i get a random date between these two dates?

A:

You can convert the dates to Unix timestamp. Randomly pick a timestamp between the two timestamps and convert it back to date.


Q:

how to design this UI

I am trying to design a UI as like in an iPhone app. The image of the design is as follows

In the above image all the white boxes are of a list view. In those list view i am placing an image View and two set of text view. I have placed a overall custom list view and in that custom list view using relative layout i have place the image view and two text view.
now i want to draw a line between the two text view and when i click on the second text view i am moving to a new activity. At that time i want to show that only the second text view is been clicked.

A:

Use a RelativeLayout:

The image android:layout_alignParenLeftt="true"
the first two textViews android:layout_toRightOf="@id/myimage",
the other textviews below the previous ones (e.g. android:layout_below="@id/author" and with a layout_width="fill_parent"

Check Romain Guy's blog post for a tutorial on a similar (simpler) setup: http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html

A:

Check this http://www.androidsnippets.com/clickable-listview-items

The ClickableListAdapter bases on the
  API-Demo-Example "Efficient List
  Adapter". It was refactored to provide
  a better reusability. Additionally,
  you can connect OnClickListener and/or
  OnLongClickListener to each View of
  your list item. This allows you to
  create complex interactive lists, or
  simply using a customized checkbox
  version.

I had implemented this in a project minus the image view. Heres a screenshot.


Q:

Xamarin: Use the Notify method that has a UICompletion Handler is not available

I have this static Source Analysis warning in Xamarin Studio:

API Usage Issue: Use the *Notify method that has a UICompletion Handler completion parameter, the bool will tell you if the operation finished

when invoking UIView.Animate(double duration, Action animation, Action completion):
UIView.Animate(duration,
   () => Animation(),
   () => Completion());

However, I can't seem to be able to pass parameters to the lambda expression. None of these options compile:

(bool) => Completion()
(finished) => Completion()
(bool finished) => Completion()

How can I pass this finished parameter to to completion block?

A:

The Animate static methods use NSAction methods, more of a C# style annotation and AnimateNotify use UICompletionHandler methods, ObjC-style...
The Animate methods are just helper wrappers around AnimateNotify:
So instead of:
UIView.Animate(30, () => { }, () => { });

You can use:
UIView.AnimateNotify(30, () => { }, (bool finished) => { });

The result is the same....
Ref: https://github.com/xamarin/xamarin-macios/blob/fc55e4306f79491fd269ca2495c6a859799cb1c6/src/UIKit/UIView.cs#L121

A:

Looks like you might be able to use one of the AnimateNotify or AnimateNotifyAsync method overloads as that passes back UICompletionHandler with a bool:
UIView.AnimateNotify(10, () => { }, finished => { });

OR
await UIView.AnimateNotifyAsync(10, () => { }, finished => { });


Q:

Objective C - Core Text, number of characters in a line?

Given an index for current character, how can I determine the number of line that the selected character is at?
Given a CTLine how can I determine the number of characters in it?

A:

For the first one:
int currentCharacterIndex = 12; // You define this.
CFArrayRef lines = CTFrameGetLines(frame);
int currentLine = 0;
for (CTLineRef line in lines) {
    currentLine++;
    CFRange range = CTLineGetStringRange(line);
    if (currentCharacterIndex > range.location)
        break;
}
// Current line is now the line that the currentCharacterIndex resides at

For the second one:
CFRange range = CTLineGetStringRange(line);
CFIndex length = range.length; // Number of characters

Can't be sure these work as I haven't tested them but it's worth a go.


Q:

JTable CellRenderer changes foreground color only when focused

I am trying to implement a cellrenderer that changes color depending on the value of an integer. However, the color of the cell changes only when focused on. See picture below.
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
        int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    switch (column) {
        case 1:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
        case 3:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
    }
    if (column == 4 && (Integer)value > 0) {
        setForeground(Color.green);
    } else {
        setForeground(Color.red);
    }
    return this;
}

A:

I guess your table isn't firing the correct update event, so there is no redraw of the cell.
A MRE incorporating all the given code that fails to reproduce the problem:
import java.awt.*;
import javax.swing.*;

class Code extends javax.swing.table.DefaultTableCellRenderer {
    public static void main(String[] args) throws Throwable {
        java.awt.EventQueue.invokeLater(Code::go);
    }
    private static void go() {
        JTable table = new JTable(
            new Object[][] {  { 0, 1, 2, 3, 4 }, { 1, 2, 3, 4, 5 } },
            new Object[] { "0", "1", "2", "3", "3" }
        );
        table.setDefaultRenderer(Object.class, new Code());
        JFrame frame = new JFrame("Table");
        frame.add(table);
        frame.pack();
        frame.setVisible(true);

        new Timer(1000, event -> {
            table.setValueAt(
                -(Integer)table.getValueAt(0, 4),
                0, 4
            );
        }).start();
    }
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

        switch (column) {
            case 1:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
            case 3:this.setFont(this.getFont().deriveFont(Font.BOLD)); break;
        }
        if (column == 4 && (Integer)value > 0) {
            setForeground(Color.green);
        } else {
            setForeground(Color.red);
        }
        return this;
    }
}


Q:

How can I simplify this function - return key value from array?

I have written the following function which returns the value of a key which is the account prefix of a cPanel account.
[prefix] = 'oneclick_'
The function works but I'm only a beginner and I'm sure there's an easier and better way to write this function.
<?php
// Get data from cPanel API
$array = $cp_db_restrictions['cpanelresult']['result']['data'];

//Pass array of $data to function
db_prefix( $array );

//Function accepts array of $data
function db_prefix( $array ) {
  if( count( $array ) > 0 ) {
      return $array['prefix'];
  } else {
      return "No prefix";
  }
}
?>

<?php echo db_prefix($array); ?>

The function echos "oneclick_"
EDIT:
This is the code which returns the array:
$cp_db_restrictions = $cpanel->uapi(
      'Mysql', 'get_restrictions'
  );

However, I'm not quite sure how to add that into the function. When I try I get the following error message:
Notice: Undefined variable: array in ...
Fatal error: Uncaught Error: Call to a member function uapi() on null in...
SOLUTION*
So, thanks to Nick's answer here is the solution. You must make sure to declare the cPanel class at the top of the document and within the same PHP tags.
<?php
include("/usr/local/cpanel/php/cpanel.php"); // Instantiate the CPANEL object.
$cpanel = new CPANEL();

function db_prefix($cpanel) {
      $cp_db_restrictions = $cpanel->uapi('Mysql', 'get_restrictions');
      $array = $cp_db_restrictions['cpanelresult']['result']['data'];
      return $array['prefix'] ?? 'No prefix';
} ?>
<?php echo db_prefix($cpanel); ?>

A:

In PHP7 you can just use the null coalescing operator ??:
echo $array['prefix'] ?? 'No prefix';


Q:

Windows C++ highlighting

Could anyone recommend me an Editor with C++ highlighting? I know there is VIM
but would prefer an easier one where I could use all the classical WINdows commands.
Many thanks

A:

On windows, If you are looking for free and pretty well featured IDE then the Eclipe CDT is nice. Also check out the Visual C++ Express.
If on a Mac XCode is free and awesome, Eclipse works there as well.
For pay options Visual Studio is still the best on windows.
If you are looking for just an editor then Notepad++ or Context works.

A:

Notepad++ is similar to notepad2.  Another option for you to check out.  Does line numbers as well, code folding, and code auto-complete.

A:

I'm surprised Visual C++ Express Edition doesn't have more positive comments. I use Visual Studio for everything it supports, and Programmer's Notepad 2 or ConTEXT for highlighting file types it doesn't support. The performance difference of Visual Studio against Eclipse is laughable - almost makes you say "wait, you were serious?"
Edit: You didn't say free in the first post. The paid version(s) of Visual Studio is the definitive Windows development IDE.


Q:

How to check List type alias in Python?

x: List[int]

If I have code like above, which is declaring an object x with List with an explicit type int using Python's typing library, is there a way that I can find out that this object x is an integer type? Not just a list type.
I know if I do type(x) it'll give <class 'list'>, but doesn't say it's an integer type list. I also tried type(x[0]) and it gave <class 'NoneType'>, which makes sense that it's an empty list. I can't initialize the first element with integer type value (i.e. x: List[int] = [0]) or something as it is assigning an arbitrary value to the list, which may cause an issue if we do not handle (override to the proper value) it properly and it's risky (for me at least).
This is an important feature that I have to have in the team project that I am working on. Can anyone with a good Python knowledge help me?
Thanks in advance!

A:

Python is a dynamically typed language, so even with type hinting, the type itself is not enforced.  Therefore List[int] does not guarantee any elements added to x is an int type.
If you do need to ensure the type is int, you will need to manually check it:
if all(isinstance(i, int) for i in x):
    # code things for when x is indeed a list of all ints
else:
    # code things for when x is not all int

You might also consider doing an assert instead:
>>> x = [1, 2, '3']
>>> assert all(isinstance(i, int) for i in x), 'Values must be all int type!'

>>> Traceback (most recent call last):
      File "<pyshell#249>", line 1, in <module>
        assert all(isinstance(i, int) for i in x), 'Values must be all int type!'
    AssertionError: Values must be all int type!

If you have multiple List[...] that you want to check for, you can make your own checker function:
def validate(lst: list, dtype):
    return all(isinstance(i, dtype) for i in lst)

>>> validate([1, 2, '3'], int):
>>> False

>>> validate(['a', 'b', 'c'], str):
>>> True


Q:

Why doesn't y=x work for arrays?

Why won't the following C code compile? It seems like it should just change the pointers' address but it throws an error.
int x[10];
int y[10];
y=x;

A:

x and y are arrays, not pointers. In C, arrays can't change size or location; only their contents can change. You can't assign arrays directly.
If you want a pointer to one of the arrays you can declare one like this.
int *z = x;

If you need to assign an array you can create a struct that contains an array. structs are assignable in C.

A:

What pointers? You have two arrays. Arrays are not pointers. Pointers hold the address of a single variable in memory, while arrays are a contiguous collection of elements up to a specified size.
That said, arrays cannot be assigned. Conceivably, saying y = x could copy every element from x into y, but such a thing is dangerous (accidentally do an expensive operation with something as simple looking as an assignment). You can do it manually, though:
for (unsigned i = 0; i < 10; ++i)
    y[i] = x[i];

A:

y is statically allocated. You can't change where it points.


Q:

What is wrong with the word "performant"?

I keep getting the red underlining in Word whenever I write the word "performant". Here I intend to refer to something that performs well or better than something else (i.e., it's more performant).
Is there something wrong with that word? Does it mean what I actually want it to say?

A:

Whether or not "performant" is actually a real word has been debated for some time.
It does not appear in the dictionary, nor does Google definitions include it.
While it has been used before and appears in wiktionary, I would tend to avoid using it until the word becomes, well...a word.
Is there any reason you could not use one of the following instead?

Example A performed better than Example B.

or

Example A outperformed Example B.

Jon Galloway's blog article Performant isn't a word is an example of someone who used "performant" extensively only to be told it was not a word. While the research he did on the subject was conducted in 2007, it certainly seems to remain valid today.

A:

I use the word performant often, and its meaning (in my opinion) is subtly different from that of fast or efficient. The most performant network might not be the fastest, or the most efficient, but the one which provides the best overall service.

My IT systems are both performant and resilient.

The above seems (to me) to be very succinct. The word performant implies speed, accuracy, flexibility and capability — it implies that my IT systems are just right for my environment. They might not be the fastest, and not necessarily the most feature-packed, but they're just right for my needs.
I like performant.

A:

It does mean what you want to say, possibly, but it's not the clearest way of saying it.
Performant is being increasingly used, therefore it deserves to be considered a word. I still have misgivings about it though, largely because it seems redundant: you could instead say "fast" or "efficient".
If something's fast, why not just say so, instead of using the word performant?
And more performant is even sillier, when you could just say faster.
At the moment, it's still the sort of word you tend to see written in press releases or spoken by marketing people. To me it's a weasel-word like "premier", which sounds promising but technically meaningless and legally non-binding (what does "premier" actually mean? First, biggest, fastest, best-selling or highest ranking sales by value?)
The word performant could mean one of several things depending on the context (fast, efficient, small, optimal) and not using one of those alternative words suggests (to me) that the speaker/writer doesn't know what he's talking about, or for some reason doesn't want me to know what he's talking about.
Go ahead and use the word if you like, but I won't trust you, because you'll sound like a sales brochure.


Q:

Convert unicode representation of number to ascii string

I've been looking for a simple way to convert a number from a unicode string to an ascii string in python. For example, the input:
input = u'\u0663\u0669\u0668\u066b\u0664\u0667'

Should yield '398.47'.
I started with:
NUMERALS_TRANSLATION_TABLE = {0x660:ord("0"), 0x661:ord("1"), 0x662:ord("2"), 0x663:ord("3"), 0x664:ord("4"), 0x665:ord("5"), 0x666:ord("6"), 0x667:ord("7"), 0x668:ord("8"), 0x669:ord("9"), 0x66b:ord(".")}
input.translate(NUMERALS_TRANSLATION_TABLE)

This solution worked, but I want to be able to support all numbers-related characters in unicode, and not just Arabic. I can translate the digits by going over the unicode string and running unicodedata.digit(input[i]) on each character. I don't like this solution, because it doesn't solve '\u066b' or '\u2013'. I could solve these by using translate as a fallback, but I'm not sure whether there are other such characters that I'm not currently aware of, and so I'm trying to look for a better, more elegant solution.
Any suggestions would be greatly appreciated.

A:

Using unicodedata.digit() to look up the digit values for 'numeric' codepoints is the correct method:
>>> import unicodedata
>>> unicodedata.digit(u'\u0663')
3

This uses the Unicode standard information to look up numeric values for a given codepoint.
You could build a translation table by using str.isdigit() to test for digits; this is true for all codepoints for which the standard defines a numeric value. For decimal points, you could look for DECIMAL SEPARATOR in the name; the standard doesn't track these separately by any other metric:
NUMERALS_TRANSLATION_TABLE = {
    i: unicode(unicodedata.digit(unichr(i)))
    for i in range(2 ** 16) if unichr(i).isdigit()}
NUMERALS_TRANSLATION_TABLE.update(
    (i, u'.') for i in range(2 ** 16)
    if 'DECIMAL SEPARATOR' in unicodedata.name(unichr(i), ''))

That produces a table of 447 entries, including 2 decimal points at U+066b ARABIC DECIMAL SEPARATOR and U+2396 DECIMAL SEPARATOR KEY SYMBOL; the latter is really just a made-up symbol to put on the decimal separator key on a numeric keypad where a manufacturer doesn't want to commit themselves to printing a , or . decimal separator on that key.
Demo:
>>> import unicodedata
>>> NUMERALS_TRANSLATION_TABLE = {
...     i: unicode(unicodedata.digit(unichr(i)))
...     for i in range(2 ** 16) if unichr(i).isdigit()}
>>> NUMERALS_TRANSLATION_TABLE.update(
...     (i, u'.') for i in range(2 ** 16)
...     if 'DECIMAL SEPARATOR' in unicodedata.name(unichr(i), ''))
>>> input = u'\u0663\u0669\u0668\u066b\u0664\u0667'
>>> input.translate(NUMERALS_TRANSLATION_TABLE)
'398.47'


Q:

How to reinitialize HammerJS on resize event?

How do I reinitialize HammerJS on resize event?
My problem is when I trigger the resize event the Selectors reset, and using jQuery for matching a container $('.container') will return an index of 0 all the time.. on document ready it worked before.
The $('.container') appears more than once so it should increment on swipe event.
Anyone got any ideas ?
$(document).ready(function() {
    mobileCalculus(animation);
    swipeActions( $('.home-element-wrapper'), $('.home').width());

    $(window).on('resize', function() {
        mobileCalculus(animation);
    });
});

function swipeActions(parent, offset) {
    var curInd = 0;
    var theThumb = $('.thumb');
    var myElement = document.getElementById('main-swipe');
    var max = theThumb.length - 1;

    // create a simple instance
    // by default, it only adds horizontal recognizers
    var mc = new Hammer(myElement);

    // listen to events...
    mc.on("swipeleft", function(ev) {

        curInd = $('.thumb.active').index() + 1;
        if (curInd > max) {
            curInd = max;
        }
        var newML = offset * curInd;
        theThumb.removeClass('active');
        theThumb.eq(curInd).addClass('active');
        console.log($('.thumb.active').index() + 1);
        parent.css({
            'margin-left': '-'+newML+'px'
        });
    });
    mc.on("swiperight", function(ev) {
        curInd = $('.thumb.active').index() - 1;
        if (curInd < 0) {
            curInd = 0;
        }
        var newML = offset * curInd;
        theThumb.removeClass('active');
        theThumb.eq(curInd).addClass('active');
        parent.css({
            'margin-left': '-'+newML+'px'
        });
    });

}

For example jquery has a function called .off which deactivates the event after which we can put a new event on the selector.
$('element').off('swiperight').on('swiperight')

A:

Apparently I've figured it out. I had to make the var mc = new Hammer(myElement); value "global". Apparently when I reinitialized it the second time in swipeActions(), the off() function would not work, so initializing the value only once and then performing off() and on() with it makes everything work.


Q:

Ubuntu 19.04 - VMWare kernel modules updater

I ran this command:
apt-cache search linux-headers-$(uname -r)

and it returns the output

linux-headers-5.0.0-13-generic - Linux kernel headers for version 5.0.0 on 64 bit x86 SMP

Then I ran the following command to update the linux headers:
sudo apt-get install linux-headers-$(uname -r)

Still, it gets stuck (VMware Kernel Module Updater) at the Compiling/Virtual Machine Monitor.
Does anyone know how to solve this?

A:

I had the same problem and I fixed it like this.
Downloaded this link:
https://github.com/mkubecek/vmware-host-modules/archive/w15.0.4-k5.0.tar.gz
Extracted the files.
Then ran these commands from terminal of the folder:

tar -cf vmmon.tar vmmon-only
tar -cf vmnet.tar vmnet-only
sudo cp -v vmmon.tar vmnet.tar /usr/lib/vmware/modules/source/


Q:

Wörter mit selber Bedeutung, aber unterschiedlichen Artikeln

Mir ist heute beim Spazierengehen aufgefallen, dass die Wörter

die Geldbörse, das Portemonnaie und der Geldbeutel

die gleiche Bedeutung, aber unterschiedliche Artikel haben – was ich irgendwie erstaunlich finde.
Gibt es einen Fachbegriff dafür, bzw. kennt ihr weitere solche Wörter?

A:

Das grammatische Geschlecht hat absolut nichts mit dem Bezeichneten zu tun. Nichts. Bei neuen Wörtern spielt teils gleiche Lautung (der Blog), teils der Originalartikel (der Latte) und teils tatsächlich ein deutsches Synonym (die Latte) eine Rolle.
Im Großen und Ganzen aber ist das nicht der Fall und das Geschlecht hängt von Wortbildung und Etymologie ab. Daher gibt es auch unzählige Beispiele.

Das Auto, der Wagen, die Karre
der Blick, die Sicht, das Panorama
die Frau, das Weib
…


Q:

$\int_t^T 1_C\cdot A\;d\!X=1_C\cdot\int_t^T A\;d\!X$ for $C\in\mathcal F_t$?

Given a semi-martingale $X$ on a filtered probability space $(\Omega,\{\mathcal F_t\}_{t\le\infty},P)$, an integrand $A$ and a set $C\in\mathcal F_t$. Show: $$\int_t^T 1_C\cdot A\;d\!X=1_C\cdot\int_t^T A\;d\!X.$$
Is this statement true? How could one prove it? Where can I find the prove?

A:

In this answer I will only consider the case that $(X_t)_{t \geq 0}$ is a Brownian motion; the general case is not even more technical, but notation gets more complicated.

The claim holds for simple integrands. This follows directly from the definition of the stochastic integral
Let $f \in L^2([0,T] \times \Omega)$ be progressively measurable, i.e. $$\mathbb{E} \left( \int_0^T f^2(s) \, ds \right)<\infty.$$ Then there exists a sequence $(f_n)_{n \in \mathbb{N}}$ of simple integrands such that $$\|f_n-f\|_{L^2([0,T] \times \mathbb{P})} \to 0.$$  This implies in particular $$\|(f_n-f) 1_C\|_{L^2([0,T] \times \mathbb{P})} \leq \|f_n-f\|_{L^2([0,T] \times \mathbb{P})} \to 0. \tag{1}$$ Consequently, by the definition of the Itô integral, $$\begin{align*} \int_t^T 1_C \cdot f(s)  \, dX_s &= L^2-\lim_{n \to \infty} \int_t^T 1_C \cdot f_n(s) \, dX_s \\ &= L^2-\lim_{n \to \infty} \left(1_C \int_t^T f_n(s) \, dX_s \right) \\ &= 1_C \int_t^T f(s) \, dX_s. \end{align*}$$


Q:

Find the general solution of the simple harmonic oscillator

Question: Find the general solution of the simple harmonic oscillator equation,
$$\ddot{x}=-\omega^2x$$
My answer: $x(t)=A\cos(\omega t)+B\sin(\omega t)$
Solution given: $x(t)=x_0\cos(\omega t)+\frac{\dot{x_0}}{\omega}\sin(\omega t)$
I can understand inputting $x_0$ for $A$, but can't understand inputting $\frac{\dot{x_0}}{\omega}$ for $B$. Where does the input for $B$ come from?

A:

The input of $B$ is given by the initial value of the velocity. Since your ODE is of second order, you need to give conditions on the velocity, too. Hence, The condition $$\dot{x}(0)=\dot{x_0}$$ leads to $B=\frac{\dot{x_0}}{\omega}$.


Q:

Embedded collection of embedded collection - isValid issue

Let's say I've got a FooType with BarType (collection; cascade validation setted to true) which itself has a FooBarType (collection; cascade validation setted to true)
So
//FooType
$builder
  [...]
  ->add('bar', 'collection', [
      //...
      'type' => new BarType()
      'error_bubbling' => false,
      'allow_add' => true,
      'allow_delete' => true,
      'required' => false,
      'by_reference' => false,
      ]
  );

//BarType
$builder
  [...]
  ->add('fooBar', 'collection', [
      //...
      'type' => new FooBarType()
      'error_bubbling' => false,
      'allow_add' => true,
      'allow_delete' => true,
      'required' => false,
      'by_reference' => false,
      ]
  );

Now the problem is, if I add from GUI one element to fooBar collection that's invalid due to Valid constraints, the error is attached to WHOLE collection (and not to collection's element field) and the element claim to be valid (saw from profiler). If I add from GUI more than one element to fooBar collection is still invalid, invalid status (error) is still attached to collection, first element still claims to be valid but other ones has error attached (that is what I desire).
Question
Why such behavior? Any ideas?

Additional info
This is the invalid path shown in profiler

Object(Symfony\Component\Form\Form).data.bar[0].foobar[0].fieldName =
null

that got the actual value, but is "tied" to collection and not to field element.
Symfony version: 2.7

A:

Solution was pretty "easy" but hard to find.
I asked to myself if it was better to delete the question or to answer here directly. As I'm pretty sure that this error could happen also to other people and "investigation" isn't so easy, I've decided to answer indeed.
Mistake
Mistake was onto collection prototype javascript and its indexes. I'm talking about
http://symfony.com/doc/current/cookbook/form/form_collections.html
addTagForm() javascript function, that in my case was customized in order to reach what I need. The problem was I made a mistake onto index calculation so every new collection was starting from 1 instead of 0.
Thus, when form validation component tried to attach error to right field, producing this

Object(Symfony\Component\Form\Form).data.bar[0].foobar[0].fieldName =
  null

no field (at foobar level) with index = 0 was find and error was attached to its parent (the collection).
So when I added more then one element to collection, every error I saw was relative to "other" field (in a n-1 fashion).
How i spot this error
Using profiler > form , onto left column you can spot all form fields with error attached. Observing indexes you can find what I'm talking about.


Q:

How to create independent/fixed inset maps with leaflet?

I am trying to create a leaflet map of the USA focusing on the contiguous 48 states and then add two inset maps of Alaska and Hawaii on the side. The problem is that addMiniMap() option creates an interactive inset mini map that just shows the location of the zoom window of the main map. Rather than this, I want to have inset maps with fixed position and zoom on Alaska and Hawaii, while the main map remains interactive.

A:

You need to set centerFixed and zoomLevelFixed:

centerFixed
Applies a fixed position to the minimap regardless of the main map's view / position. Prevents panning the minimap, but does allow zooming (both in the minimap and the main map). If the minimap is zoomed, it will always zoom around the centerFixed point. You can pass in a LatLng-equivalent object. Defaults to false.
zoomLevelFixed
Overrides the offset to apply a fixed zoom level to the minimap regardless of the main map zoom. Set it to any valid zoom level, if unset zoomLevelOffset is used instead.

Source


Q:

UK visa refusal due to wrong record from 9 years ago

I'm helping my significant other (who lives in another country) to apply for a visitor visa to the
UK. They have never been here, but they got refused once before almost
10 years ago (something about lack of ties) together with the other
people that applied with them (it was a group that hoped to visit the
UK for a summer language school). Unfortunately, they got refused
again. This is the letter:

I was already mentally prepared to try to find an explanation (possibly they changed job title in 2007, and that's why the document in 2009 might have had a different date than in the latest application), so that we could apply again, with an explanation for the discrepancy that made it obvious that it was a mistake without any intention of deception. (I know that applying again would make sense only if we can provide further documentation. Hopefully more detailed employment information and a written apology would be enough to demonstrate good faith)
But then they retrieved the application from 2009, with the attached document for employment confirmation. You can see the original here:

And this is the translation:

As you can see, nowhere is the "1st January 2007" date mentioned, nor 2007 at all.
I'm now a bit lost: we cannot appeal, so the only thing we can do is to apply again with amended documentation, but the documentation we have contradicts the reason for the refusal!
It's been 3 weeks now since they originally sent the application, (for some reason the reply arrived today even if the letter is dated 09 May) and the flight ticket has already been purchased. To have any hope of avoiding a change of plans, I think that the only venue we have is to try to apply again (rather than an appeal), possibly with the expedited process (which I understand would take only a couple of days) to allow for more time for us to change plans in case things will go wrong.
I don't think that contacting a solicitor would really help us (given that we cannot appeal), but what should we provide if applying again? If they think that we're being deceptive, a further refusal under 3.7 would be extremely inconvenient.
The obvious thing would be to send copies of the old documentation, in which the correct year can be clearly seen. Maybe by attaching a brief letter that points out that the old application and the newer one are not in conflict.
But maybe the bureaucracy won't easily accept a mistake on their part? Maybe we should apologize even for a mistake that we haven't made? What kind of justification for a non-existing discrepancy could we ever provide? (I don't think this is a good idea).
I appreciate any feedback or suggestion you can provide. Thank you.

A:

So, this just got resolved positively:
We got a solicitor involved, they recommended:

applying again
if that fails, a judicial review (that's a different thing than an appeal or an administrative review)

For both, knowing what information exactly UKVI used for their previous decision would be quite useful, and that can be obtained for free with a subject access request.
Instead of waiting on the SAR documents to get back to us, my SO submitted a new visa application right away (with the information that has been provided above in the question and a cover letter). The decision was positive in this case and the visa has been granted (which means that luckily plans didn't have to change),
Though this means that until we'll see the SAR documents, it will not yet be clear if they had any wrong records on their side or what was actually the explanation for the last refusal.
I might update this when I'll get that information, and I could also provide a (redacted) copy of the cover letter, if people could find that useful.
Update:
This is the cover letter, attached with the latest application:

We also got the SAR file, and I got 2 interesting findings:

The mistake in the date (January 2007) doesn't appear to have been on UKVI's side: the copy of the application they have lists that date.
They didn't retain a copy of the employment confirmation that had been provided in 2009, for this reason I think that to clarify the original mistake it might be better to always provide our copy (even if hopefully that wouldn't be needed now that the latest application has been successful).


Q:

if $a, b$ belong to complex with $|a|=|b|=1$ and $|a+b|=2$ prove that $a=b$

I stumbled on this question:

If $a$ and $b$ are complex numbers  with $|a|=|b|=1$ and $|a+b|=2$. Prove that $a=b$.

I tried to do it using the fact that I can write a and b as  $a= c+zi$ and $b= d+xi$ and when I used the two conditions above I got $|a+b|=2(c^2-d^2) 2cd-2zx =2$, but i don't know how to move on. Could you try to help me?

A:

Let $a=\cos\alpha+i\sin\alpha$ and $b=\cos\beta+i\sin\beta$, where $\{\alpha,\beta\}\subset[0,2\pi)$.
Thus,
$$(\cos\alpha+\cos\beta)^2+(\sin\alpha+\sin\beta)^2=4$$ or
$$\cos(\alpha-\beta)=1$$ or
$$\alpha=\beta.$$
Done!

A:

Extended hint. $$\;4 = |a+b|^2 = (a+b)(\bar a + \bar b) = |a|^2+ a \bar b + \bar a b + |b|^2 = 2 + a \bar b + \bar a b \implies a\bar b+ \bar a b - 2= 0$$
But $|a|=1 \iff \bar a = 1/a$ and the same holds for $b$, so $a/b + b/a - 2 = 0 \iff (a-b)^2=0\,$.


Q:

Access Static member

I know that we can access Static member just with class name like this
Myclass.MyStaticMember

and no need to initialize this
but my question is why we cant access Static member from initialize object
Myclass.MyStaticMember obj =new  Myclass.MyStaticMember()
obj.MyStaticMember

is there related via CLR or .net framework architecture  or compiler

A:

It's a language decision, to make your code clearer. (It would have been entirely feasible for the C# compiler to compile the code into a static access based on the compile-time type of the variable.) If you write:
obj.StaticMember

it looks like the member is specific to obj - but it's not. Code shouldn't lie.
As an example of how confusing this can be, consider the following valid Java code (assuming a Runnable variable called runnable):
Thread thread = new Thread(runnable);
thread.start();
thread.sleep(1000);

Which thread does that send to sleep? The new one, of course - look, it's calling sleep() on the variable referring to the new thread. Except of course Thread.sleep is a static method, which always makes the currently executing thread sleep. That's not at all obvious from the code above. Fortunately, it wouldn't be valid in C#.
This is one area where the C# team apparently learned from Java's mistakes, which I'm jolly glad about. (Shame about some of the other aspects, but hey...)


Q:

Where to put client and db connection in python file

So I am building a mongo database class that will be provide access to inserting documents to the insertion service and provide access for viewing documents via a querying service. Right now I have the following for my database.py class:
import pymongo

client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

class DB_Object(object):

    """ A class providing structure and access to the Database """

    def add_document(self, json_obj):
        coll = db_connection["some collection"]
        document = {
            "name" : "imma name",
            "raw value" : 777,
            "converted value" : 333
        }
        coll.insert(document)

    def query_response(self, query):
            """query logic here"""

If I want concurrent queries and inserts with this class being called by multiple services is this the correct location for the lines:
client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

And is this a standard way to provide access?

A:

Your code is correct. You should continue to use the same MongoClient instance for all operations in your application, this will ensure that all operations share the same connection pool and use as few connections as possible--this will maximize your efficiency. MongoClient is thread-safe so this will work even if you have concurrent operations on multiple threads.


Q:

splunk check if message contains certain string

In Splunk search query how to check if log message has a text or not?
Log message:
message:     2018-09-21T07:15:28,458+0000 comp=hub-lora-ingestor-0 [vert.x-eventloop-thread-0] INFO  com.nsc.iot.hono.receiver.HonoReceiver - Connected successfully, creating telemetry consumer ...

and I want to check if message contains "Connected successfully, creating telemetry consumer ..." and based on this want to assign 1 or 0 to a variable
Splunk search Query
(index="05c48b55-c9aa-4743-aa4b-c0ec618691dd" ("Retry connecting in 1000ms ..." OR "Connect or create consumer failed with exception" OR "Connected successfully, creating telemetry consumer ..."))
| rex field=_raw ^(?:[^ \n]* ){7}(?P<success_status_message>\w+\s+\w+,\s+\w+\s+\w+\s+\w+)"
| timechart count as status | eval status=if(isnull(success_status_message), 0, 1)

success_status_message is always null

A:

Part of the problem is the regex string, which doesn't match the sample data. Another problem is the unneeded timechart command, which filters out the 'success_status_message' field.  Try this search:
(index="05c48b55-c9aa-4743-aa4b-c0ec618691dd" ("Retry connecting in 1000ms ..." OR "Connect or create consumer failed with exception" OR "Connected successfully, creating telemetry consumer ..."))
| rex "\s-\s(?P<success_status_message>.*)"
| eval status=if(match(success_status_message, "Connected successfully, creating telemetry consumer"), 1, 0)


Q:

Animation Snaps back when the UIImage is changed

I have an UIImageView that runs across the screen when a button is pressed and held. When the button is pressed is changes the UIImage of the UIImageView and when the button is let go I change it to its original UIImage. When ever the image changes back it snaps back to the location that the image started.
This Timer is called when the button is pressed:
//This is the image that changes when the button is pressed.
imView.image = image2;
runTimer = [NSTimer scheduledTimerWithTimeInterval:0.04
                                            target:self
                                          selector:@selector(perform)
                                          userInfo:nil
                                           repeats:YES];

This is called When the button stops being held:
- (IBAction)stopPerform:(id)sender{
   [runTimer invalidate];

   //THIS IS WHAT SNAPS THE ANIMATION BACK:
   //Without this the animation does not snap back
   imView.image = image1;
}

- (void)performRight{

 CGPoint point0 = imView.layer.position;
 CGPoint point1 = { point0.x + 4, point0.y };

 CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position.x"];
 anim.fromValue    = @(point0.x);
 anim.toValue  = @(point1.x);
 anim.duration   = 0.2f;
 anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];

 // First we update the model layer's property.
 imView.layer.position = point1;

 // Now we attach the animation.
 [imView.layer  addAnimation:anim forKey:@"position.x"];
}

Do I need to add the change in images to the animation? If so how? Im really confused.

A:

Core Animation uses different sets of properties to represent an object:
From Core Animation Programming Guide:

model layer tree (or simply “layer tree”) are the ones your app interacts with the most. The objects in this tree are the model objects that store the target values for any animations. Whenever you change the property of a layer, you use one of these objects.
presentation tree contain the in-flight values for any running animations. Whereas the layer tree objects contain the target values for an animation, the objects in the presentation tree reflect the current values as they appear onscreen. You should never modify the objects in this tree. Instead, you use these objects to read current animation values, perhaps to create a new animation starting at those values.

So when you animate the properties you change the presentation layer, but once the animation is finished the object reverts back to its model property values.
What you need to do to fix this is use the [CAAnimation animationDidStop:finished:] delegate method to set the final property value and anything else you would like to do.  I think you could use this to dump that horrible NSTimer code you are using and one small part of the world will be that much better.


Q:

Generating random data at 1 minute intervals: Highcharts

I have created a spline real time chart where I want to show points at regular intervals.
Every point is an event taking place after one minute. However I am having a hard time trying to understand all the moving pieces:

the interval function on the highchart demo I referred updated every 1 second, I have made that 6000.
the dummy updating in the javascript just takes the latest time and appends it, is there supposed to be some delay introduced there?
the dummy initialization data in series has a for loop which again I could not understand. I understand that javascript produces a UNIX timestamp and its millisecond manipulation however the default code (again slightly modified from a highchart demo) runs from -9999 to 0 and multiples by a number.

I want to understand these parts and make sure that every time my x axis 'ticks' towards the right, I have a one minute gap and only one point on the graph.
PS: Please forgive any missing brackets, they might have been missed while posting the question, but I assure you that it isnt a problem.
Here is my code for series:
           series: [{
                type: 'spline',
                name: 'Random data',
                data: (function () {
                    // generate an array of random data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -9999; i <= 0; i += 1) {
                        data.push([
                            time + i * 60000,
                            Math.round(Math.random() * 100) + 10
                        ]);
                    }
                    return data;
                }())
            }]

Here is my code for the chart:
chart: {
 events: {
           load: function () {

             // Set up the updating
             var series = this.series[0];

             setInterval(function () {
               var x = (new Date()).getTime(), // current time
               y = Math.round(Math.random() * 100) + 10

               series.addPoint([x, y], true, true);
             }, 6000);
           }
         }
       }

A:

As to your questions:

If you want to have 1 minute data interval, you need to use 60000 value (60 * 1000), 6000 milliseconds is 6 seconds.
Current date in the interval function is taking every 6000 milliseconds, which causes gaps in the data every 6000 milliseconds.
That data initialization depends on subtracting multiples of six seconds from the current timestamp:

data: (function() {
    // generate an array of random data
    var data = [],
        time = (new Date()).getTime(),
        i;

    for (i = -9999; i <= 0; i += 1) {
        if (i === -500) {
            console.log(time, i, 60000); // 1560941909847 + (-500 * 60000)
            console.log(time + i * 60000); // 1560911909847
        } else if (i === -499) {
            console.log(time, i, 60000); // 1560941909847 + (-499 * 60000)
            console.log(time + i * 60000); // 1560911969847
        } else if (i === 0) {
            console.log(time, i, 60000); // 1560941909847 + (0 * 60000)
            console.log(time + i * 60000); // 1560941909847 = actual time
        }
        data.push([
            time + i * 60000,
            Math.round(Math.random() * 100) + 10
        ]);
    }
    return data;
}())


Q:

Почему не происходит авто-обновление списка ng-repeat?

Есть такой список формируемый ng-repeat:

Когда я удаляю элемент из массива friends:
delete $scope.friends[id];

тогда мой исходный список не обновляется, т-е удаленный элемент div не скрывается сразу. Скрывается, если сделать клик по зоне ng-repeat

A:

Во первых проверьте что используете ng-click
Во вторых лутчий способ по удалению элемента с массива splice.
Найти индекс текущего элемента
var index = arr.indexOf(element)

Удалить с текущего интекса 1 елементЖ
arr.splice(index, 1)


Q:

CSS selector for an img element with class

I have

I tried to apply hover effect on image using:
img .myClass:hover {
  opacity: 1;
}

Why doesn't it work?

A:

The selector img .myClass will select an element with a class of myClass that is a descendant of an img element. But since img elements can't contain descendant elements, that doesn't make sense.
You want to select an img element with a class of myClass, therefore you need to remove the space:
img.myClass:hover {
  opacity:1;
}

div {
  border: 1px solid;
  display: inline-block;
}
img {
  opacity: 0;
  transition: 200ms ease-in;
  vertical-align: top;
}
img.myClass:hover {
  opacity: 1;
}