Q: Django IntegrityError 'Column tag_id cannot be null' I'll describe the models first and explain the issue i'm having after.
class Tag(models.Model):
    id = models.CharField(_(u'id'), max_length=128, primary_key=True)

class Post(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, null=True)

When I execute this code I get the error in the subject:
post_obj = Post.objects.get(id='someid')
tag_obj = Tag.objects.get(id='')
post_obj.tags.add(tag_obj)

Notice how the tag id is an empty string.
I've looked into what sql is being executed and it looks something like this:
INSERT INTO `post_tags` (`post_id`, `tag_id`) VALUES ('someid', NULL)

The empty string tag_id is being converted into a NULL value.
Mysql show columns output from post_tag (manytomany table):
+---------------------+--------------+------+-----+---------+----------------+
| Field               | Type         | Null | Key | Default | Extra          |
+---------------------+--------------+------+-----+---------+----------------+
| id                  | int(11)      | NO   | PRI | NULL    | auto_increment |
| post_id             | varchar(128) | NO   | MUL | NULL    |                |
| tag_id              | varchar(128) | NO   | MUL | NULL    |                |
+---------------------+--------------+------+-----+---------+----------------+

So django is converting my empty string to NULL when adding the tag. How can I stop django from doing this?


Q: Refactoring method for getting Json from a stored procedure in ASP.NET Core Please, please don't close or mark this question as duplicate, I have already looked StackOverflow and online but couldn't find solution.
Below code works great that I receive data from SQL Server via a stored procedure, then assign to a list of book model and return Json:
public IActionResult GetAllBooks()
{
    List<BookViewModel> book = new List<BookViewModel>();

    DataTable dataTable = new DataTable();

    using (SqlConnection sqlConnection = new SqlConnection(_configuration.GetConnectionString("xxx")))
    {
        sqlConnection.Open();

        SqlDataAdapter sqlData = new SqlDataAdapter("proc_GetBookList", sqlConnection);
        sqlData.SelectCommand.CommandType = CommandType.StoredProcedure;

        sqlData.Fill(dataTable);

        foreach (DataRow dr in dataTable.Rows)
        {
            book.Add(new BookViewModel
            {
                Name = dr["Name"].ToString(),
                Stock = Convert.ToInt32(dr["Stock"]),
             });
         }
     }

     return Json(book);
}

But I am trying to find a better way or best practice e.g serialize or any other techniques so that I don't need to create (View model and Assigning them values) like below. This is small example of only two properties but sometimes I need to map like 20 or more properties, do you guy see any problem in above code? I am new in software development world, any suggestion would be appreciated.
new BookViewModel
{
    Name = dr["Name"].ToString(),
    Stock = Convert.ToInt32(dr["Stock"]),
};

A: I have used Newtonsoft JSON (NuGet package) for this purpose.
Example:
using Newtonsoft.JSON;

public string DataTableToJSONWithJSONNet(DataTable table) {
   string JSONString = string.Empty;
   JSONString = JSONConvert.SerializeObject(table);
   return JSONString;
}

You can find this Newtonsoft example and a few other methods here.

A: Using a query like you are using is pretty much going to make you use this style of assignment. Switching to Entity Framework to query your DB is going be your best bet, since it will do assignment to objects/classes automatically. But I get that doing so after a project is started can be a PITA or nearly impossible (or a very significantly large amount of work) to do. There's also a bit of a learning curve, if you've never used it before.
What you can do to make things easier is to create a constructor for your model that takes in a DataRow and assigns the data on a single place.
public BookViewModel(DataRow dr)
{
    Name = dr["Name"].ToString();
    Stock = Convert.ToInt32(dr["Stock"]);
}

Then you just call "book.Add(new BookViewModel(dr));" in your foreach loop. This works well if you have to do this in multiple places in your code, so you don't have to repeat the assignments when you import rows.
You might also be able to use Reflection to automatically assign the values for you. This also has a bit of a learning curve, but it can make conversions much simpler, when you have it set up.
Something similar to Reflection is AutoMapper, but that's not as popular as it used to be.
I was going to suggest using a JSON package like Newtonsoft or the built in package for C#, but it looks I got beat to that punchline.
Another option is using Dapper. It's sort of a half-step between your current system and Entity. It can use SQL or it's own query language to cast the results directly to a model. This might be the easiest and most straight forward way to refactor your code.
Dapper and Entity are examples of object relational mappers (ORMs). There are others around you can check out.
I've only listed methods I've actually used and there are many other ways to get the same thing done, even without an ORM. They all have their pros and cons, so do your research to figure out what you're willing to commit to.

A: Simply just replace your "return Json(book)" with
return Ok(book)


