text:
Q: Two different ON DELETE paths, how do I need to change the schema? For a project in school I'm designing a website that sells items via auctions. Think eBay, but on the complexity scale of school project. We went through the process of making an ER Diagram and planning things out but we still ran into a snag with the table creation statements in SQL. It's a problem I've never had before.
I know what the problem is now after a bit of digging. There is a table with two foreign keys to two different tables. One of those two tables has a foreign key into the other. That's all fine and great. Every foreign key has an ON DELETE CASCADE except for one, which has ON DELETE SET NULL because it makes business sense. Derby is baffing at the creation of the table with the two keys, because deleting a record in one table would cause two different actions in that table.
A clearer example, in SQL.
CREATE TABLE A (
  PrimaryA BIGINT,
  PRIMARY KEY (PrimaryA)
);

CREATE TABLE B (
  PrimaryB BIGINT,
  ForeignA BIGINT NOT NULL,
  PRIMARY KEY (PrimaryB),
  FOREIGN KEY (ForeignA)
    REFERENCES A(PrimaryA)
    ON DELETE CASCADE
);

CREATE TABLE C (
  PrimaryC BIGINT,
  ForeignA BIGINT
    DEFAULT NULL,
  ForeignB BIGINT
    NOT NULL,
  PRIMARY KEY (PrimaryC),
  FOREIGN KEY (ForeignA)
    REFERENCES A(PrimaryA)
    ON DELETE SET NULL,
  FOREIGN KEY (ForeignB)
    REFERENCES B(PrimaryB)
    ON DELETE CASCADE
);

So if those three statements went through (#3 wont) and someone deleted a row in A, there is the possibility that a row in C would want to be deleted and set null at the same time. While I respect the issue of the concurrency, shouldn't the deletion win? It isn't technically against the business logic for that to happen, but if it did I'd expect the row to be deleted.
So I obviously need to restructure the schema to avoid this pitfall but I can't really think of a way to do it and was hoping there was some magic keyword that would tell Derby to just delete the row and move on with life. If I do need to restructure, the context is that table C is the auction. Each auction has exactly one feedback entry, which is B. It also has exactly one user who is selling the item (A). Feedback (B) entries keep track of the user (A) who places them. In this respect it is the buyer who leaves the feedback.
Now it makes perfect sense to delete the auction (C) if the user (A) who is selling the item has their account deleted. However it doesn't make sense for the auction to be deleted if a rouge user (A) leaves foul feeback (B) on an auction (C) and gets their account deleted. It also doesn't make sense to populate the foreign key to B from C until after the auction is closed and the buyer (A) can leave feedback, which is why it is set to NULL initially. Like I said before, it is technically possible for a user (A) to create an auction (C) and then buy the item from themselves and leave feedback (B) and then have their account deleted. In that case the ON DELETE CASCADE should win from a business logic point of view.
I read through this question and the resolution was to normalize, which I've done already. In that question this was linked, and there they offered a solution to the multiple cascade path that I don't fully understand, but I get enough to believe it isn't a solution to this because I don't actually want to delete along both paths. Another thing mentioned was triggers. I have a rough understanding of triggers at a high level but have never designed or coded one before.


text:
Q: how can I accses the text contents of a specific DOM element stored in a array I am building a task list generator for a Javascript course. And I am not sure how to get the value of a text node inside of a List item to compare it with the value of a input field in my filter function.
The logic is onkeyup call the function taskFilter.
In the function taskFilter set the const text = to the key pressed by the user.
grab all the dynamically generated li elements and store them in the const htmlCollecton.
Declare a new array called const htmlaray
loop through the html collection and convert it into a array.
loop through the created array htmlaray and compare the inputed text char with the inner text of the list item. And that is where I got stuck :(
I am new to javascript I may be doing this all wrong but I am not sure help would be greatly appreciated
THE HTML
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="main.css">
        <title>Task Generator</title>

Task List

                <form class="form" action="" id="form">
                    <input type="text" name="taskInput" id="taskInput" placeholder="New Task">

                    <input type="submit" value="Add task" id="submitInput">
                </form>

                        <input class="filterInput" type="text" name="filter" id="filter" placeholder="Filter Tasks">

                    <button id="clearTasks">Clear Tasks</button>

THE CSS
/* http://meyerweb.com/eric/tools/css/reset/
  v2.0 | 20110126
  License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline; }

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block; }

body {
  line-height: 1; }

ol, ul {
  list-style: none; }

blockquote, q {
  quotes: none; }

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none; }

table {
  border-collapse: collapse;
  border-spacing: 0; }

/* apply a natural box layout model to all elements, but allowing components to change */
html {
  -webkit-box-sizing: border-box;
  box-sizing: border-box; }

*, *:before, *:after {
  -webkit-box-sizing: inherit;
  box-sizing: inherit; }

.clear:after {
  content: "";
  display: table;
  clear: both; }

.mainContentContainer {
  max-width: 960px;
  margin: 3rem auto;
  padding: 1%; }

.mainContent {
  border: 1px solid gray;
  border-radius: 6px; }

.h1 {
  margin: 1rem 0rem 1rem 0.5rem; }

.form {
  margin: 0rem 0rem 1rem 0.5rem; }

#taskInput {
  width: 98%;
  border: #c8c1c1 2px solid;
  border-radius: 6px;
  padding: 3px;
  margin-bottom: 0.3rem; }

#submitInput {
  background-color: black;
  color: white;
  border: gray 2px solid;
  border-radius: 6px;
  width: 35%;
  padding: 0.3rem 0rem 0.3rem 0rem; }

#submitInput:hover {
  background-color: #538a1c;
  cursor: pointer;
  -webkit-transition: background-color linear 0.5s;
  -o-transition: background-color linear 0.5s;
  transition: background-color linear 0.5s; }

#filter {
  width: 98%;
  border: #c8c1c1 2px solid;
  border-radius: 6px;
  padding: 3px;
  margin-bottom: 0.3rem; }

.filterAndClearTasks {
  margin: 0rem 0rem 1rem 0.5rem; }

#TaskCollection {
  border: #c8c1c1 2px solid;
  border-radius: 6px;
  width: 98%;
  font-size: 16px;
  padding: 1%; }

.taskListItems {
  background: cadetblue;
  padding: 2%;
  border: black solid 2px;
  border-radius: 6px;
  margin: 0.3rem 0rem 0.3rem 0rem;
  color: #242222;
  line-height: 1.3em; }

.taskListItems:hover {
  background: #265c5e;
  -webkit-transition: background-color linear 0.3s;
  -o-transition: background-color linear 0.3s;
  transition: background-color linear 0.3s;
  color: #bdc6cd; }

.floatingBtn {
  float: right;
  cursor: pointer;
  background: #0ee3cd;
  border-radius: 6px; }

.floatingBtn:hover {
  background-color: red;
  color: whitesmoke;
  -webkit-transition: background-color linear 0.2s;
  -o-transition: background-color linear 0.2s;
  transition: background-color linear 0.2s; }

#clearTasks {
  background-color: green;
  color: white;
  border: gray 2px solid;
  border-radius: 6px;
  width: 35%;
  margin-top: 0.3rem;
  padding: 0.3rem 0rem 0.3rem 0rem; }

#clearTasks:hover {
  background-color: #191a18;
  cursor: pointer;
  -webkit-transition: background-color linear 0.5s;
  -o-transition: background-color linear 0.5s;
  transition: background-color linear 0.5s; }

THE JAVASCRIPT
    const form = document.getElementById("form");
    const taskCollection = document.getElementById("TaskCollection");
    const clearTaskButton = document.getElementById("clearTasks");
    const filterInput = document.getElementById("filter");
    const taskInput = document.getElementById("taskInput");

    function attachEventListeners() {
        form.addEventListener("submit", addtask);
        taskCollection.addEventListener("click", removetask);
        filterInput.addEventListener("keyup", taskFilter);
        clearTaskButton.addEventListener("click", clearAllTasks);

    }
    attachEventListeners();

    function addtask(e) {
        const regexp = /^\s+$/;
        const task = taskInput.value;
        const result = regexp.test(taskInput.value);

        if (result === true || task === "") {
            alert("Please add a task!");
            e.preventDefault();
            return false;
        }else {
            console.log(result);
            const li = document.createElement("li");
            const button = document.createElement("button");
            const liText = document.createTextNode(task);
            const buttonText = document.createTextNode("x");

            li.appendChild(liText);
            li.className = "taskListItems clear";
            button.appendChild(buttonText);
            button.className = "floatingBtn";
            li.appendChild(button);
            taskCollection.appendChild(li);
            taskInput.value = "";
            e.preventDefault();
            return true;
        }
    }

    function clearAllTasks() {
        while(taskCollection.firstChild) {
            taskCollection.removeChild(taskCollection.firstChild);
        }
    }

    function removetask(e) {
        if (e.target.className === "floatingBtn") {
            if(confirm("Are you sure you want to delete this link?")) {
            e.target.parentElement.remove();
            }
        }
    }

    function taskFilter(e) {
        const text = e.target.value.toLowerCase();
        const htmlCollecton = document.getElementsByClassName("taskListItems");
        const htmlaray = [];
        for (var i = 0; i < htmlCollecton.length; i++) {
        htmlaray.push(htmlCollecton[i]);
        }

        for (var i = 0; i < htmlaray.length; i++) {
            if (text !== htmlaray[i].indexOf(innerText.toLowerCase()), 0) {
                htmlaray[i].style.display = "none";
            }else {
                htmlaray[i].style.display = "block";
            }
        }

        console.log(htmlaray);

    }