Q: Xubuntu tiling: how to maximize terminal window for partial tiling? I have problem when do tiling terminal in Xubuntu 14.10. Those terminal emulators (I've test with xfce4-terminal, xterm, and gnome-terminal) can be resized only by width/height of font they are using, thus it can not resized by 1px, see Fig 1.

Fig 1: When I hold mouse cursor at bottom-right corner of terminal window (cursor not included in the figure), they show current size of the window. If I moves cursor to the right, terminal window will expand its width by size of 1 character at a time.
Now when I do full screen tiling (maximizing window), the terminal window will stretch its body to cover all screen, see Fig 2.

Fig 2: Maximize terminal window, you can see a line [ NORMAL > ... < 100% < 1:1 ] ends with blank space that its width is shorter than font's width.
But when I do partial tiling (for example, left-tiling by moving the window to left edge so it expand to eats up half-left of the entire screen), the terminal window will not trying to stretch like when I do maximizing, see Fig 3.

Fig 3: Left-tiling terminal window that leaves space from right-tiling web browser and bottom edge.
Here's the problem, if I do partial tiling and then open a new terminal tab (ctrl+shift+t), terminal window will expand it's size vertically, which will kick some lines out of screen (Fig 4). That's very annoying.

Fig 4: Last line (:q!) of left-tiling terminal is kicked out of the screen after a new tab is opened.
This problem is not occur with maximize window (like in Fig 2).
This problem is also not occur in Unity/Ubuntu 14.10.
So I wonder if a window (not only terminal) can be partially maximize? Or there are other workarounds out there? (or this is just a bug and should be reported to issue tracker?)

A: I have the same problem using Xubuntu with the default terminal emulator and window manager and have nearly gone insane trying to fix it. I have a partial answer and, unfortunately, no real fix for you.
As you mentioned, the window size in a terminal emulator (at least in xterm and xfce4-terminal, the ones that I tested) is handled in terms of font size rather than pixels, which one might expect. This is acceptable behavior according to the X window system manpage: "The WIDTH and HEIGHT parts of the geometry specification are  usually measured in either pixels or characters, depending on the application."
This is why there are gaps around the terminal window when doing partial tiling: the window manager maximizes the window within that half of the display while using whole multiples of the font size for the dimensions. There may be a way to add offsets or fix this with in-depth xfwm or X configuration tweaks that are beyond me (I'm still pretty new to Linux).
The reason that the window takes up the full screen area when maximized seems to have to do with a setting that (I think) is on by default in a new Xubuntu install. If you open the Xfce4 settings manager, go to Window Manager Tweaks, and click the Accessibility tab, there is an option to "Hide frame of windows when maximized." When this option is checked, there are no gaps around the maximized terminal window; when it is unchecked, there are.
Unfortunately, this option only applies to maximized windows and not windows that are "maximized" to half of the screen by partial tiling. Disabling it will at least make the gaps around the windows consistent in both cases.
As far as your issues with the tab bar pushing lines off of the screen, tiling the window again after opening a new tab will bring the bottom of the window back into view. You could also set the terminal to always show the tab bar. This option is not available through the graphical preferences menu; you will have to edit ~/.config/xfce4/terminal/terminalrc and change the MiscAlwaysShowTabs option to TRUE. This way the size of the window won't change when opening a new tab.
Sorry I couldn't be of more help.

A: You can remove WM_NORMAL_HINTS from any terminal window with xprop.
Put these lines in the ~/.bashrc file:
if [ "$DISPLAY" ]; then
 activ_win_id=`xprop -root _NET_ACTIVE_WINDOW`
 activ_win_id=$(echo $activ_win_id | awk '{ activ_win_id=substr($0,41,9); print activ_win_id; }' )
 xprop -id $activ_win_id -remove WM_NORMAL_HINTS
fi

The hints will be removed from the current terminal window automatically.


Q: checking the Solution of Bessel differential equation I want to check the first part of the solution and help in the second part.

Obtain the solution
  $$y_{1}(x)=J_{0}(x)=1-\frac{x^{2}}{2^{2}}+\frac{x^{4}}{2^{2}\cdot 4^{2}}-\ldots+\frac{(-1)^{n} x^{2 n}}{2^{2 n}(n !)^{2}}+\ldots$$
  of the differential equation $$x \frac{d^{2} y}{d x^{2}}+\frac{d y}{d x}+x y=0$$
  Show that $$y_{2}(x)=u(x) J_{0}(x)$$ is a second solution if $$u(x)=\int \frac{d x}{x J_{0}^{2}}$$

Solution :
Firstly
Let $y(x)=\sum_{\lambda=0}^{\infty} a_{\lambda} x^{k+\lambda}$.
We differentiate and substitute. The result is
$$\sum_{\lambda=0}^{\infty} a_{\lambda}(k+\lambda)(k+\lambda-1) x^{k+\lambda-1}+\sum_{\lambda=0}^{\infty} a_{\lambda}(k+\lambda) x^{k+\lambda-1}+\sum_{\lambda=0}^{\infty} a_{\lambda} x^{k+\lambda+1}=0$$
By setting $\lambda=0,$ we get the coefficient of $x^{k-1},$ the lowest power of $x$ appearing on the
left-hand side,
$$\quad a_{0}\left[k(k-1)+k\right]=0$$
and $a_{0} \neq 0$ by definition. Equation therefore yields the indicial equation
with solutions $k=0$
It is of some interest to examine the coefficient of $x$ also. Here we obtain
$a_{1}=0$.
Proceeding to the coefficient of $x^{J-1}$ for $k=0,$ we set $\lambda=j$ in the first, and second terms and $\lambda=j-2$ in the third term. By requiring the resultant
coefficient of $x$ to vanish, we obtain
$$a_{j}\left[j(j-1)+j\right]+a_{j-2}=0$$
When $j$ is replaced by $j+2,$ this can be rewritten for $j \geq 0$ as
$a_{j+2}=-a_{j} \frac{1}{(j+2)(j+2)}$
which is the desired recurrence relation.
Repeated application of this recurrence relation
leads to
$$a_{2}=-a_{0} \frac{1}{2(2)}=-\frac{a_{0} }{2^{2}}$$
$$a_{4}=-a_{2} \frac{1}{4(4)}=\frac{a_{0} }{2^{4} (2!)^{2}}$$
$$a_{6}=-a_{4} \frac{1}{6(6)}=-\frac{a_{0} }{2^{6} (3!)^{2}}, \quad$$ and so on
and in general,
$$a_{2 p}=(-1)^{p} \frac{a_{0}}{2^{2 p} (p!)^{2}}$$
Inserting these coefficients in our assumed series solution and take $a_0=1$, we have
$$y_1(x)=J_0(x)= \left[1-\frac{ x^{2}}{2^{2} (1!)^{2}}+\frac{ x^{4}}{2^{4} (2 !)^{2}}-\cdots\right]$$
In summation form
$$y_1(x)=J_0(x)=\sum_{j=0}^{\infty}(-1)^{j} \frac{ x^{2 j}}{2^{2j} (j!)^{2} }= \sum_{j=0}^{\infty}(-1)^{j} \frac{1}{(j !)^{2}}\left(\frac{x}{2}\right)^{2 j}$$
Secondly
If $$y_{2}(x)=u(x) J_{0}(x)$$ where $$u(x)=\int \frac{d x}{x J_{0}^{2}}$$ then $$y'_{2}(x)=u(x) J'_{0}(x)+u'(x) J_{0}(x)$$ and $$y''_{2}(x)=u'(x) J'_{0}(x)+u(x) J''_{0}(x)+u''(x) J_{0}(x)+u'(x) J'_{0}(x)$$ We get
$$x(u'(x) J'_{0}(x)+u(x) J''_{0}(x)+u''(x) J_{0}(x)+u'(x) J'_{0}(x))+u(x) J'_{0}(x)+u'(x) J_{0}(x)+x(u(x) J_{0}(x))$$
$$xu'(x) J'_{0}(x)+xu(x) J''_{0}(x)+xu''(x) J_{0}(x)+xu'(x) J'_{0}(x)+u(x) J'_{0}(x)+u'(x) J_{0}(x)+xu(x) J_{0}(x)$$
$$2xu'(x) J'_{0}(x)+xu(x) J''_{0}(x)+xu''(x) J_{0}(x)+u(x) J'_{0}(x)+u'(x) J_{0}(x)+xu(x) J_{0}(x)$$
$$u(x)(x J''_{0}(x)+ J'_{0}(x)+x J_{0}(x))+xu''(x) J_{0}(x)+u'(x) J_{0}(x)+2xu'(x) J'_{0}(x)$$
I can not continue..

A: Your series solution looks good.
As for finding the second solution... it would help a great deal if we actually used the definition of $u$.
\begin{align*}y_2(x) &= u(x)J_0(x)\\
y_2'(x) &= u(x)J_0'(x) + u'(x)J_0(x) = u(x)J_0'(x) + \frac{1}{xJ_0(x)}\\
y_2''(x) &= u(x)J_0''(x) + u'(x)J_0'(x) - \frac{J_0(x)+xJ_0'(x)}{x^2J_0^2(x)}\\
&= u(x)J_0''(x) + \frac{J_0'(x)}{xJ_0^2(x)} -\frac{1}{x^2J_0(x)}-\frac{J_0'(x)}{xJ_0^2(x)}\\
y_2''(x) &= u(x)J_0''(x) - \frac{1}{x^2J_0(x)}\end{align*}
We have of course used the Fundamental Theorem to differentiate $u$. And now, we put those calculated derivatives into the differential equation:
\begin{align*}xy_2(x) + y_2'(x) + xy_2(x) &= xu(x)J_0(x) + u(x)J_0'(x) + \frac{1}{xJ_0(x)} + xu(x)J_0''(x) - \frac{1}{xJ_0(x)}\\
&= u(x)\left(xJ_0(x)+J_0'(x)+xJ_0''(x)\right) = u(x)\cdot 0 = 0\end{align*}
We use that $J_0$ is a solution of the differential equation, and there it is.


Q: Is there any way to connect my google calendar to google colab? I created a project using the Google Cloud Console and created an OAuth screen. But when I used Python in colab to access the calendar, I got an error message that I don't have a proper redirect uri. Is there any way to bypass accessing my Google Calendar with my login credentials rather than using an access token


Q: Delete multiple datas sharing a same child from Firebase - Java I have the following Firebase database
lessons :
      Id_lesson : "XXX1"
      Name_lesson : "Geography"
      Date_lesson : "25/09/2018"

      Id_lesson : "XXX2"
      Name_lesson : "Mathematics"
      Date_lesson : "25/09/2018"

      Id_lesson : "XXX1"
      Name_lesson : "Physics"
      Date_lesson : "26/09/2018"

      Id_lesson : "XXX2"
      Name_lesson : "Biology"
      Date_lesson : "26/09/2018"

I need to delete all the lessons entries from a specific date (sharing the same Date_lesson child).
I tried this method :
private void Delete_CR_Lessons(Date date) {

    final String date_to_delete_string = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
    Log.i("Tag", "date to delete : "+date_to_delete_string);

    DatabaseReference drTest = FirebaseDatabase.getInstance().getReference();

    drTest.child("lessons").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            for(DataSnapshot dataSnapshot:snapshot.getChildren()) {
                Log.i("Tag", "iteration for dataSnap");
                if(dataSnapshot.hasChild(date_to_delete_string)){
                    dataSnapshot.getRef().setValue(null);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w("TAG: ", databaseError.getMessage());
        }
    });

During execution of the method (with String date "25/09/2018" for example), the entries are not deleted from Firebase Database. I see the two logs I specified  but I also see a log called
"I/chatty: uid=10298(com.example.myname.lessonsmanagment) identical 2 lines"
I suppose that the method doesn't work because it cannot detect both Lessons from date 25/09/2018 (Geography and Mathematics) on the same time.
Does anyone have an idea on how to make it work ?

A: first of all, you need to query/order the data with the date
you can simply do it using this sample.
mRef.child("lessons").orderByKey().equalTo(Date_lesson)
.addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {

  for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
    String key = postsnapshot.getKey();
    dataSnapshot.getRef().removeValue();
 }
});

where mRefis you lessons branch ref


Q: Destructuring object passed like argument to a function Don't know if is possible with ES6.
I'm working in a project that have a function which is passed an Object with lots of properties. Right now the code is as follows:
function foo({arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8}){
   this.model = arg1;
   this.model = arg2;
   // and so on...
};
obj = {
    arg1: 'some',
    arg2: 'whatever',
    arg3: 'text'
    // and so on up to 8
    arg8: 'end text'
    }
foo(obj);

Mi DESIRED output would be,if possible, accessing the parameters like this:
function foo( {...args} ){ // not working
   this.model = arg1;
   this.model = arg2;
   // and so on...
};

obj = {
    arg1: 'some',
    arg2: 'whatever',
    arg3: 'text'
    // and so on up to 8
    arg8: 'end text'
    }
foo(obj);

So question is: is there any way for the function to get parameter object in a single var (args) AND have them destructured to be ready to use?

A: there are couple of ways to do it.
the first one would be to store all argumens in a variable then do destruct it

function foo(...args){
  const  { arg1, arg2 } = args
   this.model = arg1;
   this.model = arg2;
   // and so on...
};

Or

function foo({ arg1, arg2 }){
   this.model = arg1;
   this.model = arg2;
   // and so on...
};


Q: Backbone.js View removing and unbinding when my page opens, I call the collection and populate the view:
var pagColl = new pgCollection(e.models);
var pagView = new pgView({collection: pagColl});

Separately (via a Datepicker), I wish to want to populate the same collection with different models and instantiate the view again.
The problem I have is how to close the original pagView and empty the pagColl before I open the new one, as this "ghost view" is creating problems for me.  The variables referred to above are local variables? is it that I need to create a global  pagColl and reset() this?

A: well there has been many discussion on this topic actually,
backbone does nothing for you, you will have to do it yourself and this is what you have to take care of:

*

*removing the view (this delegates to jQuery, and jquery removes it from the DOM)
// to be called from inside your view... otherwise its  `view.remove();`
this.remove();

this removes the view from the DOM and removes all DOM events bound to it.

*removing all backbone events
// to be called from inside the view... otherwise it's  `view.unbind();`
this.unbind();

this removes all events bound to the view, if you have a certain event in your view (a button) which delegates to a function that calls this.trigger('myCustomEvent', params);
if you want some idea's on how to implement a system I suggest you read up on Derrick Bailey's blogpost on zombie views: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/.
another option
another option would be to reuse your current view, and have it re-render or append certain items in the view, bound to the collection's reset event

A: I was facing the same issue. I call the view.undelegateEvents() method.
Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

A: I use the stopListening method to solve the problem, usually I don't want to remove the entire view from the DOM.
view.stopListening();

Tell an object to stop listening to events. Either call stopListening
  with no arguments to have the object remove all of its registered
  callbacks ... or be more precise by telling it to remove just the
  events it's listening to on a specific object, or a specific event, or
  just a specific callback.

http://backbonejs.org/#Events-stopListening

A: Here's one alternative I would suggest to use, by using Pub/Sub pattern.
You can set up the events bound to the View, and choose a condition for such events.
For example, PubSub.subscribe("EVENT NAME", EVENT ACTIONS, CONDITION); in the condition function, you can check if the view is still in the DOM.
i.e.
var unsubscribe = function() {
    return (this.$el.closest("body").length === 0);
};
PubSub.subscribe("addSomething",_.bind(this.addSomething, this), unsubscribe);

Then, you can invoke pub/sub via PubSub.pub("addSomething"); in other places and not to worry about duplicating actions.
Of course, there are trade-offs, but this way not seems to be that difficult.


Q: BETWEEN query using JDBC with MySQL public int getdata(String startDate, String endDate) {
    PreparedStatement ps;
    int id = 0;
    try {
        /*
         * SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
         * java.util.Date startDat = formatter.parse(startDate);
         * java.util.Date endDat = formatter.parse(endDate);
         */
        // ps = connection.prepareStatement("select * from project.order Where PO_Date Between " + startDate + "' AND '" + endDate + "'");
        //ps = connection.prepareStatement("select * from project.order where PO_Date between ? AND DATE_ADD( ?, INTERVAL 1 DAY) ");
        //ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date between ? AND ?");
        ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date >= ? AND PO_Date <= ?");
        //ps = connection.prepareStatement("SELECT * FROM project.order WHERE PO_Date(now())>= ? AND PO_Date(now())<=?");
        /*
         * ps.setDate(1, new java.sql.Date(startDate)); ps.setDate(2, new
         * java.sql.Date(endDate.getTime()));
         */
        ps.setString(1, startDate);
        ps.setString(2, endDate);

        ResultSet rs = ps.executeQuery();
        // System.out.println("value of rs "+rs);

        while (rs.next()) {
            ArrayList<String> arrlist = new ArrayList<String>();
            System.out.println(rs.getString(2));
            System.out.println(rs.getInt(1));
            System.out.println(rs.getString(4));
            System.out.println(rs.getString(5));
            System.out.println(rs.getString(6));
            System.out.println("***************");
            // System.out.print(rs.getDate("endDate"));
            Iterator<String> itr = arrlist.iterator();
            while (itr.hasNext()) {
                System.out.println(itr.next());
            }
        }
        rs.close();

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return id;
}
}

I tried to solve but I am getting out except last date means endDate which we give as a input.
I tried around 5 different queries but still I am getting the same.

A: In MySQL, the DATE type maps to the Java class java.sql.Timestamp.  So you should be working with this type to build your query, and not java.util.Date.  Here is code which generates the two timestamps you will need:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date startDate = formatter.parse(startDate);
java.util.Date endDate   = formatter.parse(endDate);

java.sql.Timestamp start = new Timestamp(startDate.getTime());
java.sql.Timestamp end   = new Timestamp(endDate.getTime());

Then use your first BETWEEN query to get your result:
PreparedStatement ps = con.prepareStatement("SELECT * FROM project.order
                                             WHERE PO_Date BETWEEN ? AND ?");
ps.setTimestamp(1, start);
ps.setTimestamp(2, end)

Note here that I am using a parametrized PreparedStatement, which avoids (or at least greatly lessens) the possibility of SQL injection.

A: Try this
SELECT * FROM project.order po
   WHERE po.PO_Date IS NOT NULL
     AND TO_DATE(PO_Date, 'DD/MM/RRRR') >=
         TO_DATE('17/02/2015', 'DD/MM/RRRR')
     AND TO_DATE(PO_Date, 'DD/MM/RRRR') <=
         TO_DATE('20/06/2015', 'DD/MM/RRRR');


Q: how to select many different data"s" from two table? I have two tables tableA, tableB
Two of them have col "ip",like this...

tableA-ip
1.1.1.1
1.1.1.2
1.1.1.3
1.1.1.4
1.1.1.5
1.1.1.6
1.1.1.7
1.1.1.8

tableB-ip
1.1.1.3
1.1.1.4
1.1.1.5
And what I want is
1.1.1.1
1.1.1.2
1.1.1.6
1.1.1.7
1.1.1.8
How to select it?

A: It looks like you want the set difference (that is, IPs in A that are not also in B), soooooo:
SELECT a.ip FROM tableA a WHERE tableA.ip NOT IN (SELECT b.ip FROM tableB)

A: Use NOT IN:
SELECT ip FROM TableA WHERE TableA.ip NOT IN (SELECT ip FROM TableB)

A: You can combine two result sets with UNION.
select ip from tableA
union
select ip from tableB;

http://dev.mysql.com/doc/refman/5.0/en/union.html
The default behavior is to remove duplicate rows.
If you want duplicate rows use UNION ALL.

A: select a.id from a minus select b.id from b

or
select a.id from a where a.id not in (select b.id from b)

A: SELECT col1, col2, .. , Ip from TableA
UNION
SELECT col, col2, ...., Ip from TableB

To get the differences you can use the MINUS Operator instead of UNION


Q: How would I go about connecting to a database securely via Java? I wish to connect to a Mysql Database with Java without revealing the password to anyone that may decompile my code? I can efficiently connect to a database, but my ways will openly show my password in the code :( and wish only a response on how to hide the password. Thanks is advance, Josh Aurora

A: OAuth allows client connection without  storing credentials on client ( used widely on mobile devices  or to identify tweitte applications ).  It also allows to remove access permissions from rogue clients.   But I doubt that mysql suzpports this directly,. so you will have to wrap your database  with some kind of service layer.  One  of usable imaplementations of OAuth:
http://code.google.com/p/oauth-signpost/
(IIRC, used by Qipe )

A: Assuming that the database which will be accessed will be on your machines, two things that come to mind:

*

*Set up a small secure REST service (as shown here) which will, upon a certain request with certain credentials, pass the password to your database. This however might be an issue if your application is sitting behind some corporate firewall since you might need to add firewall exceptions, which is something that not all administrators are enthusiastic about.

*You could use a mix of Cryptography and Obfuscation to encrypt the password to the database and then obfuscate all your code.
As a note though, either of these methods can, in time be broken. This is basically the rule about all security related software.
If it where up to me, I would go about this problem using the first approach and make sure that the credentials through which the service is accessed are changed often.
However, databases which are used as part of a client solution contain pretty sensitive data which is in the client's interest not to tamper with, so the client will most likely not mess around with it, he/she will be happy as long as the system works.
If on the other hand, the database is not deployed onto one of your machines then you can't really do much about it. You could recommend that the server will be stored on a remote machine with access only over the intranet, but other than that, I do not think you can do much about it.


Q: python3 KTinker grid load time incredibly long I'm trying to write a fairly basic grid which I've noticed generates fairly quickly but takes minutes to actually display anything. It runs through the loop but the window is plain until everything appears at once a few minutes later
i = 0
for i,element in enumerate(headerArray):
    label = tk.Label(text=element).grid(row=0,column=i)

for itter in outputArray:
    line=re.split(r'\s{2,}',itter)

    if not (nextLineColor is None):
        nextLineColor = None

    if(len(line) == 1):
        continue
    elif(len(line) == 6):
        for j,col in enumerate(line):
            ele = None
            if(j==0):
                ele = tk.Button(self,text=col)
                ele.config(command=lambda val=col: self.node_selected(val))
            else:
                ele = tk.Label(text=col)
            ele.grid(row=i,column=j)
        i = i + 1


Q: cannot find symbol Serializable? Why does this:
package com.example;

import com.example.Foo.Bar.Baz;

import java.io.Serializable; // I did import Serializable...

public class Foo implements Serializable {

    public final Bar bar;

    public Foo(Bar bar) {
        this.bar = bar == null ? new Bar(Baz.ONE) : bar;
    }

    public static class Bar implements Serializable { // this is line 15, where the compiler error is pointing

        public enum Baz {
            ONE
        }

        public final Baz baz;

        public Bar(Baz baz) {
            this.baz = baz;
        }
    }

}

Give me this:
[ERROR] <path to file>/Foo.java:[15,44] cannot find symbol
[ERROR] symbol:   class Serializable
[ERROR] location: class com.example.Foo

If I replace the Serializable interface to something else like :
public interface MyMarkerInterface {}

then the code compiles. (even Cloneable works!)
What makes this happen?
intelliJ didn't spot anything wrong through static analysis.

A: Don't try and import the internal class. That's causing your compiler error
// import com.example.Foo.Bar.Baz;
import java.io.Serializable;

public class Foo implements Serializable {
    public final Bar bar;

    public Foo(Bar bar) {
        this.bar = bar == null ? new Bar(Bar.Baz.ONE) : bar;
    }

    public static class Bar implements Serializable {
        public enum Baz {
            ONE
        }
        public final Baz baz;
        public Bar(Baz baz) {
            this.baz = baz;
        }
    }
}

A: in java7 and java8 compiling depended on order of imports.
your code works in java >= 9. see https://bugs.openjdk.java.net/browse/JDK-8066856 and https://bugs.openjdk.java.net/browse/JDK-7101822
to make it compile in java7 and java8 just reorder the imports


Q: Setting border for checkable QListWidgetItem I have added some check-able QListWidgetItem and I have challenge setting the border color for the checkboxes. setForeground function only sets the color of the checkbox text.
Any suggestion please.
This is my sample code creating the check-able QListWidgetItems:
    watch_list = ["Protesters", "Local news staff", "Techfluencers"]
    for category in watch_list:
        self.checkBox = QtWidgets.QListWidgetItem(category)
        self.checkBox.setFlags(self.checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
        self.checkBox.setCheckState(QtCore.Qt.Unchecked)
        self.checkBox.setForeground(QtGui.QColor('#FFFFFF'))
        self.watchListslistWidget.addItem(self.checkBox)

I have tried
     self.watchListslistWidget.setStyleSheet("""
                                            QListWidget::item {
                                                 border:1px #FFFFFF
                                            }
                                        """)

But it sets the all background of the QListWidget to white.

A: You can use a delegate:
from PyQt5 import QtCore, QtGui, QtWidgets

class CheckBoxDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        option.palette.setBrush(QtGui.QPalette.Button, QtGui.QColor("red"))

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.watchListslistWidget = QtWidgets.QListWidget()
        self.setCentralWidget(self.watchListslistWidget)

        watch_list = ["Protesters", "Local news staff", "Techfluencers"]
        for category in watch_list:
            checkBox = QtWidgets.QListWidgetItem(category)
            checkBox.setFlags(checkBox.flags() | QtCore.Qt.ItemIsUserCheckable)
            checkBox.setCheckState(QtCore.Qt.Unchecked)
            self.watchListslistWidget.addItem(checkBox)

        delegate = CheckBoxDelegate(self.watchListslistWidget)
        self.watchListslistWidget.setItemDelegate(delegate)

def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MainWindow()
    w.show()

    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

A: I got it working by using indicator as follows:
self.watchListslistWidget.setStyleSheet("""
                                       QListWidget::indicator{
                                            border: 1px solid white;
                                       }
                                       """)


Q: display json data that contains html I have the following json
[{
  "date": "2011",
  "content": "
Hello world?
"
},
{
  "date": "2012",
  "content": "
Hello again
"
}]

my controller has
public function index() {
  $data['json'] = json_decode(file_get_contents('location_of_json_file.json'));
  return view('index', $data);
}

my view has
@foreach ($json as $a)
  {{ $a->content }}
@endforeach

but what i get is
<p>Hello world?</p>

<p><strong>Hello again</strong></p>

how can i make it parse the html code instead of displaying the syntax? i've tried htmlentities and html_entity_decode. i tried to json_encode in different place of the code, i'm lost. please help.

A: The Blade output tags changed between Laravel 4 and Laravel 5.  You're looking for:
{!! $a->content !!}

In Laravel 4, {{ $data }} would echo data as is, whereas {{{ $data }}} would echo data after running it through htmlentities.
However, Laravel 5 has changed it so that {{ $data }} will echo data after running it through htmlentities, and the new syntax {!! $data !!} will echo data as is.
Documentation here.

A: In Laravel 5, by default {{ ... }} will escape the output using htmlentities. To output raw HTML that get's interpreted use {!! ... !!}:
@foreach ($json as $a)
    {!! $a->content !!}
@endforeach

Here's a comparison between the different echo brackets and how to change them


Q: WPF: Making child elements' MinWidth/MinHeight constrain the Window I have a WPF Window that contains a UserControl with a MinWidth and MinHeight. How can I prevent the user from resizing the Window down to a point where that UserControl's minimum size is violated?
Here's a simplified version of a Window I'm working on. My real app's UserControl is replaced here by a Border:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
      <Button Content="OK"/>
      <Button Content="Cancel"/>
    </StackPanel>
    <Border BorderBrush="Green" BorderThickness="10"
            MinWidth="200" MinHeight="150"/>
  </DockPanel>
</Window>

If I shrink the window small enough, the Border's right and bottom edges are cut off. I want to prevent the window from getting that small -- I want my window's minimum size to be exactly the point at which the Border is at its minimum size. Some frameworks (like the Delphi VCL) automatically aggregate child controls' minimum sizes up to the window; I expected WPF to do the same, but clearly it does not.
I could always explicitly set the Window's MinWidth and MinHeight, but to calculate those correctly, I would have to factor in the Buttons' ActualHeight, which would mean waiting for at least one layout pass (or calling Measure manually). Messy.
Is there any better way to keep the Window from resizing too small for its content?

A: The simplest way I've found is to tell the Window to size to its content:
<Window ... SizeToContent="WidthAndHeight" ...>

and then, once it's done sizing (which will take the child elements' MinWidth and MinHeight into account), run some code that sets MinWidth and MinHeight to the window's ActualWidth and ActualHeight. It's also a good idea to turn SizeToContent back off at this point, lest the window resize when its content changes.
The next question is, where to put this code? I finally settled on OnSourceInitialized:
protected override void OnSourceInitialized(EventArgs e)
{
    base.OnSourceInitialized(e);
    MinWidth = ActualWidth;
    MinHeight = ActualHeight;
    ClearValue(SizeToContentProperty);
}

I also tried the Loaded event, but in my case, that was too soon -- Loaded happens before databindings have been evaluated, and I had databindings that affected my layout (a Label with a binding for its Content -- its size changed after the binding took effect). Moving the code into OnSourceInitialized, which fires after databinding, corrected the problem.
(There were also other events that fired after binding, but before the window was shown -- SizeChanged and LayoutUpdated -- but they both fire multiple times as the window is shown, and again later if the user resizes the window; OnSourceInitialized only fires once, which I consider ideal.)

A: Have you tried using an ElementName style binding from the Window to the UserControl at hand? It seems like it would be feasible to bind the Window's MinWidth/Height to those of the Button. Still not pretty, but it shouldn't require extra passes once the binding is in place and will adapt if you change the values on the Button.


Q: What's the converse proposition of $\forall x(P(x)\implies Q(x))$? As we all know, the converse proposition of $P\rightarrow Q$ is $Q\rightarrow P$. But when it comes to predicate logic, things may become different. Consider this:
$$(\forall x) (P(x)\rightarrow Q(x)).\tag{1}$$
Should its converse be $(\forall x) (Q(x)\rightarrow P(x))$?
I don't think so. In my opinion, we shouldn't neglect the quantifier $\forall$, which constrains $(Q(x)\rightarrow P(x))$.
Consider another proposition: $$(\exists x) (P(x)\rightarrow Q(x))\tag{2}.$$
When we deduce its converse, we can rewrite it as
$$(\forall x) P(x)\rightarrow (\exists x)Q(x) \tag{3}.$$ At this moment, we can readily obtain its converse: $(\exists x)Q(x)\rightarrow (\forall x) P(x)$.
Let's return to proposition (1) now. Unfortunately, I cannot rewrite it in the form of proposition (3). So I can't get its converse.
Did I make a mistake in the deduction above? And what's the converse of proposition (1)? Thanks a lot!

A: [[A]] Concept of "Converse" is well Defined for things like "$P \rightarrow Q$" & "All $P$ are $Q$" , while that is not well Defined (or Does not even Exist) for Cases like $\forall X (\cdots)$ & $\exists X (\cdots)$ , hence in Such Cases , we try to convert to "$U \rightarrow V$" form , where we may (or may not) have to lose some Exactness/rigour.
[[B]] Your Example (2) $\iff$ (3) is a Case where we have the Exact Converse , we do not lose rigour.
[[C]] The "Exact Converse" of (1) seems like it Does not Exist , hence we have to lose some Exactness/rigour to try that.
$(\forall x) (P(x)\rightarrow Q(x))\tag{1}$
$\iff$
$\lnot \lnot (\forall x) (P(x)\rightarrow Q(x))$
$\iff$
$\lnot (\exists x) \lnot (P(x)\rightarrow Q(x))$
$\iff$
$\lnot (\exists x) \lnot (\lnot P(x) \lor Q(x))$
$\iff$
$\lnot (\exists x) P(x) \land \lnot Q(x)$
Till here , it is BiDirectional , here we are forced to use UniDirectional :
$\lnot (\exists x) P(x) \land \lnot Q(x)$
$\rightarrow$
$\lnot (\exists x) P(x) \land (\exists x) \lnot Q(x)$
$\iff$
$(\lnot (\exists x) P(x)) \lor (\lnot (\exists x) \lnot Q(x))$
$\iff$
$((\forall x) \lnot P(x)) \lor (\lnot (\exists x) \lnot Q(x))$
$\iff$
$(\exists x) \lnot Q(x) \implies (\forall x) \lnot P(x)\tag{4}$
While (1) $\rightarrow$ (4) , it is not (1) $\iff$ (4) , hence we are losing Exactness/rigour here. It is in the "$U \implies V$" form.
Hence the "Weak Converse" may be :
$(\forall x) \lnot P(x) \implies (\exists x) \lnot Q(x)\tag{7}$
$ \lnot (\exists x) P(x) \implies \lnot (\forall x) Q(x)\tag{8}$
[[D]] I think , this is the best we can get , online Articles [[ Eg https://nokyotsu.com/qscripts/2014/07/distribution-of-quantifiers-over-logic-connectives.html ]] all show that (1) has no Exact/rigorous Converse.


Q: Choose specific item from sharepoint list as default value? In SharePoint I have a list full of people from AD with a Name (presence). I have another drop down menu with different items, so based on this drop down menu I want to be able to specify who should be emailed.
So once an item is chosen from the drop down menu, a person is chosen from the list to be set as a default value for another control so I can specify to send an email to that person.
How can I change the default value of a control to be a specific item in a list, not just the first item?
I would prefer to not use any hard coding options, if I can avoid it.

A: You could use an InfoPath form for entry instead.  InfoPath lets you set rules and such so that when you fill in one value, it populates another based on a formula or value.

A: Go throw this link
http://geekswithblogs.net/SoYouKnow/archive/2008/12/24/creating-a-sharepoint-list-parent--child-relationship---out.aspx
http://koobarspoint.blogspot.in/2010/06/cascading-drop-downs-with-infopath-2010.html


Q: Form that has a date picker input. And I’m sending my data to the database using nodejs My problem is: when I set the data type of my date picker to just “date” my data makes it to the database(even though it’s not the current date), BUT when I set the data type of my date picker to “datetime-local” it doesn’t make it, instead it’s just giving me an error.

*

*Date picker image
    <form action="/formdata" method="POST"class="row g-12 needs-validation" novalidate>

                     End Shift

 <input name="datepicker" id="datepicker"
                        class="form-
                       control" type="datetime-local" required>

*This is how I'm adding the data to the database (SQL Server)

    class forms {
        constructor(datepicker,site,line,units){

            this.d = datepicker;
            this.s = site;
            this.l = line;
            this.u = units;
        }

    }

    app.use(bodyParser.urlencoded({ extended: true}));
    app.use(bodyParser.json());

    //make directory static
    app.use(express.static(__dirname + '/public'));

    //we getting the home.html page
    app.get("/",(req,res)=>{
        res.sendFile(__dirname+"/public/home.html");
    });

    //creating a route for form data
    app.post("/formdata",(req,res)=>{
        const userDetails = new
         forms(req.body.datepicker,req.body.site,req.body.line,req.body.units);

        //Requesting database
        var request = new sql.Request();

        // let datetime =userDetails.d ;
        console.log(userDetails.d);

        const date = moment(userDetails.d).format('YYYY-MM-DD HH:mm:ss');

        // Insert data into the database
        let mssql = (`INSERT INTO DataEntry(Date,TimeStamp,Line,Units,Site)
           Values(${date},'25114','${userDetails.l}','${userDetails.u}','${userDetails.s}');`);

           request.query(mssql,function (err, data) {
               if (err) throw err;
               console.log("User data is successfully inserted");
          });
            res.sendFile(__dirname+"/public/home.html");
    });

    //Listern to port 3002
    app.listen(port,(e)=>{
        if(e) throw e;
        console.log("html page provided");
    });

*This is the error I'm getting

originalError: Error: Incorrect syntax near '11'.

*This is the date format on my database

Databasecolums and data format

*And this is how the date appears in my database when when the date picker datatype is set to "datetime-local".

Date entry to the database
As you can see things look pretty broken, please help me figure out this problem.


Q: .bash_profile permission denied I'm trying to make one of my first projects published with github but I'm having trouble testing the build locally.
I'm following the steps here:
https://jekyllrb.com/docs/installation/macos/
and I am stuck on the following command line runs:
echo "source $(brew --prefix)/opt/chruby/share/chruby/chruby.sh" >> ~/.bash_profile
echo "source $(brew --prefix)/opt/chruby/share/chruby/auto.sh" >> ~/.bash_profile
echo "chruby ruby-3.1.2" >> ~/.bash_profile # run 'chruby' to see actual version

Each time I run the first one, I get the following error:
-bash: /Users/account/.bash_profile: Permission denied
This is all very new to me and honestly I have no clue what I'm doing when it comes to the console. I am on MacOS Monetory and my shell is bash. Any help would be really appreciated!

A: Something has corrupted or changed ownership to root your .bash_profile script.
Open Terminal.app and do these:

*

*mv -f ~/.bash_profile ~/.bash_profile

*cp ~/.bash_profile.old ~/.bash_profile
These commands show not produce errors.
Now try to re-run your scripts to append to .bash_profile.


Q: $C$ be the curve of intersection of cylinder $x^2+y^2=2y$ and plane $y=z$ ; to evaluate $\int_C (y+z)dx + (x+z) dy +(x+y) dz$ by Stoke's theorem ? Let $C$ be the curve of intersection of the cylinder $x^2+y^2=2y$ and the plane $y=z$ ; how to evaluate $\int_C (y+z)dx + (x+z) dy +(x+y) dz$ by Stoke's theorem ? I cannot determine what is my surface $S$ over which to apply Stoke's theorem . Please help , thanks in advance

A: Hint: $x^2+y^2 = 2y$ can be rewritten into $x^2 +(y-1)^2 = 1$ and the parametric for of this would be the below.
$$\bar r(t) = cost\hat i + (sint+1) \hat j + (sint+1) \hat k$$
$$\bar r'(t) = -sint\hat i + cost \hat j + cost \hat k$$
$$F(\bar r(t)).\bar r'(t) = [2(sint+1)(-sint)  + (cost+sint+1)cost + (cost + sint +1)cost] $$
$$\int\int curlF.dS = \int_{0}^{2\pi}F(\bar r(t)).\bar r'(t)dt $$
Which when you evaluate gives you $\boxed{0}$


Q: IE10 anchor tag z-index issue In IE 10, I have a relatively positioned wrapper div with some content (an image / text). Inside of that div is an absolutely positioned anchor tag which is positioned to "cover" the entire wrapper div. It has a z-index set. So the entire area inside the wrapper div should be clickable. However, only the areas in the wrapper div that don't have content are clickable. The entire wrapper div is clickable in all other browsers except for IE 10. Here is a fiddle: http://jsfiddle.net/NUyhF/3/. Help?

Here is some text

.wrapper { position : relative; width: 500px; height: 300px; }
.wrapper a { position: absolute; top: 0px; width: 500px; height: 300px; z-index: 2; }

A: It is now semantically correct to wrap block level elements in an anchor tag (using the html5 doctype).  I would suggest amending your markup to this.
HTML

Here is some text

A: I have found this to be an annoying trait of IE for some time, to solve it I had to make a transparent image and use it as the background of the anchor tag:
background:url(transparent1x1.gif) repeat;

http://jsfiddle.net/NUyhF/6/


Q: Asp net core RC2. Как запустить MusicStore в debug mode Всем привет!
Пытаюсь перейти с RC1 -> RC2. Для изучения

*

*скачал MusicStore

*установил .NET Core SDK - .NET Core + CLI tools

*в папке с \MusicStore сделал dotnet restore

*в папке \MusicStore\src\MusicStore сделал dotnet build

*через dotnet run проект нормально запускается

Когда я открываю проект в VS2015, то вижу ошибки
unknown keyword platform

Соответственно скомпилировать проект не получается и запустить в debug не могу
Подскажите что нужно сделать?
E:\Develop\MusicStore\src\MusicStore>dotnet --info
.NET Command Line Tools (1.0.0-rc2-002543)

Product Information:
 Version:     1.0.0-rc2-002543
 Commit Sha:  38d0c28a1e

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.10240
 OS Platform: Windows
 RID:         win10-x64


Q: Multiprocessing pool.imap with large chunksize is skipping processing some records in iterable I am processing a list of string using multiprocessing pool.imap() with passing chunksize. My list length is 1821 and process in imap is 4. I was trying to give almost equal number of chunk size to each process so set chunk size as 455. Also tried with 500. But this makes my imap to skip some of the records.
Skipping was not so random too as it is ordered list. Once I changed the chunk size to 200, imap started sending all the records to my target function.
Can some one explain why the chunksize > 450 is causing issue here, while as per documentation it should be divided 1821/4  = 455 or 456 rec in each process ideally.
Also note , in my function I am using that string and running some steps which takes few seconds for each. While for testing I tried  to writing the string only in file inside target function and even then it was skipping some records.
  def process_init(self,l):
        global process_lock
        process_lock = l

  def _run_multiprocess(self,num_process,input_list,target_func,chunk):
        l = mp.Lock()
        with mp.Pool(processes=(num_process),initializer=self.process_init, initargs=(l,)) as p:
            start = time.time()
            async_result  = p.imap(target_func, input_list,chunksize =chunk)

            p.close()
            p.join()
            print("Completed the multiprocess")
            end = time.time()
            print('total time (s)= ' + str(end-start))

chunksize = 500
self._run_multiprocess(4,iterator_source,self._process_data,chunksize)

def _process_data(self,well_name):

        with open("MultiProcessMethod_RecordReceived.csv","a") as openfile:
            process_lock.acquire()
            openfile.write( "\t" +well_name.upper() + "\n")
            openfile.flush()
            process_lock.release()


Q: Unable to choose order of buttons in UIAlertController I was under the impression that if the normal action is a destructive action and the other is a cancel action in their UIAlertController that the destructive one should be on the left and the cancel should be on the right.
If the normal action is not destructive, then the normal action should be on the right and the cancel should be on the left.
That said, I have the following:
var confirmLeaveAlert = UIAlertController(title: "Leave", message: "Are you sure you want to leave?", preferredStyle: .Alert)

let leaveAction = UIAlertAction(title: "Leave", style: .Destructive, handler: {
        (alert: UIAlertAction!) in

        //Handle leave

    }
)

let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

confirmLeaveAlert.addAction(leaveAction)
confirmLeaveAlert.addAction(cancelAction)

self.presentViewController(confirmLeaveAlert, animated: true, completion: nil)

I was under the impression that if I add the leaveAction first, then the cancelAction that the leaveAction would be the button on the left. This was not the case. I tried adding the buttons in the opposite order as well and it also resulted in the buttons being added in the same order.
Am I wrong? Is there no way to achieve this?

A: My solution to this was to use the .Default style instead of .Cancel for the cancelAction.

A: Since iOS9 there is a preferredAction property on UIAlertController. It places action on right side. From docs:

When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.)
The action object you assign to this property must have already been added to the alert controller’s list of actions. Assigning an object to this property before adding it with the addAction: method is a programmer error.


Q: ASP.NET custom HttpHandler in IIS 7, 7.5 My web.config is setup as following. My handler lives in an assembly called TestProject.Custom. I am calling this handler via jQuery post, works great in VS 2010 (of course!) but when I push it out to IIS 7.5 or IIS 7, it throws 404 about not being able to find TestHandler.ashx. Not sure what I am missing.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />

<handlers>
  <add name="TestHandler"
       verb="*" preCondition="integratedMode"
       path="TestProject.Custom.HttpHandlers.TestHandler.ashx"
       type="TestProject.Custom.HttpHandlers.TestHandler, TestProject.Custom"/>

</handlers>

Edit: I am calling this handler with jQuery and the handler is behind forms authentication (which I don't think is the problem):
jQuery(function () {
    jQuery.ajax({
        type: "POST",
        url: "TestHandler.ashx",
        data: { "test_data": "some test data" }
    });
});

A: I think the "path" attribute should be "TestHandler.ashx" instead of its current value. It must match the URL you use in jQuery. Otherwise, 404 is expected.

A: 404 usually means a problem with the registration, basically it just can't find something to handle the request that came in.
Inside of the add node, try adding the following attribute at the end: resourceType="Unspecified"
That tells IIS not to look for a physical file when it sees the request for the ashx.  I think that's causing the 404


Q: org.apache.catalina.LifecycleException: Failed to start component i am getting this error when starting my tomcat server with my application.
I don't really understand it but if i "clean" in eclipse a few times or if i stop start the tomcat server a few times it somehow works, but then it happens over again if i stop.
any ideas?

WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:datalinx-backend' did not find a matching property.
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer- 2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.el-api-2.2.4.jar)    - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\javax.servlet-api-3.0.1.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-core-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class      May 27, 2014 11:23:36 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\wtpwebapps\datalinx-backend\WEB-INF\lib\tomcat-embed-el-7.0.52.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/el/Expression.class
May 27, 2014 11:23:39 AM org.apache.catalina.core.ContainerBase addChildInternal
SEVERE: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.IllegalStateException: Unable to complete the scan for annotations for web application [/backend] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies. The class hierarchy being processed was [org.bouncycastle.asn1.ASN1EncodableVector->org.bouncycastle.asn1.DEREncodableVector->org.bouncycastle.asn1.ASN1EncodableVector]
at org.apache.catalina.startup.ContextConfig.checkHandlesTypes(ContextConfig.java:2179)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2126)
at org.apache.catalina.startup.ContextConfig.processAnnotationsJar(ContextConfig.java:2001)
at org.apache.catalina.startup.ContextConfig.processAnnotationsUrl(ContextConfig.java:1967)
at org.apache.catalina.startup.ContextConfig.processAnnotations(ContextConfig.java:1952)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1326)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5269)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 11 more

 May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDescriptor
 SEVERE: Error deploying configuration descriptor D:\Applications\STS\vfabric-tc-server-developer-2.9.2.RELEASE\base-instance\conf\Catalina\localhost\backend.xml
 java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/backend]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:904)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1637)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)

  May 27, 2014 11:23:39 AM org.apache.catalina.startup.HostConfig deployDirectory