A: This filters tasks:
for (var i = 0; i < htmlaray.length; i++) {
    if (htmlaray[i].innerText.indexOf(text.toLowerCase()) < 0) {
        htmlaray[i].style.display = "none";
    } else {
        htmlaray[i].style.display = "block";
    }
}

Is this the desired result? You can use toLowerCase() as you see fit--it might be appropriate to apply it to both the search string and the list item string.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Структуры в с++
Описать структуру с именем NOTE2, содержащую поля: Name – фамилия и инициалы, TELE – номер телефона, DATE – дата рождения (год, месяц, число).
Написать программу, выполняющую:

*

*ввод с клавиатуры данных в массив BLOCK2, состоящий из 7 элементов типа NOTE1, записи должны быть упорядочены по фамилиям в алфавитном порядке;

*вывод на экран информации о человеке, чья фамилия введена с клавиатуры;

*если такого нет – выдать сообщение.

Неправильно выводит в таблице дату рождения и телефон, а так же выводит неверные данные по запросу фамилии после таблицы.
Подскажите в чем ошибка?
#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <conio.h>
#include <cstdlib>
#define M 15
#define N 7
#pragma warning(disable : 4996)// чтобы компилятор не ругался на strcpy

using namespace std;

struct NOTE2
{
    char name[M];
    int num;
    char date[M];
};

int main()
{

    setlocale(0, "rus");

    NOTE2 BLOCK2[N];
    int i;
    for (i = 0; i < N; i++)
    {
        cout << "\nВведите имя: ";
        cin >> BLOCK2[i].name;
        cout << "\nВведите номер телефона: ";
        cin >> BLOCK2[i].num;
        cout << "\nВведите дату рождения: ";
        cin >> BLOCK2[i].date;
    }
    char cur[M];
    for (i = 0; i<N - 1; i++)
        for (int j = i + 1; j<N; j++)
            if (strcmp(BLOCK2[i].name, BLOCK2[j].name)>0)
            {
                strcpy(cur, BLOCK2[i].name);
                strcpy(BLOCK2[i].name, BLOCK2[j].name);
                strcpy(BLOCK2[j].name, cur);
            }
    cout << "\n ________________________________________________________\n";
    for (i = 0; i < N; i++) {
        cout << BLOCK2[i].name << "    " << BLOCK2[i].num << "    " << BLOCK2[i].date << endl;

    }
    cout << "\n ________________________________________________________\n";
    char temp[M];
    int count;
    while (strcmp(temp, "exit")) {
        cout << "\nВведите фамилию: ";
        cin >> temp;
        count = 0;
        for (i = 0; i < N; i++) {
            if (strcmp(BLOCK2[i].date, temp) == 0)
            {
                cout << endl << BLOCK2[i].name << "    " << BLOCK2[i].num << endl;
                count++;
            }
        }
        if (count == 0) cout << endl << " Нет такой фамилии\n";
    }
    _getch();
}


text:
Q: How can I show a tooltip when a user hovers over the box shadow of an element? I have an element that is 1x1 px, with a box shadow that is much larger.
I would like a tooltip to display whenever the user hovers, but the problem is that the tooltip only activates when the user hovers over the 1x1 px area, ignoring the huge box shadow.
The blue element (glow) in this fiddle is an example. I tried making the green element (glow2) larger just to show how the tooltip should look.
https://jsfiddle.net/fortunette/fLm3d7oz/1/
.glow {

        width: 1px;
        height: 1px;
        background-color: blue;
        border-radius: 50%;
        box-shadow: 0 0 24px 19px blue;
        position:absolute;
        top:300px;
        left:100px;
  }

Other requirements are that there are an arbitrary number of these glowing elements at arbitrary positions and sizes.

A: Create pseudo-elements that are the same size as the entire area of your divs including the box-shadow.
The pseudo-element overlays can be transparent. Then use the :hover state for the pseudo-elements to trigger the tool tip.
Working example:

.glow {
  width: 1px;
  height: 1px;
  background-color: blue;
  border-radius: 50%;
  box-shadow: 0 0 24px 19px blue;
  position: relative;
  margin: 2em;
}

.glow:after {
  content: "";
  display: block;
  height: 50px;
  width: 50px;
  position: absolute;
  top: -25px; /* needs to be half of height and width */
  left: -25px; /* needs to be half of height and width */
  border-radius: 50%;
}

.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black;
}

.glow .tooltiptext {
  display: none;
  width: 120px;
  background-color: black;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0; /* Position the tooltip */
  position: absolute;
  z-index: 1;
}

.glow:hover:hover .tooltiptext {
  display: block;
}

Tooltip text

A: The box shadow is not part of the box html element and that is why your tooltip is not showing. I would recommend you wrap your box with in a div and use the tooltip on the outer div that also contains your box shadow.
Of course you will have to add padding to the outer div so it will fully contain the box shadow. This way when the user hover on the box shadow, they are actually hovering on top of the outer div and the tooltip will show up. You can use google chrome developing tools (ctrl+shift+i) to see how much padding you will need. Use a: hover or JqueryUI tooltip on the outer div class. Hope this helps!


text:
Q: solving an assembly conflict issue -- Visual Studio project reference + specific version SHORT QUESTION: How can I use a project reference but build my assembly so the reference is a specific version reference?

LONG QUESTION (more details): We're working on a modular setup for one of our applications.  Different sets of software components are loaded, along with their dependencies, into isolated AppDomains.
There are libraries that might be referenced by different components.  In some cases, we're running into assembly conflicts.  IE we've got the newest version of a library loaded AND an old version and one of the Types being used (components are instantiated using reflection) needs to grab something that's no longer in the new version, ie a type whose name has been changed or something, so a TypeLoadException or whatever is thrown because it's trying to pull the type from the new version even though the old version has also been explicitly loaded.  The way to avoid problems like this, it seems, is to reference specific versions.
As far as I understand it, the way to set a reference up this way from Visual Studio is to set the Specific Version property on the reference to true, and this can only be done when you're referencing a DLL as a file reference NOT as a project reference.  The problem is that these other libraries are still in development so I'll potentially need to be debugging them too during tests.  I want to be able to do all the nice stuff project references let you do ie navigate to definitions (mostly that, really, so i can set breakpoints while debugging and etc).

<Edit> In response to Slak's question, yes I do need to run both versions.  It's explained in the LONG QUESTION.

A: I believe what you are asking is something I have had to face before, but for platform specific dlls. You could easier adapt this to your requirements.
How to reference different version of dll with MSBuild

A: The solution that ended up working was actually signing all the assemblies in question and using custom resolution logic.  Specific Version did indeed have nothing to do with it.


text:
Q: inequality similar to AM>GM Is the inequality $$\frac{1}{n^2}(x-y)^2<xy$$ true in $[0,1]$ for some fixed positive integer $n$ and $x\neq y$?
I couldn't seem to get the answer, though I have a hunch that it is not so!
Any kind of help is needed. Thanks!

A: It is false.
Let $x=0.5$ and $y=0.1$. Then $$(x-y)^2=0.4^2=0.16$$ but $$xy=0.5\times0.1=0.05$$

A: Take $x=3y$
$$(x-y)^2<xy \implies 4y^2<3y^2$$


text:
Q: How to decrease the size of a label in tkinter python I want to decrease the size of a label in tkinter python.
the code:
from tkinter import *

top = Tk()
top.title("...")
top.geometry("200x200")

name = Label(top,text="Type Here: ").place(x = 20,y = 50)
e = Entry(top).place(x = 100, y = 50)
name1 = Label(top,text="Type Here: ").place(x = 20,y = 100)
e1 = Entry(top).place(x = 100, y = 100)

top.mainloop()

A: I suppose you want to decrease the font size:
name = Label(top,text="Type Here: ", font=("Courier", 11)).place(x = 20,y = 50)

just specify a font and a font size

A: You can set the width and height of a label like this
name = Label(top,text="Type Here: ", height=100, width=100)
name.place(x = 20,y = 50)

And you can change it with
name.config(height= new_height, width= new_width)


text:
Q: Google Chrome Not Rendering Font Properly I am making a website at the moment and I have noticed that my Chrome browser is not rendering Google Fonts properly. Does anybody have any ideas as to what this could be and how to sort it out please?
Please see the screenshot below for an example:
OS: Windows 8.1
Browser: Google Chrome 41.0.2272.76 m
Font: Open Sans and Bree Sans for headings

If you need any more information please let me know.
http://i.imgur.com/5UDUbBy.png


text:
Q: Definition of limit: $\forall n>N$ or $\forall n \geq N$? My question is about the definition of limit.

Definition: The number $a$ is said to be the limit of the sequence $\{x_n\}$ if $\forall \epsilon > 0$, $\exists N \in \mathbb{N}$ such that $\forall n > N$, we have
  $$|x_n - a| < \epsilon.$$

This definition is in the book "The fundamentals of Mathematical Analysis - Fikhtengol'ts". But in "Principles of Mathematical Analysis - Walter Rudin", he uses the condition $n \geq N$. Is there any difference in the definition of limit when we use the conditions $n>N$ and $n \geq N$?

A: No. There are no differences ! Try a proof !

A: No, because both of them means the same: the inequality
 $|x_n-a|<\epsilon$
holds true for every natural number except finitely many.

A: No, since $n>N\iff n\geqslant N+1$.


text:
Q: Run some task in parallel and others sequentially using python I was new to python, Now, I have an requirements to run single function as parallel for some process and some may be depends on others.
My dataset will be like:
[
  {
    'process_id': 1,
    'dependency_id': 0
  },
  {
    'process_id': 2,
    'dependency_id': 0
  },
  {
    'process_id': 3,
    'dependency_id': 0
  },
  {
    'process_id': 4,
    'dependency_id': 2
  },
  {
    'process_id': 5,
    'dependency_id': 2
  },
  {
    'process_id': 6,
    'dependency_id': 1
  }
]