A: First of all, that looks like Pivotal's tc Server rather than Apache Tomcat. tc Server is based on Apache Tomcat but they are not exactlt the same and it always helps to provide the most accurrate information you can.
There is something seriously wrong with your dependencies. Tomcat is detecting the following class heirarchy:
org.bouncycastle.asn1.ASN1EncodableVector
 ->org.bouncycastle.asn1.DEREncodableVector
  ->org.bouncycastle.asn1.ASN1EncodableVector
This is a cyclic dependency. In Java it is illegal for A to extend B if B extends A.
Cleaning out your dependencies and ensuring you are using only using one version of the bouncy castle JAR should fix this.
If the problem persists and can be reproduced on a clean install of the latest stable Tomcat 7 release then please do open a bug against Apache Tomcat and provide the web application that demonstrates the issue.


Q: Connectionless UDP vs connection-oriented TCP over an open connection If a TCP connection is established between a client and server, is sending data faster on this connection-oriented route compared to a connectionless given there is less header info in the packets? So a TCP connection is opened and bytes sent down the open connection as and when required.  Or would UDP still be a better choice via a connectionless route where each packet contains the destination address?
Is sending packets via an established TCP connection (after all hand shaking has been done) a method to be faster than UDP?

A: I suggest you read a little bit more about this topic.
just as a quick answer. TCP makes sure that all the packages are delivered. So if one is dropped for whatever reason. The sender will continue sending it until the receiver gets it. However, UDP sends a packet and just forgets it, so you might loose some of the packets. As a result of this, UDP sends less number of packets over network.
This is why they use UDP for videos because first loosing small amount of data is not a big deal plus even if the sender sends it again it is too late for receiver to use it, so UDP is better. In contrast, you don't want your online banking be over UDP!
Edit: Remember, the speed of sending packets for both UDP and TCP is almost same, and depends on the network! However, after handshake is done in TCP, still receiver needs to send the acks, and sender has to wait for ack before sending new batch of data, so still would be a little slower.

A: In general, TCP is marginally slower, despite less header info, because the packets must arrive in order, and, in fact, must arrive.  In a UDP situation, there is no checking of either.


Q: Doing A is preferable to doing B. = Doing A rather than doing (?) / do (?) B is advisable
In that situation I would rather do A than (I would) (do) B.

If the verb 'do' appears after 'rather' it has to be in the bare infinitive, not in the gerund.
How about that other way of expressing the same idea?

Doing A rather than (do) (?) / (doing) (?) B is the course of action I would choose in that situation.*

The verb 'do' being itself the subject of the verb 'be' has to be in the gerund. If that same verb appears again after 'rather', should it also be in the gerund this time rather than in the bare infinitive?

A: You would say "Doing A rather than doing be" because of parallel structure because you are comparing two things.
Use parallel structure:

*

*With a coordinating conjunction such as and, but, or, nor, yet

*With a pair of correlative conjunctions such as either . . . or or not only . . . but also

*

*With a word introducing a comparison, usually than or as

http://www.grammar.com/rule-of-parallel-structure/


Q: How to have few options as checked in the entity/choice type in symfony I want to render the choice type from entity and its working fine. I want to few options to be checked by default when the form is rendered. For e.g. I have 10 options out of it only 3 options to be checked by default and when it persisted and in edit page whatever is saved to database should be rendered not the default 3 items. In the below title is fieldname
->add('attendee', EntityType::class, [
    'label' => 'Select any information you would like to
    require per Attendee:',
    'multiple' => true,
    'expanded' => true,
    'required' => true,
    'class' => 'AppBundle\\Entity\\Registrant',
    'choice_label' => 'title',
  ])