Here,

the process_id 1,2,3 should run in parallel because it has the
  dependency_id as 0.
the process_id 4 has the dependency_id as 2 -- it should wait until
  process 2 get done
the process_id 5 has the dependency_id as 2 -- it should wait until
  process 2 get done. Now process 4 and 5 should wait for 2 and get run
  in parallel.
the process_id 6 has the dependency_id as 1 -- it should wait until
  process 1 get done

I have tried in the following way :
from multiprocessing import Process
from time import sleep

process = []
process_list =[{'process_id': 1,'dependency_id': 0},{'process_id': 2,'dependency_id': 0},{'process_id': 3,'dependency_id': 0},{'process_id': 4,'dependency_id': 2},{'process_id': 5,'dependency_id': 2},{'process_id': 6,'dependency_id': 1}]

def process_fn(process_id):
    print i

def main():
  for item in len(process_list):
     p = process(target=process_fn, args=(item['process_id']))
     process.append(p)
     p.start()

But I want to know how to include that dependency logic inside multiprocessing. Can anyone please help me with the solution.


text:
Q: Border is overlapping the child and sub-child of li I'm trying to develop a bordered box using ul li,
I have applied borders but the problem is when I applied border bottom and border top for li, the first 1px border-bottom is overlapping with second li border-top and it is appearing like 2px border.
My code is below,

.main-permissions-box{
  border-right: 1px solid #555;
  border-bottom: 1px solid #555;
  border-left: 1px solid #555;
  width: 380px;
  margin: 0 auto;
  margin-bottom: 20px;
}
.main-permissions-box li{
  list-style-type: none;
  padding:8px;
  border-top:1px solid #555;
  border-bottom:1px solid #555;
}
.main-permissions-box > ul> li{
  border-bottom:1px solid #555;
}
.main-permissions-box > li:first-child{
  border-top: 1px solid #555;
}
.main-permissions-box ul ul li{
  border-left:1px solid #555;
}
.main-permissions-box > ul{
  padding: 0;margin: 0;
}
.permission-text{
  padding-left: 25px;
}

        <input type="checkbox" class="checkBoxClass">
    Pre Sales

      <input type="checkbox" class="checkBoxClas">
    Schedule Consultation

       <input type="checkbox" class="checkBoxClass">
    Option One

       <input type="checkbox" class="checkBoxClass">
    Option Two

     <input type="checkbox" class="checkBoxClass">
         Schedule Consultation

      <input type="checkbox" class="checkBoxClass">
          Customer

Is there any way to apply border so that it wont appear like it is overlapping?

A: Apply margin-bottom to the list elements. Here is the code:

    .main-permissions-box{
  border-right: 1px solid #555;
  border-bottom: 1px solid #555;
  border-left: 1px solid #555;
  width: 380px;
  margin: 0 auto;
  margin-bottom: 20px;
}
.main-permissions-box li{
  list-style-type: none;
  padding:8px;
  border-top:1px solid #555;
  border-bottom:1px solid #555;
}
.main-permissions-box > ul> li{
  border-bottom:1px solid #555;
  margin-bottom:-1px;
}
.main-permissions-box > li:first-child{
  border-top: 1px solid #555;
}
.main-permissions-box ul ul li{
  border-left:1px solid #555;
  margin-bottom:-1px;
}
.main-permissions-box > ul{
  padding: 0;margin: 0;
}
.permission-text{
  padding-left: 25px;
}

        <input type="checkbox" class="checkBoxClass">
    Pre Sales

      <input type="checkbox" class="checkBoxClas">
    Schedule Consultation

       <input type="checkbox" class="checkBoxClass">
    Option One

       <input type="checkbox" class="checkBoxClass">
    Option Two

     <input type="checkbox" class="checkBoxClass">
         Schedule Consultation

      <input type="checkbox" class="checkBoxClass">
          Customer

Increase the margin by the amount you wish. Hopefully this is what you need.

A: If this is what you want, I'd be inclined to use a table instead of an unordered list. However, you can get the effect you want by using outline styles instead of borders. You'll need to add an extra 1px margin to the boxes in order to get these outlines to overlap, and you need a bit more adjustment to get things lined up down the left side, but it should work:

.main-permissions-box{
  border-left: 1px solid #555;
  width: 380px;
  margin: 0 auto;
  margin-bottom: 20px;
}
.main-permissions-box li{
  list-style-type: none;
  padding:8px;
  margin: 1px;
  outline: 1px solid #555;
}
.main-permissions-box > ul> li{
  margin-left: 0;
}
.main-permissions-box > li:first-child{
}
.main-permissions-box ul ul li{
}
.main-permissions-box > ul{
  padding: 0;margin: 0;
}
.permission-text{
  padding-left: 25px;
}

        <input type="checkbox" class="checkBoxClass">
    Pre Sales

      <input type="checkbox" class="checkBoxClas">
    Schedule Consultation

       <input type="checkbox" class="checkBoxClass">
    Option One

       <input type="checkbox" class="checkBoxClass">
    Option Two

     <input type="checkbox" class="checkBoxClass">
         Schedule Consultation

      <input type="checkbox" class="checkBoxClass">
          Customer

A: The question is already answered but answering if someone wants to solve it by border and not with outline or negative margins
This excerpt from below code helps with any kind of nesting and not only the nesting in this question
ul > li{ border-bottom: 1px solid #555; }
ul > li:last-child{ border-bottom: none; }
ul > li:first-child{ border-top: 1px solid #555; }
ul ul > li:first-child{ border-top: none; }

First three rules make sure an individual ul is bordered correctly and the last rules takes care of the nesting

.main-permissions-box {
  border-right: 1px solid #555;
  border-bottom: 1px solid #555;
  border-left: 1px solid #555;
  width: 380px;
  margin: 0 auto;
  margin-bottom: 20px;
}

.main-permissions-box li {
  list-style-type: none;
  padding: 8px;
}

.main-permissions-box ul ul li {
  border-left: 1px solid #555;
}

.main-permissions-box>ul {
  padding: 0;
  margin: 0;
}

.permission-text {
  padding-left: 25px;
}

.main-permissions-box ul>li {
  border-bottom: 1px solid #555;
}

.main-permissions-box ul>li:last-child {
  border-bottom: none;
}

.main-permissions-box ul>li:first-child {
  border-top: 1px solid #555;
}

.main-permissions-box ul ul>li:first-child {
  border-top: none;
}

            <input type="checkbox" class="checkBoxClass">
            Pre Sales

              <input type="checkbox" class="checkBoxClas">
              Schedule Consultation

                <input type="checkbox" class="checkBoxClass">
                Option One

                <input type="checkbox" class="checkBoxClass">
                Option Two

            <input type="checkbox" class="checkBoxClass">
            Schedule Consultation

            <input type="checkbox" class="checkBoxClass">
            Customer


text:
Q: hg changegroup hook - suppress specific output from hg? I have written a changegroup hook that is invoked in my local repository when I pull changes from the remote server copy. In the hook implementation, I invoke hg update to pull in the changes. On running hg pullcommand, the output shows as follows:
pulling from ssh://lava@lava.in/hgrepo
searching for changes
adding changesets
adding manifests
adding file changes
added 1 changesets with 1 changes to 1 files
Verified file test1.cpp
(run 'hg update' to get a working copy)

Since I am already invoking hg update in the hook, I want to suppress the last line that suggests user to run hg update.

A: There's another thread that might be useful.
Also, if you are doing this just for yourself, you could achieve the same result with an alias for pull -u; I use an alias called get and I tend to just run hg get to effect a pull and update.
If you are using TortoiseHg, you can add postpull = update under the [tortoisehg] section in the appropriate file (.hgrc/hgrc/mercurial.ini) and that will take care of updating your working directory after you fetch remote changes using the Workbench.


text:
Q: How to create data and render within the one get request

dashboardRouter.route('/:Teachersubjects/:Class/:Salary')
         .get(function(req,res)
            {
              function handleErr(err,redir)
  {
    if(redir){
      res.end("err");
    }
    else{
      res.writeHead(200, {"content-type": "text/plain"});
      res.end('Error occured');
    }
  }
              Verify.verifySchoolUser(req,res,function(err,schooluserId){
              if(err){
                res.redirect('/schoolusers/login');
                return;
              }
              else{
                SchoolUser.findOne({_id:schooluserId}).exec(function(err,schooluser){
                  if(err)
                  {
                    console.log("NOUSER school")
                    handleErr(err);
                    return;
                  }
                  else
                  {
                    if(schooluser.count<4){
                      console.log(req.params.Class);
                      vacancies.create(req.params,function(err,vacancy){
                        if(err){
                          console.log(err.message);
                          console.log(err.name);
                          console.log("create error");
                          for (field in err.errors) {
                            console.log(err.errors[field].message);
                          }
                          handleErr(err);
                            return;
                          }
                          console.log(vacancy);

                          schooluser.vacancies.push(vacancy._id);
                          schooluser.save(function(err){
                          if(err){
                            console.log(JSON.stringify(err));
                            handleErr(err);
                          }
                          teacherforms.find({}, function (err, teacherforms) {
                            if (err) throw err;
                            else {
                              var teacherforms = teacherforms;
                              console.log(teacherforms);
                              var arr=[];
                              for(i=0; i<teacherforms.length; i++ ) {
                                arr.push(teacherforms[i]._id);
                                console.log(arr);
                              }
                              teacherusers.find({checking:{$in:arr}}, function (err, teacherusers){
                                if (err) throw err;
                                else{

                                  var data =[];
                                  for(i=0; i<teacherusers.length; i++ ) {
                                    var kdata={};
                                    var str = "";
                                    kdata.firstname = teacherusers[i].firstname;
                                    kdata.profilepic= teacherusers[i].profilepic;
                                    kdata.experience= teacherforms[i].Teachingexperience;
                                    var len= teacherforms[i].Qualifications.length;
                                    console.log(teacherforms[i].Qualifications);
                                    for(j=len-1;j>=0;j--){
                                      if(j==0){
                                        str = str + teacherforms[i].Qualifications[j];
                                      }
                                      else{
                                        str=str + teacherforms[i].Qualifications[j] + ", ";
                                      }
                                    }
                                    kdata.qualifications = str;
                                    data.push(kdata);
                                  }
                                  data.push(vacancy.Class);
                                  //data.push(vacancy.Qualification);
                                  data.push(vacancy.Teachersubjects);
                                  console.log(data);
                                  res.render('../views/dashboard/dashboard_resumes.ejs',{
                                    sdata:data
                                  });
                                }
                              });
                            }
                          })
                        });
                      })
                }
                else {
                res.send("Limit Exceeded");
              }
}
              });
              }

        });
});

I want to save a object firstly in MongoDB at get request and then render a page in ejs with a new object.But I am getting a error 500(Internal Server Error),so can we save a object and render the ejs page with new object at same end point?
P.S- The code below is the crucial part of the code and there is no syntax error and schooluser(object) is passed from the upper part of the code.
dashboardRouter.route('/:Teachersubjects/:Class/:Salary')
  .get(function(req, res) {
    vacancies.create(req.params, function(err, vacancy) {
      if (err) {
        console.log(err.message);
        console.log(err.name);
        console.log("create error");
        for (field in err.errors) {
          console.log(err.errors[field].message);
        }
        handleErr(err);
        return;
      }

      schooluser.vacancies.push(vacancy._id);
      schooluser.save(function(err) {
        if (err) {
          handleErr(err);
        } else {
          res.render('../views/dashboard/dashboard_resumes.ejs', {
            sdata: data
          });
        }
      });
    });
  });

A: There are multiple issues with your route handler. First, whenever an error occurs you run this through your handleErr() function, but you never do anything with res in these cases. This means that the request is never resolved and eventually times out on the client side.
When an error occurs, you should respond with an error code. For instance:
res.status(400).send('Something went wrong');

When you actually do send a response and render the template, you're applying a variable called data. However, this variable doesn't seem to be declared anywhere in your code. Maybe you left out that code, but if that variable is indeed undeclared, it throws a ReferenceError which is caught by the routing framework which in turn responds with a 500 Internal Server Error. So this is probably the source of your issue.
Any uncaught errors thrown by vacancies.create() or schooluser.save() would have the same effect.


text:
Q: Assign first value in the day to the rest of the rows for that day using Pandas Please, I have a pandas dataframe containing intraday data for 2 stocks.
The index is a time series sampled by minute (i.e. 1/1/2017 9:30, 1/1/2017 9:31, 1/1/2017 9:32, ...).
There are only two columns "Price A", "Price B".
Total number of rows = 52000.
I need to create a new column in which I store the 9.30 am value for every day.
Assuming for 1/1/2017, the 9:30 am "Price A" is 150, I would need to store this value in a new column called "Open A" for every row that has the same day.
For example:
Sample input:
                     Price A  Price B
date
2017-01-01 09:30:00      150        1
2017-01-01 09:31:00      153        2
2017-01-01 09:31:00      149        3
2017-01-01 09:31:00      151        4
2017-02-01 09:30:00      145        1
2017-02-01 09:31:00      139        2
2017-02-01 09:31:00      142        3
2017-02-01 09:31:00      149        4

I tried to simply use:
for ind in df.index:
    df['Open A'][ind] = 2
just to make a test but this seems to be taking forever.
I also tried to read what's available here:
How to iterate over rows in a DataFrame in Pandas?
but it doesn't seem to be of help.
does anybody have a suggestion?
Thanks

A: If needed, set your index to datetime -
df.index = pd.to_datetime(df.index, errors='coerce')

df

                     Price A  Price B
date
2017-01-01 09:30:00      150        1
2017-01-01 09:31:00      153        2
2017-01-01 09:31:00      149        3
2017-01-01 09:31:00      151        4
2017-02-01 09:30:00      145        1
2017-02-01 09:31:00      139        2
2017-02-01 09:31:00      142        3
2017-02-01 09:31:00      149        4

An assumption here is that your day's recordings start at 9:30, making our job really easy.
Use groupby with a pd.Grouper + transform + first -
df['Open A'] = df.groupby(pd.Grouper(freq='1D'))['Price A'].transform('first')
df

                     Price A  Price B  Open A
date
2017-01-01 09:30:00      150        1     150
2017-01-01 09:31:00      153        2     150
2017-01-01 09:31:00      149        3     150
2017-01-01 09:31:00      151        4     150
2017-02-01 09:30:00      145        1     145
2017-02-01 09:31:00      139        2     145
2017-02-01 09:31:00      142        3     145
2017-02-01 09:31:00      149        4     145


text:
Q: UART loopback test for vxworks I trying to write a command line UART loopback test. First, I used 'devs' to find the serial port: /tyCo/0. Then I opened the serial port for read/write: fd=open("/tyCo/0",2).
Since read() appears to be a blocking call, I tried to create a task to perform the read:
sp(read, fd, &W, 0x10) where W=malloc(0x10).
I tried writing to fd: write(fd,"HELLO",5) but when I display the contents at &W, I get garbage.
When I list the running tasks I see the task I created for read which is "PENDING" and has priority 100. I've used taskPrioritySet() to assign it different priorities but to no avail.
I was hoping the task I created, which I'd like to block immediately on a read() call, would wake up when I execute the write().
Any ideas on how I might accomplish a command line UART loopback test?

A: read call is blocking as you suggest, but only blocks if there is nothing to read. So you do not have to spawn a task for it, can be just called from the command line (and if it blocks due to lack of input you can break the call and restart the command line task by sending CTRL-C via a terminal)
Another point is, W is a pointer, that points to the allocated memory. No need to take the address of it (and I am not sure if VxWorks shell handles address referencing of its variables)
As a disclaimer, currently I do not have a system to test these steps below. But having done the exact thing you are trying to do, this is how it is supposed to look like.
To sum it up, this should be a MWE:
fd=open("/tyCo/0",2)
W=malloc(0x10)
write(fd,"HELLO",5)
read(fd, W, 0x10)
d W

As a side note, tyCo/0 is often the serial port that is used for the vxWorks shell communication. So make sure you are actually using the correct port name.
To verify the operations on fileDescriptors, you can ditch the serial port and open a file as a test. At least you will be certain that you can read and write to a fileDescriptor as expected.
fd=open("testFile",2)
W=malloc(0x10)
write(fd,"HELLO",5)
read(fd, W, 0x10)
d W


text:
Q: return only one document for each filter defined in the query In one of my latest projects I use Solr 1.4 for searching products.However I have ran into a slight problem, which I aint sure if its possible to do using Solr.
All products are indexed by "country" and "category" and the "id", "class" and "description" are stored values. I now have been requested to extract a sample list of products that we have for a give "category" and "ONLY RETURNING ONE" product for each country where the product is available.
In my current implementation, I have a dismax query to get a list of all the countries that correspond to the catergory, then I call again solr to extract all products for each country, limiting the no. rows by the size of the countries found in the previous query.
The problem I have with this current implementation is I can not be certain that I have one product for each country in the list. Therefore would anyone know if it possible to tell solr that you want only one product per country provided in the query?
Any guidance would be useful.

A: Take a look at Field collapsing. It allows you to do something analogous to a GROUP BY in SQL. Unfortunately, as of this writing, this feature is not even in trunk. You have to download the latest patch from the issue tracker, apply it to trunk and compile.


text:
Q: Elements of $L^p$ and nice representatives of equivalence classes Considering $L^p$ $( 1 \leq  p < \infty)$ as a normed vector space, each element of $L^p$ is actually an Equivalent class. Take $[f] \in L^p $ as an Equivalent class, What is the Nicest possible function $g$ such that $g \in [f]$ (i.e. $g=f$ almost everywhere).
By the word Nice you are free to consider any good topological or algebraic property like continuity, differentiability, boundedness, etc... (as many as you can)
Second question: Let $N$ denotes the set of such Nice Properties, imposing $N$ as set of conditions on $g$, can one identify $g$ uniquely ? In other words can we rewrite  $L^p$ in following way
$$L^p = \{ g : R\rightarrow R \cup \{\pm \infty\}  \quad  | \quad  \|g\|_p < \infty  ,~g\text{ satisfies }N    \}$$
This makes we can think about  $L^p$ as a set of nice functions, free of any confusing equivalent classes.
Clarification: My intention is to find a set of finite conditions called $N$ , when we imposing them, $g$ is determined uniquely, in order to replace this $g$ by $[f]$ to rewrite $L^p$ as above.
Lusin's theorem says one can pick $g \in [f]$ such that $g$ is continuous except on very small set (as small as you want but might have positive measure).This might be helpful but still can't give us the set of condition $N$ !

A: In harmonic analysis one frequently defines a modification of $f$ by taking the new value $f(x)$ as the limiti of averages of $f$ over balls centered at $x$, with radius tending to 0. You do this at every point for which the limit exists. If $f$ is equivalent to a continuous function, this method produces the continuous representative. By Lebesgue differentiation this limit exists at almost every $x$ and coincides with the original value of $f(x)$ for any locally $L^1$ function; of course it remains the question of how to redefine $f$ at points where the limit do not exist; maybe one can set $f=0$ there. I guess you can not do better than this, but I might be wrong since I do not know lifting theory.


text: Q: How to delineate a zone of slope break I have a DEM of a region and want to delineate about a half-mile region at the base of hills (e.g. an area where the slope changes from steep to shallow). I ran the slope analysis tool and it kinda works if I classify it with low slope values (0-10) and high (10+) (see image), but I am still left with the tops of ridges and high elevation areas also showing shallow slope. How might I just show a region at the base of hills?


text:
Q: Prove that $(ab+ac+bc)\sum\limits_{cyc}\frac{1}{(a-7b)^2}\geq\frac{1}{4}$
Let $a$, $b$ and $c$ be non-negative numbers such that $\prod\limits_{cyc}(a-7b)\neq0$. Prove that:
  $$(ab+ac+bc)\left(\frac{1}{(a-7b)^2}+\frac{1}{(b-7c)^2}+\frac{1}{(c-7a)^2}\right)\geq\frac{1}{4}$$

I think this inequality is very interesting
because it's similar to the known Ji Chen's inequality (Iran 1996):
$$(ab+ac+bc)\left(\frac{1}{(a+b)^2}+\frac{1}{(b+c)^2}+\frac{1}{(c+a)^2}\right)\geq\frac{9}{4}$$
Example of my trying.
BW does not help:
Let $a=\min\{a,b,c\}$, $b=a+u$ and $c=a+v$.
Hence, we need to prove that:
$$44064(u^2-uv+v^2)a^4+864(38u^3+17u^2v+73uv^2+38v^3)a^3-$$
$$-24(217u^4-1478u^3v-2157u^2v^2-3494uv^3+217v^4)a^2+$$
$$+4(98u^5-1631u^4v+3938u^3v^2+15698u^2v^3-1463uv^4+98v^5)a+$$
$$+uv(196u^4-2793u^3v+10490u^2v^2-2457uv^3+196v^4)\geq0,$$
which is nothing.
Thank you!

A: Hints:
1)Put : $A=a$,
$AB=b$,
$AC=c$
With this following substitution you can eliminate a variable
We obtain $$(B+C+BC)(\frac{1}{(1-7B)^2}+\frac{1}{(B-7C)^2}+\frac{1}{(C-7)^2})$$
2)Try to prove this :
$(x+\alpha+\frac{1}{x+\beta}+\frac{x+\alpha}{x+\beta})(\frac{1}{(1-7(x+\alpha))^2}+\frac{1}{((x+\alpha)-7\frac{1}{x+\beta})^2}+\frac{1}{(\frac{1}{x+\beta}-7)^2})$
$\geq  (x+\alpha+\frac{1}{x+\alpha}+1)(\frac{1}{(1-7(x+\alpha))^2}+\frac{1}{((x+\alpha)-7\frac{1}{x+\alpha})^2}+\frac{1}{(\frac{1}{x+\alpha}-7)^2}) $
With $0\leq \beta\leq \alpha \leq x$
For the last inequality it's easy to see that $$(x+\alpha+\frac{1}{x+\alpha}+1)(\frac{1}{(1-7(x+\alpha))^2}+\frac{1}{((x+\alpha)-7\frac{1}{x+\alpha})^2}+\frac{1}{(\frac{1}{x+\alpha}-7)^2}) $$
Is a translation of the function :
$$(x+\frac{1}{x}+1)(\frac{1}{(1-7(x))^2}+\frac{1}{((x)-7\frac{1}{x})^2}+\frac{1}{(\frac{1}{x}-7)^2}) $$
And the minimum of this last function is 0.25