A: if you have saved some values, then symfony will select the values in the form itself. You don't need to preselect them. You need in your form type the method "configureOptions" like this:
    public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\MyClass'
    ));
}

If it is not working anyway, post more code.


Q: phonegap Google Analytics plugin for android returns class not found when i call one of the methods Good evening,
I am currently developing an application for android using phonegap  and sencha touch 1.1.
I am having trouble with the GoogleAnalyticsTracker plugin for Android. I followed all the instructions on github on how to import the necessery code for the plugin to work but I am having trouble with initialization.
In my plugins.xml I have added the following line:
< plugin name="Analytics" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker" />
As indicated in the readme.md file in github. I also added the GoogleAnalyticsTracker.java file inside com/phonegap/plugins/analytics and referenced the js file in my html... every thing seems to work fine except the part where I call the start method with my account id... The method returns the failure callback with error 'Class not found'. any ideas why phonegap cannot find the class specified in the xml?
if you need more info on this please do not hesitate to ask.
Thank you in advance!
PS. i am using phonegap 1.4.1
-L_Sonic

A: I took a look at the src and I see that the PhoneGap.exec calls in analytics.js does not match the plugin name. You have two ways to fix this.

*

*In plugins.xml make the plugin line:
<plugin name="GoogleAnalyticsTracker" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/>