text:
Q: JQMobile - unable to load spinner in custom ajax I have a search form that is data-ajax=false. As i want to write my own custom ajax call.
<form id="search" data-ajax="false">
<fieldset data-role="controlgroup" data-mini="true">
<input required="required" autocorrect="off" name="TERM_1" placeholder="Search Catalogue" type="search" value=""/>
</fieldset>
</form>

Below is the js code
$(document).bind('pageinit',function() {
$('#search').unbind('submit');
        $('#search').submit(function(event) {
        $.mobile.loading( 'show', { text: "loading", textonly: true, textVisible : true });
        input = $('[name="TERM_1"]').val();
        $.ajax(
        {
            type: "GET",
            async: false,
            url: 'LiberoWebServices.JSONAPI.cls',
            data:
            {
                Method: "Catalogue",
                Type: "simple",
                Split: 10,
                Term: input
            },
            dataType: 'jsonp',
            success: function(data) {
                loadResults(data);
            },
            complete: function(data) {
                $.mobile.loading('hide');
            }
        })
        return false;
        });
    });

The loading popup doesn't seem to show. I'm guessing it has to do with the way i unbind and bind.
The reason i unbinded it was because everytime i submit the form it keeps running the ajax call for all the other pages i have pre-fetched in my DOM.
I'm not sure what's the best way to go about doing this.
Need help figuring out how to get the loading popup to show.
Thanks

A: Use a change in the logic. Instead of this:
 $('#search').unbind('submit');

create a function pointer and reset the binding to run it once, as in these unrelated questions:

*

*jsmart - Can't get template contents (in time?)

*How to Run a Greasemonkey Script only once


text:
Q: Получить первые ячейки таблицы Всем привет. Как с помощью jQuery вытянуть все первые ячейки таблицы и определить ту из них которая содержит определенное значение? Нужно выбрать именно первые.
Спасибо.
A: Например так:
jQuery("table tr").find("td:first").each(function(){
    if (jQuery(this).html() == "<b>первые</b>")
        console.log(this);
})

Есть и другие варианты решения )
< выполнить >


text:
Q: On the rank of the kernel bundle over a complex algebraic surface Let we have the following exact sequence of vector bundles on an  complex smooth projective algebraic surface $X$ in $\mathbb P^3$ given by :
$0 \to E \to \mathcal O_X^{\oplus r} \to  F \to 0$
where,  it's given that $E$ is vector bundle and $F$ is a coherent sheaf on $X$ supported on a codimension $1$ subscheme of $X$.
Then since rank is additive we must have rank$(E) =r-\text{rank}(F)$. But I have come across situation where for $r=2$  it's mentioned that rank$(E) =r$.
Then is it so that $F$ being supported on a codimension $1$ subscheme means that it has always $0$ rank?
Here by rank I mean the complex dimension of the vector space which is obtained as the stalk at the generic point.
Any help from anyone is welcome.


text:
Q: Are shopify apps limited to touch only products and post-sale? I've read through all the API documentation and looked at the shopify app PixelPrinter on github and I'm not seeing anywhere in the doc's where I can have a customer add a custom dollar amount on checkout to go to a specific cause.
Is it possible to add a drop down field to the cart/checkout screen via my app (or instruct them how to add this) and have that selected value end up in the order?  Maybe i'm thinking about this all wrong?

A: If you want to collect money using Shopify, you need to sell Products. A product can have variants and each one has a dollar amount. You cannot sell any product for a random amount of money. You could create a product called Donation, and assign some values to it, allowing a customer to select from some amount of money available as a variant, which you then assign to their favorite cause.


text:
Q: ios accent letters appearing strange I am parsing some JSON in my iOS app and setting some labels with the text. Some of the labels should appear like this:
Beyoncé
However, when shown in the label they appear as:
Beyoncé
The font im using supports accents but I can't seem to figure out how to get it to display properly, even when using NSUTF8StringEncoding.
Any ideas?

A: Does your JSON have an encoding parameter, or can you get it from the response header? I do it like this using a NSHTTPURLResponse:
- (NSString *)decodedStringWithResponse:(NSHTTPURLResponse *)response data:(NSData *)data {
    NSStringEncoding encoding = NSUTF8StringEncoding;
    if (response.textEncodingName) {
        CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)response.textEncodingName);
        if (IANAEncoding != kCFStringEncodingInvalidId) {
            encoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding);
        }
    }

    NSString *decodedString = [[NSString alloc] initWithData:data encoding:encoding];
    if (!decodedString)
        decodedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (!decodedString)
        decodedString = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];
    if (!decodedString)
        decodedString = [[NSString alloc] initWithData:data encoding:NSISOLatin2StringEncoding];

    return decodedString;
}

A: Not sure what you're currently using to parse this but you should give SBJSON a shot. It's super easy to use and here's a tutorial that'll save you lots of trouble probably:
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
SBJSON: https://github.com/stig/json-framework


text:
Q: 404 error encountered when requesting a classic asp page in MVC3 I am converting a classic asp application to ASP.NET MVC3.
I have following route mappings in the global.asax:
routes.MapRoute("LogOn", "Scripts/Logon", New With {.controller = "Account", .action = "Logon"})
routes.MapRoute("LogOnASP", "Scripts/Logon.asp", New With {.controller = "Account", .action = "Logon"})
routes.MapRoute("LogOnASPX", "Scripts/Logon.aspx", New With {.controller = "Account", .action = "Logon"})

Neither logon.asp nor logon.aspX exist in the folder "Scripts".  But only logon.asp renders the 404 error. It seems that IIS checks if the logon.asp exists and reports 404 if no such a file.
How do I configure the IIS settings to allow an asp url to pass through?
I feel confused that my localhost IIS (Windows 7 64-bits), IIS 7.5) doesn't render any error when I use the Logon.asp in a url.  The error is only rendered in the demo server (IIS 7.5 on Windows 2008 R2 server).


text:
Q: Locking an instance variable in Objective-C What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it? Should the use of @synchronized(self) directive be enough?
Thanks in advance