*Or in analytics.js replace all instances of 'GoogleAnalyticsTracker' with 'Analytics'
This is a bug in the way the code is setup in github. You should message the author to get them to fix it.

A: Rather than using the PhoneGap plugin, I would recommend using the Google Analytics SDK for tracking usage of application developed using PhoneGap or any web based mobile app.
Ensure that you respect your users privacy and dont send any other data to Google Analytics.
Besides you should also adhere to Google Analytics privacy policy.
Heres how to do it.
http://www.the4thdimension.net/2011/11/using-google-analytics-with-html5-or.html


Q: XLSX Writer Python- 3 Color Scale with Number as Midpoint I'm trying to conditional formatting in XLSX writer with a 3 color scale with a 0 midpoint value in the middle.  I want all negative values to scale from red (lowest number) to yellow (when the value is zero) and all positive numbers to scale from yellow (at zero) to green (at the highest).
The scaling gets all messed up when I try the following..
Something that would look like the following in Excel:

I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:
worksheet.conditional_format('G2:G83', {'type': '3_color_scale',
                                     'min_color': "red",
                                     'mid_color': "yellow",
                                     'max_color': "green"})

I then tried to break it down with a criteria with one format applied to values above zero and one below zero
worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                    'min_color': "red",
                                    'max_color': "yellow"})

worksheet.conditional_format('G2:G83', {'type': '2_color_scale',
                                    'criteria': '>',
                                    'value': 0,
                                     'min_color': "yellow",
                                     'max_color': "green"})

But that doesn't seem to work either - if anybody has any ideas.. please let me know.. would really appreciate it.
Complete sample code:
import xlsxwriter

workbook = xlsxwriter.Workbook('conditional_format.xlsx')
worksheet1 = workbook.add_worksheet()

# Add a format. Light red fill with dark red text.
format1 = workbook.add_format({'bg_color': '#FFC7CE',
                           'font_color': '#9C0006'})

# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#C6EFCE',
                           'font_color': '#006100'})

# Some sample data to run the conditional formatting against.
data = [
[34, 72, -38, 30, 75, 48, 75, 66, 84, 86],
[-6, -24, 1, -84, 54, 62, 60, 3, 26, 59],
[-28, 0, 0, 13, -85, 93, 93, 22, 5, 14],
[27, -71, -40, 17, 18, 79, 90, 93, 29, 47],
[0, 25, -33, -23, 0, 1, 59, 79, 47, 36],
[-24, 100, 20, 88, 29, 33, 38, 54, 54, 88],
[6, -57, -88, 0, 10, 26, 37, 7, 41, 48],
[-52, 78, 1, -96, 26, -45, 47, 33, 96, 36],
[60, -54, -81, 66, 81, 90, 80, 93, 12, 55],
[-70, 5, 46, 14, 71, -19, 66, 36, 41, 21],

]
for row, row_data in enumerate(data):
    worksheet1.write_row(row + 2, 1, row_data)

worksheet1.conditional_format('B2:B12', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                    'min_color': "red",
                                    'max_color': "yellow"})

worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
                                    'criteria': '>',
                                    'value': 0,
                                     'min_color': "yellow",
                                     'max_color': "green"})

worksheet1.conditional_format('C2:C12', {'type': '2_color_scale',
                                    'criteria': '<',
                                    'value': 0,
                                     'min_color': "red",
                                     'max_color': "yellow"})

worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
                                     'min_color': "red",
                                     'mid_color': "yellow",
                                     'max_color': "green"})

workbook.close()
writer.save()

This is what I get:

As you can see, column B (the first column) has no green
Column C has no red
Column D has 0 as green
Any ideas how to do the 3 step scaling with zero in the middle?
Thanks

A:
I can figure out how to do a 3 color scale in XLSX writer, but there doesnt seem to be an option (I can see) for midpoint being a number:

You can use the min_type, mid_type and max_type parameters to set the following types:
min        (for min_type only)
num
percent
percentile
formula
max        (for max_type only)

See Conditional Format Options
So in your case it should be something like.
worksheet1.conditional_format('D2:D12', {'type': '3_color_scale',
                                         'min_color': "red",
                                         'mid_color': "yellow",
                                         'max_color': "green",
                                         'mid_type': "num"})

However, I'm not sure if that will fix your overall problem. Maybe add that to your example and if it doesn't work then open a second question.
One thing that you will have to figure out is how to do what you want in Excel first. After that it is generally easier to figure out what is required in XlsxWriter.

A: I know this is an old question but I just ran into this problem and figured out how to solve it.
Below is a copy of a utility function I wrote for my work. The main thing is that the min, mid and max types ALL need to be 'num' and they need to specify values for these points.
If you only set the mid type to 'num' and value to 0 then the 3 color scale will still use min and max for the end points. This means that if the contents of the column are all on one side of the pivot point the coloring will in effect disregard the pivot.
from xlsxwriter.utility import xl_col_to_name as index_to_col

MIN_MIN_FORMAT_VALUE = -500
MAX_MAX_FORMAT_VALUE = 500

def conditional_color_column(
        worksheet, df, column_name, min_format_value=None, pivot_value=0, max_format_value=None):
    """
    Do a 3 color conditional format on the column.

    The default behavior for the min and max values is to take the min and max values of each column, unless said value
    is greater than or less than the pivot value respectively at which point the values MIN_MIN_FORMAT_VALUE and
    MAX_MAX_FORMAT_VALUE are used. Also, if the min and max vales are less than or greater than respectively of
    MIN_MIN_FORMAT_VALUE and MAX_MAX_FORMAT_VALUE then the latter will be used

    :param worksheet: The worksheet on which to do the conditional formatting
    :param df: The DataFrame that was used to create the worksheet
    :param column_name: The column to format
    :param min_format_value: The value below which all cells will have the same red color
    :param pivot_value: The pivot point, values less than this number will gradient to red, values greater will gradient to green
    :param max_format_value: The value above which all cells will have the same green color
    :return: Nothing
    """
    column = df[column_name]
    min_value = min(column)
    max_value = max(column)

    last_column = len(df.index)+1
    column_index = df.columns.get_loc(column_name)
    excel_column = index_to_col(column_index)
    column_to_format = f'{excel_column}2:{excel_column}{last_column}'

    if min_format_value is None:
        min_format_value = max(min_value, MIN_MIN_FORMAT_VALUE)\
            if min_value < pivot_value else MIN_MIN_FORMAT_VALUE

    if max_format_value is None:
        max_format_value = min(max_value, MAX_MAX_FORMAT_VALUE)\
            if max_value > pivot_value else MAX_MAX_FORMAT_VALUE

    color_format = {
        'type': '3_color_scale',
        'min_type': 'num',
        'min_value': min_format_value,
        'mid_type': 'num',
        'mid_value': pivot_value,
        'max_type': 'num',
        'max_value': max_format_value
    }
    worksheet.conditional_format(column_to_format, color_format)


Q: multi-select with search ability in angularjs I started angularjs two weeks ago. I should make a multi select input with search ability.
What I made has 2 problems that I can't fix.
first when I search for "a" it won't filter correctly to only show "a" but the other work fine
second it has a bug when I select "a" to "d" and then deselect from "a" to "d" the last 2 won't delete and the second time that I do this it get's worse.

*

*please try to edit my own code if possible because I'm not good at reading other people's code

appreciate any help

var app = angular.module("myApp", []);

app.controller("myCtrl", function ($scope, $http) {

 $scope.selectEnable = false;
 $scope.selectedItems = [];

 $scope.openSelect = function () {
  $scope.selectEnable = !$scope.selectEnable;
 };

 $scope.itemChecked = function (data) {

  data.flag = !data.flag;
  var selected = $scope.datas.indexOf(data);
  var x = $scope.selectedItems.indexOf(data);
  if ((data.flag == true) && (x == -1)) {
   $scope.selectedItems.push(data.item);
  } else {
   $scope.selectedItems.splice(selected, 1);
  }
 };

 $scope.datas = [
  {
   "item": "a",
   /*"category": "x",*/
   "flag": false
  },
  {
   "item": "b",
   /*"category": "y",*/
   "flag": false
  },
  {
   "item": "c",
   /*"category": "x",*/
   "flag": false
  },
  {
   "item": "d",
   /*"category": "y",*/
   "flag": false
  }
 ];

});
ul li {
 list-style: none;
 text-align: center;
}