A: If you want that an object is blocked so that no two threads use it at the same time then
@synchronize is one way. But this does not make it thread-safe.
You can also use GCD(Grand Central Dispatch) for the same

A:
What should be the best way in an iOS app to prevent an instance variable from being changed by an object while another is using it?

A good old lock, such as pthread_mutex; you could also use an Objective-C wrapper of this (e.g. NSLock and NSRecursiveLock). @synchronized also falls into this category, but it is the highest level mechanism mentioned here.
Of course, superior concurrent solutions typically have more to do with changes to design, program flow, favoring immutability, and so on. There will still be cases where mutual exclusion/locking is preferred or required.
Unfortunately, pure ObjC/Cocoa are sorely lacking in this domain -- developing a highly efficient concurrent program using ObjC and Cocoa technologies alone is far more difficult than it should be (or needs to be).

Should the use of @synchronized(self) directive be enough?

For simple cases, it is adequate. It is an object level Recursive Lock.
However, it is quite slow, compared to other mutual exclusion options.
I don't think @synchronized has much going for it, apart from:

*

*convenience for the developer to introduce (can have bad side-effects) and

*symmetry (it ensures an unlock matches a lock), greatly reducing the probability of deadlock compared to alternatives (a very good attribute).

@synchronized is convenient, but because it has a high cost, it should be used judiciously.

A: If the only purpose is to be able to access
self.myString; //getter

and,
self.myString=aString; //setter

The best way is to declare it as atomic, for example:
@property (atomic, strong) NSString* myString;

This will ensure that in a multithreaded environment, setting and getting myString by thread 1 is protected from thread 2 doing something to it.


text:
Q: PCIe Present pin working principle I have a doubt about the PCIe present pin working principle, As shown in the below image which is taken from PCI_Express_CEM_r3.0 Specification, How the Hot-plug control logic will detect the PCIe card lane whether it is x1 or x4, or x8 since its shorted together and connected to Hot-plug control logic.

A: The number of lanes (and the maximum speed) is detected by trying to use them.
The PRSNT# signal only indicates that a card is present and sufficiently far inserted on both ends that all the power supply and signal pins are connected.
This avoids powering up a card that is inserted incorrectly, which may damage the card.


text:
Q: Navigation drawer listview position not refreshing I have one NavigationDrawer in my Application and I have five items in my drawer:

*

*Home

*Accounts

*stock

*help

*logout

Now if user click on logout it is displaying two items:

*

*Home

*Login

Now the issue is when user click on login it always getting view of Accounts
 public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private String abc;

    private Intent ii;
    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        prefs.edit().putBoolean("locked", true).commit();

        ii=getIntent();

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // empty the adapter array

        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1), 0));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), 5));

        /*navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));*/

        //  navDrawerItems.remove(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        // What's hot, We  will add a counter here
        //navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

        // Recycle the typed array
        //navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter

        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);

                //boolean isUserLoggedOut = getPrefBoolean("pref_is_user_logged_out",false);

                //Boolean isUserLoggedOut = prefs.getBoolean("locked", false);

/*
                boolean locked = true;
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();*/

                // Check Condition and Update list as required
                /*if(isUserLoggedOut){
                    navDrawerItems.clear();

                    // Home
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),0));                   // Login
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1),5));
                }else{
                    navDrawerItems.clear();

                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),0));
                    // Find People
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1),1));
                    // Photos
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1),2));
                    // Communities, Will add a counter here
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1),3));
                    // Pages
                    navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1),4));

                }

                adapter.notifyDataSetChanged();
*/
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item

            // Get the item that was selected
            NavDrawerItem item = navDrawerItems.get(position);
            // display view for selected nav drawer item
            displayView(item.thingToDo);

            if(position == 4) { // position of Sign out button

                navDrawerItems.clear(); // empty the adapter array

                navMenuIcons.recycle();

                navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),0));
                navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1),5));

                //navDrawerItems.remove(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));

                adapter.notifyDataSetChanged();

            }
            else {
                if (ii.hasExtra("login")) {
                    abc = ii.getStringExtra("login");

                    if (abc == ii.getStringExtra("login")) {
                        navDrawerItems.clear();

                        navMenuIcons.recycle();

                        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),0));
                        // Find People
                        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1),1));
                        // Photos
                        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1),2));
                        // Communities, Will add a counter here
                        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1),3));
                        // Pages
                        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1),4));

                    //  navDrawerItems.remove(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

                        adapter.notifyDataSetChanged();
                        Toast.makeText(MainActivity.this, "success" + abc, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "unsuccess" + abc, Toast.LENGTH_LONG).show();
                    }
                }

            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new HomeFragment();
                break;

            case 1:
            fragment = new FindPeopleFragment();
                break;
            case 2:
                fragment = new PhotosFragment();
                break;
            case 3:
                fragment = new CommunityFragment();
                break;
            case 4:
                fragment = new LoginActivity();
                break;
            case 5:
                fragment = new LoginActivity();
                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

Adapter
public class NavDrawerListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<NavDrawerItem> navDrawerItems;

    public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
        this.context = context;
        this.navDrawerItems = navDrawerItems;
    }

    @Override
    public int getCount() {
        return navDrawerItems.size();
    }

    @Override
    public Object getItem(int position) {
        return navDrawerItems.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);
        }

        ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
        TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
        TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

        imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
        txtTitle.setText(navDrawerItems.get(position).getTitle());

        // displaying count
        // check whether it set visible or not
        if(navDrawerItems.get(position).getCounterVisibility()){
            txtCount.setText(navDrawerItems.get(position).getCount());
        }else{
            // hide the counter view
            txtCount.setVisibility(View.GONE);
        }

        return convertView;
    }

}

Login_Activity
public class LoginActivity extends Fragment{

    public LoginActivity(){}

    private Button alreadymember;
    private Button checkout;
    private Button forgotpass;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.login_activity, container, false);

        alreadymember=(Button)rootView.findViewById(R.id.btn_login_alredymember);
        forgotpass=(Button)rootView.findViewById(R.id.login_forgot_pwd);
        checkout=(Button)rootView.findViewById(R.id.checkout_login);

        alreadymember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               Intent intent=new Intent(getActivity(),MainActivity.class);
                intent.putExtra("login","login");
                startActivity(intent);
               /* HomeFragment tf = new HomeFragment();
                android.support.v4.app.FragmentManager fm = getFragmentManager();
                android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
                Bundle bundle = new Bundle();
                bundle.putString("login", "login");
                tf.setArguments(bundle);
                ft.replace(R.id.frame_container, tf);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();*/
            }
        });

        forgotpass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Forgot_Password tf = new Forgot_Password();
                android.support.v4.app.FragmentManager fm = getFragmentManager();
                android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.frame_container, tf);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        checkout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckoutBeforeLogin tf = new CheckoutBeforeLogin();
                android.support.v4.app.FragmentManager fm = getFragmentManager();
                android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.frame_container, tf);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();
            }
        });
        return rootView;
    }
}

A: You can do it in onDrawerOpened method like this.
  mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
    R.drawable.ic_drawer, //nav menu toggle icon
    R.string.app_name, // nav drawer open - description for accessibility
    R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);

            // get value from preference, whether user is logged in or not
            boolean isUserLoggedOut = getPrefBoolean("pref_is_user_logged_out",false);

            // Check Condition and Update list as required
            if(isUserLoggedOut){
                  navDrawerItems.clear();

                  // Home
                  navDrawerItems.add(new NavDrawerItem("Home", navMenuIcons.getResourceId(HOME_ICON_ID, -1)));
                 // Login
                 navDrawerItems.add(new NavDrawerItem("Login", navMenuIcons.getResourceId(LOGIN_ICON_ID, -1)));
            }else{
                  navDrawerItems.clear();

                  navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
                  // Find People
                  navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
                  // Photos
                  navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
                  // Communities, Will add a counter here
                  navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
                  // Pages
                  navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));

            }

            adapter.notifyDataSetChanged();

            invalidateOptionsMenu();
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

A: You are always calling displayView() with the selected index position in the list of NavDrawerItems. In the case where the user is logged out, there are only 2 items in the list. When the user chooses "login", the index position is 1, not 5.
You probably want to add one more variable to NavDrawerItem which represents which Fragment to show when the user selects that item. You could use either an int value which is then passed to displayView(), or your could use the class name of the Fragment to show.
EDIT: Add example code
In NavDrawerItem, you should have something like:
String title;
Icon icon;

add the following:
int thingToDo;

Then, in the constructor of NavDrawerItem, add an int parameter to the constructor to initialize the field, like this:
public NavDrawerItem(String title, Icon icon, int thingToDo) {
    this.title = title;
    this.icon = icon;
    this.thingToDo = thingToDo;
}

change all your calls that create new NavDrawerItem instances to include the "thing to do", like this:
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1), 0));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), 5));

Then, in SlideMenuClickListener.onItemClick() method, do this:
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
    // Get the item that was selected
    NavDrawerItem item = navDrawerItems.get(position);
    // display view for selected nav drawer item
    displayView(item.thingToDo);
}

A: The code is very confusing to follow. So I'll submit suggested sample code and at best it will be a workaround.
In method displayView(), it displays the Fragment based on position, obviously. When the app is in Login state, you only have 2 positions, Home and Login, as you stated. But displayView() will show the FindPeopleFragment when user selects Login, which is position = 1. Understand? This part of the code design is confusing, the code changes the positions dynamically on run-time while displayView() is static when checking for the position. Now, there are many solutions to this, I would suggest a minor code redesign such that the app checks for item strings instead of position.
However since that would be more involved, I can give you simple workaround fix.
Code fix:
// Get the item that was selected
NavDrawerItem item = navDrawerItems.get(position);