#category {
 text-align: center;
 background: #ddd;
}

#listContainer {
 width: 20%;
}

span {
 cursor: pointer;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>

 <link rel="stylesheet" href="stylesheet/style.css">

 <input type="text" ng-click="openSelect()">

{{selectedItems.toString()}}

  <input type="text" id="searchField" ng-model="searchField">

     <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems">
     {{data.item}}

A: Follow these steps:
1- Change your itemChecked function to this
$scope.itemChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item
    });
    if (selected == -1) {
      $scope.selectedItems.push(data.item);
    } else {
      $scope.selectedItems.splice(selected, 1);
    }

    };

2- Add an array for showing data after any filtering. Also add a function which filter your data according to input text:
$scope.filter = function() {
    if (!$scope.searchField) {
      $scope.data2Show = angular.copy($scope.data);
    } else {
      $scope.data2Show = [];
      $scope.data.map(function(itm) {
        if (itm.item.indexOf($scope.searchField) != -1) {
          $scope.data2Show.push(itm);
        }
      });
    }
  };

  $scope.data2Show = [];

Use this array to show items in list:

3- Write a function to check if an item is selected or not and use:
$scope.isChecked = function (data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      return false;
    } else {
      return true;
    }
  }

And usage in html :
<input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="selectedItems" ng-checked="isChecked(data)">

4- Change checkbox ngModels from selectedItems to data.flag
ng-model="data.flag"

Final code:

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope, $http) {
  $scope.selectEnable = false;
  $scope.selectedItems = [];

  $scope.openSelect = function() {
    $scope.selectEnable = !$scope.selectEnable;
  };

  $scope.itemChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      $scope.selectedItems.push(data.item);
    } else {
      $scope.selectedItems.splice(selected, 1);
    }
  };

  $scope.filter = function() {
    if (!$scope.searchField) {
      $scope.data2Show = angular.copy($scope.data);
    } else {
      $scope.data2Show = [];
      $scope.data.map(function(itm) {
        if (itm.item.indexOf($scope.searchField) != -1) {
          $scope.data2Show.push(itm);
        }
      });
    }
  };

  $scope.isChecked = function(data) {
    var selected = $scope.selectedItems.findIndex(function(itm) {
      return itm == data.item;
    });
    if (selected == -1) {
      return false;
    } else {
      return true;
    }
  }

  $scope.data2Show = [];

  $scope.data = [{
      item: "a",
      /*"category": "x",*/
      flag: false
    },
    {
      item: "b",
      /*"category": "y",*/
      flag: false
    },
    {
      item: "c",
      /*"category": "x",*/
      flag: false
    },
    {
      item: "d",
      /*"category": "y",*/
      flag: false
    }
  ];

  $scope.filter();
});
ul li {
  list-style: none;
  text-align: center;
}

#category {
  text-align: center;
  background: #ddd;
}

#listContainer {
  width: 20%;
}

span {
  cursor: pointer;
}

  <meta charset="UTF-8">
  <title>Document</title>

  <link rel="stylesheet" href="stylesheet/style.css">

  <input type="text" ng-click="openSelect()">

{{selectedItems.toString()}}

    <input type="text" id="searchField" ng-model="searchField" ng-change="filter()">

          <input type="checkbox" ng-change="itemChecked(data)" name="select" ng-model="data.flag" ng-checked="isChecked(data)"> {{data.item}}

There are some prepared directives for multi-selecting. for example this one Angular-strap selects


Q: AngularJS : Seqential Promise chain Function one passes value to two and then two passes value to three. Any of these functions could take any amount of time to return data. How can I make them wait for value instead of rushing ahead and printing undefined.
var deferred = $q.defer();

var one = function (msg) {
  $timeout(function () {
    console.log(msg);
    return "pass this to two";
  }, 2000);
};

var two = function (msg) {
  console.log(msg);
  return "pass this to three";
};

var three = function (msg) {
  console.log(msg);
};

deferred.promise
  .then(one)
  .then(two)
  .then(three);

deferred.resolve("pass this to one");

A: You need to return a promise from every function that does something asynchronous.
In your case, your one function returns undefined, while it would need to return the promise that you created for the "pass this to two" value after the timeout:
function one (msg) {
  return $timeout(function () {
//^^^^^^
    console.log(msg);
    return "pass this to two";
  }, 2000);
}

Btw, instead of using var deferred = $q.defer();, the chain is better written as:
one("pass this to one")
  .then(two)
  .then(three);


Q: Email addresses contain @HOSTNAME.domain.com when mail is configured using Profile Manager I'm setting up a Lion server environment for an entire office full of MacBook Pros, all running Lion. Lion server is 10.7.2, running Open Directory, DNS, and Mail.  I have successfully set up the mail server to relay mail for two domains.  Let's call them domainA and domainB.  Everything works if I set it up manually from the Mail client, but I'm trying to use Profile Manager.  Now, this requires quite a bit of explanation, so apologies in advance for the long post:
The "Settings for Everyone" profile, when auto-populated via the "Include configuration for services" setting in Server.app > Profile Manager seems to use the setting from Server Admin > Mail > General > "Host Name:".  If I set the hostname to one of the two domain names, the "Settings for Everyone" profile works fine, populates the user's Mail configuration with an address username@domain.com.  However, if I use the actual host name for this setting, it populates the email address as username@hostname.domain.com.  This is regardless of what is set in the "Domain Name:" setting on the same page.  This leaves me with an issue.  I can't choose the address / domain the user will use, as it would be defaulted to domainA or domainB via the "Hostname:" setting, not to mention that it just does not seem right to have to use "domain.com" as the hostname, and have DNS records pointed at a mail server.  (I would usually point the .domain.com DNS record to a web server, like many domains are set up)
So, I have set up a Group and Group Profile called MailTest, where I have specified the settings for the mail server.  I cannot use the "Settings for Everyone" because of the issue I mentioned above, which is why I thought I could just have two profiles, one for each domain.  I found this doc on Profile Manager variables, and used a few of these to set MailTest up so that it would dynamically configure Mail the way I wanted it.  Everything seems to work, EXCEPT for the Email Address setting.
I have tried using %email% for the Email Address setting, and verifying that the user's OD account has the correct address.  When I used %email%, it seems that the Incoming Mail > Mail Server and Port setting from the profile is actually used.  I also tried using %short_name%@domain.com, and experienced the same behavior.  The only time this setting seems to be recognized is when it is left blank.  Then, you are prompted for the email address when installing the profile.
For those of you that are still with me, has anyone experienced this issue?  Are there others that found that they could not use a hostname in the Mail server's settings or else their mail users would have a user@hostname.domain.com address?  Does anyone know why the "Email Address" profile setting seems to be overridden by the "Incoming Mail Server" setting?
I can certainly work around this by having multiple Profiles, and by using A records for domain.com that point to my mail server, but this is not desired.  I would like to use the %email% variable in my Profile so that I can use a single profile, in hopes of controlling users' email address from their OD account settings.

A: Another update...  I started fresh with a new install of Lion.  Updated to 10.7.3 first, having read about everyone's nightmares after this update.
Anyway, my Kerberos realm is now set to domain1.com, but Profile Manager still insists on using the incoming server name (hostname.domain1.com)as the email address.  I tried using both variables, %email% and %short_name%@domain1.com.  No luck either way.
What I find aggravating is that if you view the Profile when it is installed, or in Systems Settings > Profiles, the email address is correct.  This was also the case before I started over.  This leads me to believe that the profiles are somehow not implemented correctly by either Mail or the profile installation process.  I looked at the XML in the profile, and do not see any settings that would be responsible for the behavior.  Everywhere I used a variable, the resulting values were precisely as I expected.
I again tested the default "Settings for Everyone" profile that is configured automatically based on your server settings, and the Server Admin > Mail > General > "Host name:" setting still takes precedence.  So, if you put your actual hostname in this field (i.e. mail.domain.com) your users will all end up using user@mail.domain.com as an address.
I am admitting defeat for now, and just set up A records for domain.com that point to the mail server.  This way, I can set my two profiles up, one for each that use domain1.com and domain2.com, respectively, as their incoming servers.  The email address will then default to %short_name%@incomingserver

A: Same problem here. It is a bug in Apple Mail on 10.7.3.
If you open the downloaded mobileconfig file in a text editor you will see that the correct email address is listed.
I can confirm from testing that Apple Mail incorrectly populates the email address's domain part from the config's incoming mail server hostname.


Q: Angular dynamic form, sub-components not updating top level form As the title suggests, I've created a dynamic form using a mix of tutorials I've read.
I have a parent component which creates a empty form group which I then (try) to populate with sub-groups via child components. These components are passed a reference to the parent form, and the child component then creates its own formgroup and attempts to bind this to the parent.
The form model should then look like the following:
FormGroup
-- FormGroup1
---- FormControl1
---- FormControl2
-- FormGroup2
---- FormControl3
---- FormControl4
However, even thought the lower level form controls all render, the parent form doesn't seem to know they exist. My issue seems like it might be related to Angular 2: How to link form elements across a dynamically created components? but I was unable to figure out what he actually did to fix his issue.
Any thoughts?
See https://stackblitz.com/edit/angular-imi6j6?file=app%2Fapp.component.html for what I'm doing.

A: Wow... I just figured it out.
I was trying to add my subgroups to the parent via just assigning properties, but I should have been using FormGroup.addControl(new <FormGroup>).
Works perfectly now.


Q: I would like + please I received an email with this sentence:

*

*He gives a talk and then I and anyone else interested can discuss with him afterward.

In response to that sentence, can I write this next sentence or not? How is the best way of responding to it?

*

*I would also like to talk to him after his talk, please.

A: I think it might be better to say, "I would like to speak with him after his talk." That way you avoid using the word "talk" twice in the same sentence.


Q: type 'ObjectId' is not a subtype of type 'String' of 'value' I am trying to insert a document into my Mongo Database using the package mongo_dart
  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });

Runtime error on line 4
Unhandled Exception: type 'ObjectId' is not a subtype of type 'String' of 'value'

Is it an issue with the package or is something wrong with my code?

A: try this one
var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  }).toList();

A: Are you using the latest version of the package?
I think your problem is related to this issue in the GitHub Repo of the package but it is closed at Jul 25, 2015.

A: The error is arising because you declared variables db and (collection name) outside the static connect() async function; declare them inside the function.
  var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
    "dateTime": "today",
  });

static connect() async {
var db = await Db.create(MONGO_CONN_STRING);
  await db.open();
  var coll = db.collection('reports');
  await coll.insertOne({
    "username": "Tom",
    "action": "test",
   "dateTime": "today",
  });
}