if(position == 4) { // position of Sign out button
   displayView( 4 );   // show the Login fragment
   ...
}
else {
   displayView(item.thingToDo);
   ...
}

Note:

*

*I added the workaround fix of displayView( 4 );

*David Wasser put a good posted answer for you to understand. His post is useful and compliments my post well. I don't want to repeat his texts.

I need to move on with other questions. Good luck in your project...

A: If you detect login situation, you can set adapter of drawer
If you are login change the navDrawerItems and set adapter.
adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);

    mDrawerList.setAdapter(adapter);


text:
Q: How to use Bootstrap 3 Modal in Angular 4 Application? I tried every possible solution given here and I still have this error. I'm using Bootstrap 3 and Angular 4. It happens when I try to show a modal using this:
$("#myModal").modal('show');

A: It sounds like you haven't added the Bootstrap Javascript files to your Angular project in the correct way. What you should do is to add the files to your .angular-cli.json file.
"styles": [
  "styles.css",
  "../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/bootstrap/dist/js/bootstrap.min.js"
],

You can read more about it here.
Bonus Tips
Instead of mixing jQuery with Angular, I recommend you to install a library such as ngx-bootstrap that have rewritten the Bootstrap components as Angular components instead, it makes it way easier to work with together with the rest of your Angular code.
Resources:

*

*ngx-bootstrap Github page

*Blog Post of how to use Bootstrap with an Angular CLI Project.

A: Take a look @ this link. It has a working example and a question for the same with typings and without it. I have used bootstrap and jquery with Angular in that project, you can check the repo too.
In your case you need to add the jquery files
like this in your angular-cli.json
  "styles": [
    "../node_modules/bootstrap-v4-dev/dist/css/bootstrap.min.css",
    "styles.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/tether/dist/js/tether.min.js",
    "../node_modules/bootstrap-v4-dev/dist/js/bootstrap.min.js"

and then declare in component.declare var $: any;
This should work.
UPDATE
I went on to create a modal of bootstrap using just jquery in Angular using the steps i mentioned.
It works Check this gh page link - LINK.
and if you want to check the source code for the same check LINK.
The answer i posted came from this link this is my page on Angular LINK


text:
Q: Adding The Role Attributes of the Default User in PostgresQL I have a PostgreSQL setup with the default user, postgres, for a project. Now, I need to work on another project. For some reason, the DB schema specifies an owner, user2. To work on it, I created the user with a command:
create user user2 with password pw2;

The command
\du

yields "role name", "list of roles Attributes", and "Member of" in a table format. And the default user "postgres" has Superuser, Create role, Create DB, Replication, and Bypass RLS  as role attributes. How to add those attributes to the user2?
Update:
I have found out to use the command "alter role" to add those attributes. With the change, I am able to run the following command to generate a DB schema:
./psql -U user2 mydb < schema.sql

That, however, doesn't resolve an issue I have in regarding the owner of sequence, "sequence must be same owner s table it is linked to" for a script,
... owned by mydb.a_table.uid

. That would be another post.


text:
Q: Is it a good idea to close a class-level database connection on a page/control's Unload event? In my page codebehind, I have a class-level, lazy-loaded connection property that instantiates and opens when it is referenced.  I never close the connection after it is used.  Instead, I close it during the page's unload event.  This eliminates the extra code needed to close it off every time I am done with it.  So far, it appears to work, but I am interested in hearing about any possible negative implications of doing it this way.
Here's what it looks like:
Dim _DbConnection As MyConnection
Private ReadOnly Property DbConnection As MyConnection
    Get
        If _DbConnection Is Nothing Then _DbConnection = GetNewConnection()
        Return _DbConnection
    End Get
End Property

Private Sub Page_Unload(sender As Object, e As System.EventArgs) Handles Me.Unload
    CloseConnection(DbConnectionConnection)
End Sub

Edit: I appreciate the answers advising it is a bad idea, but what are the negative implications of doing it the way I am?  If it's not a good idea, there has to be a legitimate reason as to why.

A: "I never close the connection after it is used" this is horrible idea.  you can use Using blocks to ensure proper dispoing of resoruces.
this what i suggest.
 using (SqlConnection conn = new SqlConnection(strconString))
   {
     // do some logic
    }

A: I agree with Ravi that this is a bad idea. A better practice is to always close your db connection as soon as you finish each query, and you should use connection pooling to improve performance.
http://msdn.microsoft.com/en-us/library/8xx3tyca%28v=vs.100%29.aspx
I think it is a bad idea because it makes for less obvious code, which can lead to bugs later. If another developer takes a look at the code, it will not be obvious to him how the connection is being closed, and as a result he may make modifications that introduce bugs. You want your code to be readable and obvious. Using page life cycle tricks to save a couple milliseconds is just going to lead to problems down the road.

A: See this.
As quoted from there:

In controls, use this event to do final cleanup for specific controls,
  such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as
  closing open files and database connections, or finishing up logging
  or other request-specific tasks.

My recommendation would be to avoid the unload event. When possible do any cleanup code sooner rather than later, so use "using" if you can. In a way, it's like the choice between using a "global" variable as opposed to a local variable, the latter is preferable
Or alternative (using System.Data.CommandBehavior.CloseConnection)
string sConnString = "Server=localhost;Database=Northwind;Integrated Security=True";
string sSql = "SELECT CategoryID, CategoryName FROM Categories ORDER BY CategoryName";
SqlConnection cn = new SqlConnection(sConnString);
SqlCommand cmd = new SqlCommand(sSql, cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
rdr.Read();
//execute
rdr.Close();//closing reader closing connection


text:
Q: Python If statement not printing anything I'm new to this site and this is my very first post. Can usually find answers by just typing in what I needed, but for this I don't know how to word the question. Trying to fix it still, have been for about an hour now, but don't know what's wrong.
My code is below, and when I run it all it does it print out the functions I have (npc and story) and the correct print statements for those, and then stops at the bottom where I have an infinite while loop doing nothing, and it seems to not even notice that the if statement (with the print "STORYSTORYSTORY") is there.
Here's my code:
while True:
    print "\n You wake up in a small room, the lights are dim and the only thing you can see is a table with a few gold pieces and a glass of water."
    input1 = raw_input ("What do you do?").lower()
    if input1 == "take gold":
        print "\n You take the gold and it's added to your inventory"
        time.sleep(3)
        npc("jenkins_gold")
        story("part1")
        loop == 2
        break
    if input1 == "drink water":
        print "\n You reach for the water, and gulp it down."
        time.sleep(3)
        npc("jenkins_water")
        story("part1")
        loop == 2
        break

if loop == 2:
    print "\n Story"
    print "\n STORYSTORYSTORY"

while True:
    y = 1
    x = y
    time.sleep(1)

I have the whole game running in a loop. There's the while loop at the bottom, just in case that has anything to do with it. If you need anything else from my code please let me know, I should respond within minutes. Thank you

A: In your first while statement: loop == 2 evaluates to True (it's a boolean expression, because you used ==) and does nothing else, you want to affect loop with 2, so you need to do loop = 2 (it will be an assignment, because you will use =).
while True:
    print "\n You wake up in a small room, the lights are dim and the only thing you can see is a table with a few gold pieces and a glass of water."
    input1 = raw_input ("What do you do?").lower()
    if input1 == "take gold":
        print "\n You take the gold and it's added to your inventory"
        time.sleep(3)
        npc("jenkins_gold")
        story("part1")
        loop = 2
        break
    if input1 == "drink water":
        print "\n You reach for the water, and gulp it down."
        time.sleep(3)
        npc("jenkins_water")
        story("part1")
        loop = 2
        break

A: You're trying to assign 2 to loop via the equality operator ==. Instead, assign it with the assignment operator = like this:
loop = 2


text:
Q: Implementing membership provider using ASP.NET MVC 4 and Entity Framework When we create a new ASP.NET MVC 4 project in Visual Studio 2012, we get option of "Internet application" which implements membership provider.
Is there anything available by which I will use Entity Framework instead of normal ADO.NET while creating new project so that connection to database will be using Entity Framework & not using ADO.NET.


text:
Q: How to update an appended value? Guys I have an input text and when I start typing, it counts how many letters I am using. But when I clear the input value, I can't change letter counter. How can I get it?
Thanks in advance.
Jsfiddle

function count_letter() {
  var len = $("#area").val().length;
  $('#counter').append(len);
}

$('#area').bind('keyup', function() {
  $('#counter').html('');
  count_letter();
});

$('#clear-value').click(function(){
  $("#area").val(" ");
});

<input type="text" id="area">

<button id="clear-value">
Clear value
</button>

A: In the #clear-value event handler, add:
$('#counter').empty();

Which will clear the #counter element.

  function count_letter() {
    var len = $("#area").val().length;
    $('#counter').append(len);
  }

  $(function() {
    $('#area').bind('keyup', function() {
      $('#counter').html('');
      count_letter();
    });

    $('#clear-value').click(function(){
      $("#area").val("");
      $('#counter').empty(); //<<<-----
    });
  });

<input type="text" id="area">

<button id="clear-value">
Clear value
</button>

A: Just call your count_letter function when you clear the input value :
$('#clear-value').click(function(){
    $("#area").val(" ");
    $('#counter').html('');
    count_letter();
});

A: Cleear your counter on click of clear value button.
See below in action:
https://jsfiddle.net/28bs18gq/2/
function count_letter() {
    var len = $("#area").val().length;
    $('#counter').append(len);
    }

  $('#area').bind('keyup', function() {
    $('#counter').html('');
    count_letter();
  });

  $('#clear-value').click(function(){
  $("#area").val(" ");
    $('#counter').html('');
  });


text:
Q: How can I disable a button if an image has not been edited? I want to try to disable a post button until an image has been chosen by the user.
However, I have a default image set as a placeholder.I have already managed to disable the post button when a textfield has not filled with information. I haven't, however, found a way to disable the button immediately.Hopefully I have explained myself.
Here's an image of my uiview
func handleBlancInformation(){
    address.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
    breed.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
    phone.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)

}

@objc func textFieldDidChange() {
    guard let address = address.text, !address.isEmpty,
            let breed = breed.text, !breed.isEmpty,
            let phone = phone.text, !phone.isEmpty,
            let image = imagePosted.image, !imagePosted.isEqual("placeholder.png")
        else {
        postButton.setTitleColor(UIColor.lightText, for: UIControlState.normal)
            postButton.isEnabled = false
            return
    }
    postButton.setTitleColor(UIColor.white, for: UIControlState.normal)
    postButton.isEnabled = true
}

A: Try This. Use bool for status to check weather image is selected or not.
var isImageSelected = false

override func viewDidLoad() {
    postButton.isEnabled = false
}
Check Image is Selected or not. Change Button Enable property while selected image.
if isImageSelected{
// Do Your Work
}

A: From what I understand the user can click when the View is loaded and you want to prevent this right?

but when they first enter the uiview they can click the post button

If so simply disable the button on the viewDidLoad() or in the storyboard.
override func viewDidLoad() {
    postButton.isEnabled = false
}

or uncheck the "Enabled" field

To verify if an user did pick an image (after the View has loaded) check Greg's answer

A: I would need more code to give an exact solution here, but think about it this way:
Whatever method you are using for the user to choose a new image, that is where you should be enabling the "post" button.
For example, assuming you are using a UIImagePickerViewController to handle picking an image, you will want to enable the "post" button inside of this method, which is part of the UIImagePickerControllerDelegate:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
     if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
          //Enable button here
     } else {
          //Disable button here
     }
}

A: This is how I managed to make the button dissapear from the moment the user enters this tab and show it once both the uiimage and the textfields have been filled out.
 override func viewDidLoad() {

        handleBlancInformation()
        postButton.isHidden = true

    }

func handleBlancInformation(){
            address.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
            breed.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
            phone.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged)
            changeImageLostButton.addTarget(self, action: #selector(PostViewController.textFieldDidChange), for: UIControlEvents.editingChanged )
        }

        @objc func textFieldDidChange() {
            guard let address = address.text, !address.isEmpty,
                    let breed = breed.text, !breed.isEmpty,
                    let phone = phone.text, !phone.isEmpty
                else {
                    postButton.isHidden = true
                    return
            }
            postButton.isHidden = false
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

        {
            print("did Finish Picking Media")
            if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage {
                selectedImage = image
                imagePosted.image = image
            }

            else {

                postButton.isHidden = true

            }
            self.dismiss(animated: true, completion: {

                self.handleBlancInformation()

            })
        }


text:
Q: How can I have a hashmap of form params coming in curl request in my jersey servlet? I am making a curl request like:
curl -i -X POST -d "debit_user_id=/customer/mobile_number:917827448775&recipient_id=/customer/mobile_number:9988776655/recipients/mobile_number:917526337452&pintwin=1234&amount=5000&currency=INR&customer_id=/customer/mobile_number:9988776655&agent_id=/agents/mobile_number:919987536699" http://localhost:8080/switch/apikongcall.do/transactions

And I am getting these parameters in my jersey servlet like:
@POST
//@Path("/transactions")
@Consumes("application/x-www-form-urlencoded")
public void initiatePostTransaction(@FormParam("debit_user_id") String debit_user_id,
        @FormParam("recipient_id") String recipient_id,
        @FormParam("pintwin") String pintwin,
        @FormParam("amount") String amount,
        @FormParam("currency") String currency,
        @FormParam("customer_id") String customer_id,
        @FormParam("agent_id") String agent_id) {

My question is there any way I can create a hashmap for these parameters so I dont need to extract these with their names individually. I jest need the hashmap so even if somebody adds a new parameter later, I don't need to change anything. Is there a way to remove this dependency in jersey.?


text:
Q: Looping a cut and paste if criteria is met I am trying to loop the following
Dim x As Integer
Dim y As Integer

x = Range("AE4")
y = Range("AD4")

If x >= y Then
Range("AE4").Select
Selection.Copy
Range("AD4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Else

End If

Once this cell AE4 has been checked and then copied or not depeding of it is greater or = to AD4 i would like this to then move on to AE5, AE6 etc to the end of the data set. any ideas what i need to do next? I currently have the rest of the script executed before this checking iof the a cell date is below 4 weeks and then 5 weeks, 6 weeks old up to 10 weeks. and is currenlty working as expected checking the date of the cell and then checking and copying the first cell in the data.
Full script is as follows.
Sub Test()

  Range("AE4").Select
    ActiveCell.Formula = _
      "=IF(RC[-2]>=TODAY()-28,""1"",IF(AND(RC[-2]<TODAY()-28,RC[-2]>=TODAY()-35),""4"",IF(AND(RC[-2]<TODAY()-35,RC[-2]>=TODAY()-42),""5"",IF(AND(RC[-2]<TODAY()-42,RC[-2]>=TODAY()-49),""6"",IF(AND(RC[-2]<TODAY()-49,RC[-2]>=TODAY()-56),""7"",IF(AND(RC[-2]<TODAY()-56,RC[-2]>=TODAY()-63),""8"",IF(AND(RC[-2]<TODAY()-63,RC[-2]>=TODAY()-70),""9"",IF(RC[-2]<TODAY()-70,""10""))))))))"
  Range("AE4").Select
  Selection.AutoFill Destination:=Range("AE4:AE200")
  Range("AE4:AE200").Select

  Dim x As Integer
  Dim y As Integer

  x = Range("AE4")
  y = Range("AD4")

  If x >= y Then
  Range("AE4").Select
  Selection.Copy
  Range("AD4").Select
  Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

  Else

  End If
End Sub

A: Below is some code that'll do what I think you're asking. It looks as though you're relying on the macro generator quite heavily which tends to 'select' a lot more than a developer needs to do. Have a play with your code and look at other posts to see how others do it.
Sub Test()
    Dim ws As Worksheet
    Dim startCell as Range
    Dim fullRng As Range
    Dim thisCell As Range
    Dim leftCell as Range

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set startCell = ws.Range("AE4")
    Set fullRng = startCell.Resize(196)

    startCell.Formula = "=IF(RC[-2]>=TODAY()-28,""1"",IF(AND(RC[-2]<TODAY()-28,RC[-2]>=TODAY()-35),""4"",IF(AND(RC[-2]<TODAY()-35,RC[-2]>=TODAY()-42),""5"",IF(AND(RC[-2]<TODAY()-42,RC[-2]>=TODAY()-49),""6"",IF(AND(RC[-2]<TODAY()-49,RC[-2]>=TODAY()-56),""7"",IF(AND(RC[-2]<TODAY()-56,RC[-2]>=TODAY()-63),""8"",IF(AND(RC[-2]<TODAY()-63,RC[-2]>=TODAY()-70),""9"",IF(RC[-2]<TODAY()-70,""10""))))))))"
    startCell.AutoFill fullRng

    For Each thisCell In fullRng.Cells
        Set leftCell = thisCell.Offset(, -1)
        Debug.Print("Before If: " & thisCell.Address(False, False) & "=" & thisCell.Value2 & " v. " & leftCell.Address(False, False) & "=" & leftCell.Value2)
        If thisCell.Value2 >= leftCell.Value2 Then
            leftCell.Value2 = cell.Value2
            Debug.Print("After If: " & thisCell.Address(False, False) & "=" & thisCell.Value2 & " v. " & leftCell.Address(False, False) & "=" & leftCell.Value2)
        End If
    Next

End Sub

A: Easiest way is probably a lopp that just repeats what you are doing.
Instead of defining x and y as ranges, you would only need a count variable:
dim lastrow as integer
lastrow = Cells(Rows.count, "AE").End(xlUp).row 'counts the amount of cells you have with values in the row

for i = 2 to lastrow 'set 2 = whatever, but I guess you have header rows, if you want to start in the 4th row set it 4

if CELLS(i,31).Value >= CELLS(i,30).Value THEN 'the cell commands uses 1-indexed numbers to refer to cells on an x-y axis, rows go on the x axis so Cells(2,1) is "B1" for some reason.
    'insert your loop here
    Cells(i,31).Select
    Selection.Copy
    Cells(i,30).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
       :=False, Transpose:=False
End if
Next i


text:
Q: What is limitToList="true" equivalent attribute in primefaces? I know that attribute limitToList="true" in richfaces 3.5 or limitRender="true" in richfaces 4.x allows to dismiss the behavior of the "ajaxRendered" attribute.
Now I'm looking for the equivalent attribute in primefaces 3.5 to dismiss the behaviour of autoUpdate="true", because I don't want to update my p:outputPanel with autoUpdate="true" on every ajax call.
Any help is highly appreciated.
Thanks in advance guys.

A: Just answering my question with a thought that it may help others.
In primefaces 4.X there is an attribute ignoreAutoUpdate which is equivalent of limitToList or limitRender in richfaces. This attribute is available on various components like p:ajax, p:commandButton p:commandLink and p:poll and p:remoteCommand.

A: There's none.
You can however do it from the other side on. Just make autoUpdate itself conditional. Basically:
autoUpdate="#{evaluate true only if you actually need auto update}"

You could check for request parameters, pressed buttons or bean properties here the usual way.