Q: Flag-staff subtending greatest angle
A person moving towards a house observes that a flag-staff on the top of the house subtends the greatest angle $\theta$ when his distance from the house is d. Prove the heights of the flag staff and the house are $2d.tan\theta$ and $d.tan(45-\theta/2)$ respectively.

Le OP be the house and PQ be the flag-staff. And let A be the point where a circle through P and Q touches the ground. The book says that at A, PQ will subtend the greatest angle. I wonder why. Also, the book says $\angle AQP=\angle OAP$. I didn't understand this either.

A: The reasoning is the following. Let $C$ be a point at the "ground" (the line through the point $O $ perpendicular to $ OP $) distinct from $O$. Draw a circle through $P $, $Q $ and $C$. In general the circle will intersect the line $OC$ at one further point $C'$. As easy to see both points $C$ and $C'$ lie in the same semiplane with respect to the line $OP$. The center of the circle lies in the same semiplane as well. By the inscribed angle theorem the segment $PQ $ subtends the same angle (equal to the half of the central angle) for every point of the circle lying in the the semiplane, particularly for the points $C$ and $C'$. Now observe that for these circle points the smaller is the radius of the circle the larger is the subtended  angle. But if the radius is too small the circle does not intersect the "ground". It follows that the subtended angle for points lying on the "ground" attains the largest value when the "ground" is tangent to the circle.
The equality $\angle AQP=\angle OAP $ is a corollary of the inscribed angle theorem, saying that the angle subtended by a chord and the tangent line at one of its endpoints equals half of the central angle subtended by the chord.


Q: How to evaluate the change of information of a random variable? Given a random variable $X$ having finite alphabet $\mathcal{A}_X$ and valid $p_x(\cdot)$ (for which there is no $x_0 \in \mathcal{A}_X$ so that $p_x(x_0) = 0$) I want to know its actual outcome (speaking about sport, $X$ could be the team that would buy a really famous player: the experts would give me $\mathcal{A}_X$ and $p_x(\cdot)$).
I'm willing to pay a $V$ amount of money for this information and I've found someone who could help me. Before the closing of the deal I find out that the outcome of $X$ won't surely be, let's say, $x_0$.
Since prior this discovery the value of $X$ was $V$, what is the value $V^\star$ I should pay for the information?
How I would do - I would evaluate $H(X)$ using the definition, then I'd declare a new random variable $Y$ so that $\mathcal{A}_Y = \mathcal{A}_X \,/\, x_0$ and $p_Y(y) = \frac{p_x(y)}{1 - p_x(x_0)}$ and finally I'd evaluate $H(Y)$. Now I guess that $V^\star = \frac{H(Y)}{H(X)}V$.
I think this approach could be valid but I am not sure about that since it would be more natural to me to evaluate something like $H(X \,|\, X \neq x_0)$. Also, I'm not sure that a proportion is the way to go for finding $V^\star$.

A: Let's investigate if entropy can be a reasonable measure for this usage. Consider a rv $X$ whose alphabet is $\mathcal{A}_X = \{ \alpha, \beta, \gamma \}$ and $p_X(\alpha) = 0.9$, $p_X(\beta) = 0.05$ and $p_X(\gamma) = 0.05$. The entropy of $X$ defined as $$H(X) = -\sum_{x \in \mathcal{A}_X} p_X(x) \log_2(p_X(x))$$ gives $H(X) \simeq 0.57$. For example, let's say we're sure $\alpha$ won't be the outcome of $X$, we define $Y$ as stated in the question and evaluate its entropy obtaining $H(Y) = 1$. Considering another situation, this time $\gamma$ won't be the outcome of $X$ and if we define $Z$ as said above we get $H(Z) \simeq 0.3$.
In the initial scenario $\alpha$ is the most likely outcome, almost certain. If we remove that outcome we're left with no more than a coin toss, the worst case scenario: our knowledge about $X$ is actually lower than before (we thought we were almost certain about the outcome - not entirely sure) and now we're left with a 50-50 decision. Knowing the exact outcome now is more valuable than knowing it before - this is represented by the fact that $H(Y) > H(X)$.
On the other hand, removing $\gamma$ from the possible outcomes increases the probability that $\alpha$ will be the real outcome, lowering the uncertainty of the scenario and the value of the information I wanted to buy - confirmed by $H(Z) < H(X)$.
This example seems to agree that entropy is a reasonable measure for this usage.


Q: How to change permission of a kvm-qemu serial console output log I have a virtual machine with this config to redirect serial console log to another file:
<devices>
   ...
   <console type="pty">
       <target type="sclp"/>
       <log file="/home/nptusk/serial-console.log" append="on"/>
   </console>
</devices>

For automation reasons I want the log to have the permission other than root:root. What can I do to achieve this without using chown afterwards, in other words the log file when generated already has my desired user and group.

A: Kvm deamon is running on root.Otherwise it changes its uid,there is no way to change owner.But you can change its permssion to 665 or 664 so that you can access it,or change its ACL for more security


Q: How load Partial View with JavaScript In my view I have JavaScript to load a partial view.

@using (Html.BeginForm(@MyChoise, "Corr_Exit"))
{
    @Html.AntiForgeryToken()

                    etc...........

I'd load this partial between
 tag

But my code doesn't work. Why?
Someone can help me please?

A: I have used load ajax for this
$('#AREA_PARTIAL_VIEW').load('@Url.Action("Insert_Partial_View","Customers")');


Q: Ansible ec2_vpc_route_table playbook error was: 'dict object' has no attribute subnet I have a previously working piece of Ansible that I've inherited for a previous contractor, and I'm getting an error message that doesn't lead me in the right direction. I have tried searching for a few days now, with no joy, and my colleagues can't figure it out either.
The Ansible in question is :-
- name: Routes | Set up NAT-protected route table
  ec2_vpc_route_table:
    vpc_id: "{{ ec2_vpc_net_reg.vpc.id }}"
    region: "{{ vpc_region }}"
    tags:
      Name: "Internal {{ item.subnet_id }}"
    subnets:
      - "{{ az_to_private_sub[public_subnets_to_az[item.subnet_id]] }}"
      - "{{ az_to_private_data_sub[public_subnets_to_az[item.subnet_id]] }}"
    routes:
      - dest: 0.0.0.0/0
        gateway_id: "{{ item.nat_gateway_id }}"
  loop: "{{ existing_nat_gateways.result|flatten(levels=1) }}"
  #with_items: "{{ existing_nat_gateways.result }}"
  register: nat_route_table
  retry: 2
  delay: 10

And the error message is :-
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute u'subnet-0facefaceface9'\n\nThe error appears to have been in '/cup/core-kubernetes-linux/ansible/roles/aws_vpc/tasks/routes.yml': line 62, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Routes | Set up NAT-protected route table\n  ^ here\n"}

I have tried adding extra debug, for az_to_private_sub and public_subnet_to_az, and these look OK. I've tried reading the docs
Can anyone suggest where I should look next?
Thanks!

A: After speaking to a different colleague, they pointed out that the version which works uses Ansible 2.5.5 and I was trying with 2.5.1 also the boto python libraries need to be using the correct version.


Q: Interesting behaviour with infix notation One sometimes try to get away from your girlfriend by hiding behind your computer screen. However, I find that Scala is sometimes exactly like my girl...
This prints the intersection between two lists:
  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys.intersect(girls))

This prints absolutely nothing:
  val boys = List(Person("John"), Person("Kim"), Person("Joe"), Person("Piet"), Person("Alex"))

  val girls = List(Person("Jana"), Person("Alex"), Person("Sally"), Person("Kim"))

  println("Unisex names: " + boys intersect girls)

There are no compiler warnings and the statement prints absolutely nothing to the console. Could someone please explain gently (I have a hangover), why this is so.

A: It gets desugared to this:
println("Unisex names: ".+(boys).intersect(girls))

then according to the -Xprint:typer compiler option it gets rewritten like this:
println(augmentString("Unisex names: ".+(boys.toString)).intersect[Any](girls))

where augmentString is an implicit conversion from type String to StringOps, which provides the intersect method.


Q: iPhone SDK:NSScanner crashing randomly I have an application that scans text from a website in order to get the information and put it into my application. So in this case I'm retrieveing the number of notifications that the user has on facebook. Everything works fine except that the application crashes randomly. This is the code I have for searching for the number inside the text:
   NSScanner *theScanner = [NSScanner scannerWithString:facebookTextF];
NSScanner *theScanner2 = [NSScanner scannerWithString:facebookTextFa];

[theScanner scanUpToString:@"Notifications" intoString:&facebookTextFa] ;
[theScanner scanUpToString:@"\n" intoString:&facebookTextF] ;
NSString *NotificationsValue;
if ([facebookTextF isEqualToString:@"Notifications"]) {
    NotificationsValue = @"0";
    NSLog(@"%@", NotificationsValue);

       } else {
    [theScanner2 scanUpToString:@"Notifications" intoString:nil] ;
    [theScanner2 setScanLocation:([theScanner2 scanLocation] + 13)];
    [theScanner2 scanUpToString:@"\n" intoString:&facebookTextFa] ;

               NSLog(@"%@", facebookTextFa);

                    }

This code works well but just randomly crashes. Here is the crash log I get:
iphone[654:907] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSConcreteScanner setScanLocation:]: Range or index out of bounds'

* First throw call stack:
(0x3361b6c3 0x398b397f 0x3361b5e5 0x34d2632f 0x25147 0x34dbf78b 0x335f09ff 0x335f06b1 0x335ef321 0x3356239d 0x33562229 0x39fad31b 0x3402b8f9 0x22267 0x22208)
libc++abi.dylib: terminate called throwing an exception
This crash occurs randomly no matter what. For example if I leave it running for a while, after 7 minutes is just randomly crashes. Not sure what is wrong.
Thank you for looking. IF you need any more information please let me know.

A: You are getting that error message because (apparently) the string sometimes doesn't have the word "Notifications", so the theScanner2 sets its scan location to the end of the string. Then, when you try to set the scan location 13 characters ahead, it's past the end of the string, and you get an out of range error.

A: Trying to setScanLocation in NSScanner which is out of bound means the end of the string and beyond which doesnot exists by  setting scan location


Q: Parser for Pipfiles (get a list of all packages used in a Pipfile) Is there any parser out there for reading in a Pipfile and returning a list of all packages used in the Pipfile?
If not, how would one go about this? I was thinking a regular expression could do the job, but I am not sufficiently acquainted with the structure of Pipfiles to confirm that is the case.

A: first install pipfile    pip install pipfile.
then just use the parser it provides
from pipfile import  Pipfile
parsed = Pipfile.load(filename=pipfile_path)