text:
Q: How to connect to Azure Cosmos DB from Service Fabric Mesh I'm trying to create an application that connects to a Cosmos DB and runs on Service Fabric Mesh. I've created a simple console application that tries to make the connection
var client = new Microsoft.Azure.Documents.Client.DocumentClient(new Uri(***), ***);

client.OpenAsync().Wait();

This causes an error "No such host is known"
The CosmosDB URL is HTTPS, so I tried adding code to make HTTP and HTTPS calls to a website, which gave me a similar error.
Question
Is there some config I need to allow my code external access to specific ports outside of the cluster?
I can create a connection to a SQL Server database.
At the minute I'm just trying to debug the code locally. I can connect if I run the code away from the cluster in a standalone console application.
Thanks

A: This is a known bug - open Dockerfile and add EXPOSE 80 to the first section, i.e.

FROM ...
WORKDIR ...
EXPOSE 80

then networking starts working.


text:
Q: An object of ApiController for each request ASP.NET Will a new object of API Controller creating after each request to the page?
So I need to know if condition #1 is always true or not?
public class ProductsController : ApiController {
    private int _reqState = -1;

    public object Get(int id) {
        if (_reqState == -1}  {} //condition #1
        //DO SOME WORK WITH _reqState
    }
}

A: Yes, a controller has a short lifetime, just for this request. After that it is disposed and your value is lost.
If you want to keep some state, you have to use Session, Application or an external storage to save your state.
For example:
private int ReqState
{
    get
    {
        return (this.HttpContext.Session["ReqState"] as int?).GetValueOrDefault(-1);
    }
    set
    {
        this.HttpContext.Session["ReqState"] = value;
    }
}

A: Assuming that the value of _reqState is not changed between the invocation of your Action method (Get()) and then conditional check, or in your controller constructor - then yes the condition is always true.
public class ProductsController : ApiController {

    public ProductsController()
    {
        // As long as _reqState is not changed here
    }

    private int _reqState = -1;

    public object Get(int id) {

        // ... or here

        if (_reqState == -1}  {} //condition #1 - always true
        //DO SOME WORK WITH _reqState
    }
}

The value set for _reqState is not carried across multiple requests as the controller is created and destroyed with each request.
So the value of _reqState is not the same instance of the variable each time, it's a newly set -1 value.

redpajama_set_name: RedPajamaStackExchange


text:
Q: why is function of division not returning the correctly? I have written some code below that is meant to print our how many times some integer n can be divided by a divisor:
for example if n = 100, divisor = 2   output = 6.  (as 100 can be divided by 2, 6 times)
def divisions(n, divisor):
    division_counter = 0
    n2 = n // divisor
    if n2 != 1:
        division_counter += 1
        n2 = divisions(n2,divisor)

    else:
        return division_counter

    return n2

The question I have is with the last line of code- what should I be returning?- is it correct to return n2? My thought behind this is that this will execute after every if statement, and so by the way I have defined n2, this will cause a recursion of the function divisions().
And the recursion will break, and thus 'else' statement will print when n2 == 1, which will always happen eventually.

A: You are resetting the counter to 0 every time you go into the function. Instead, pass the counter along to each successive call. I've also fixed the off-by-one error below (if n2:) as the test case was producing 5 rather than 6.
def divisions(n, divisor, counter=0):
    n2 = n // divisor
    if n2:
        counter += 1
        n2 = divisions(n2, divisor, counter)
    else:
        return counter
    return n2

>>> divisions(100, 2)
6

A: You can go with recursion @Tigerhawk or you can go with iteration method as per my logic,

*

*Just iteration with condition up to dividend become 0 by this operation n //= divisor.

*And finally return number of iteration takes place

Check out this code
Method-1:
def divisions(n, divisor):
    for i in range(n):
        n //= divisor
        if not n :
            return i

print(divisions(100, 2))

Method-2:
def divisions(n, divisor):
    number = 0
    condn = True
    while condn:
        n //= divisor
        if n:
            number +=1
        else:
            return number

print(divisions(100, 2))

If a number is very large you can go with this method:
Method-3
from math import log
n = 100
k = int(log(n, 2))

print(k)

A: First step to set the result for boundary condition which to end the recursion.
for example:
if n < divisor:
    return 0

If not, final result should one more times than result of divisions for new_n is n//divisor
So full code
def divisions(n, divisor):
    if n < divisor:
        return 0
    return 1 + divisions(n//divisor, divisor)

print(divisions(100, 2))    # 6 for 100, 50, 25, 12, 6, 3
print(divisions(100, 3))    # 4 for 100, 33, 11, 3

A: Recursion is a functional heritage and so we should avoid things like mutation, variable reassignment, and other side effects. We can rewrite this using mathematical induction -

*

*if n is smaller than the divisor, no more divisions are possible. return the counter

*(inductive) n is greater than or equal to the divisor, so at least one division is possible. return the result of the sub-problem (n // divisor, divisor, counter + 1)
def divisions(n, divisor, counter = 0):
  if n < divisor:
    return counter                                        # 1
  else:
    return divisions(n // divisor, divisor, counter + 1)  # 2

A simple variation removes the unnecessary counter variable -

*

*if n is smaller than the divisor, zero divisions are possible. return 0

*(inductive) n is greater than or equal to the divisor, so at least one division is possible. return 1 + the result of the sub-problem (n // divisor, divisor)
def divisions(n, divisor):
  if n < divisor:
    return 0                                     # 1
  else:
    return 1 + divisions(n // divisor, divisor)  # 2

A: Another approach would be using math.log:
import math
def divisions(n, divisor):
    return math.floor(math.log(n,divisor))


text:
Q: LinkedList Wrong Display(string builder) The following program is a basic linked list divided in 3 classes.
In the tester class (main) i add several numbers to the list (sorted).
But insteed of getting the numbers as a  result i get the result: LinkedList.LinkedList
Is something wrong with the stringbuilder (the program was first in java where a string buffer was used, but that should be the same i think?)
LinkedListTester.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinkedList
{
public class LinkedListTester
{
    static void Main(string[] args)
    {
        LinkedList ll = new LinkedList();
        ll.addDataSorted(5);
        ll.addDataSorted(7);
        ll.addDataSorted(13);
        ll.addDataSorted(1);
        ll.addDataSorted(17);
        ll.addDataSorted(8);
        Console.WriteLine(ll);
    }
}

}/*LinkedList*/

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

namespace LinkedList
{
public class LinkedList
{
    //toestand
    private LinkedListNode first;
    private LinkedListNode last;

    //gedrag
    public LinkedList()
    {
        first = null;
        last = null;
    }

    public void addDataInFront(int data)
    {
        first = new LinkedListNode(data, first);
        if (last == null){
            last = first;
        }
    }/*addDataInFront*/

    public void addDataToBack(int data)
    {
        if (first == null)
        {
            addDataInFront(data);
        }
        else
        {
            last.setNext(new LinkedListNode(data, null));
            last = last.getNext();
        }
    }/*addDataToBack*/

    public void addDataSorted(int data)
    {
        if (first == null || first.getData() > data)
        {
            addDataInFront(data);
        }
        else
        {
            LinkedListNode currentNode = first;
            while (currentNode.getNext() != null && currentNode.getNext().getData() < data)
            {
                currentNode = currentNode.getNext();
            }

            currentNode.setNext(new LinkedListNode(data, currentNode.getNext()));
            currentNode = currentNode.getNext();

            if (currentNode.getNext() == null)
            {
                last = currentNode;
            }
        }
    }/*addDataSorted*/

    public String toString()
    {
        StringBuilder Buf = new StringBuilder();
        LinkedListNode currentNode = first;
        while (currentNode != null)
        {
            Buf.Append(currentNode.getData());
            Buf.Append(' ');
            currentNode = currentNode.getNext();
        }
        return Buf.ToString();
    }/*toString*/

}/*LinkedList*/

}/*LinkedList*/

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

namespace LinkedList
{
public class LinkedListNode
{
    //toestand
    private int data;
    private LinkedListNode next;
    private LinkedListNode previous;

    //gedrag
    public LinkedListNode(int data, LinkedListNode next)
    {
        this.data = data;
        this.next = next;
        this.previous = null;
    }

    public LinkedListNode(int data, LinkedListNode next, LinkedListNode previous)
    {
        this.data = data;
        this.next = next;
        this.previous = previous;
    }

    public LinkedListNode getNext()
    {
        return next;
    }

    public LinkedListNode getPrevious()
    {
        return previous;
    }

    public void setNext(LinkedListNode next)
    {
        this.next = next;
    }

    public void setPrevious(LinkedListNode previous)
    {
        this.previous = previous;
    }

    public int getData()
    {
        return data;
    }

}/*LinkedListNode*/
}/*LinkedList*/

A: public **override** String **ToString**()
{
    StringBuilder Buf = new StringBuilder();
    LinkedListNode currentNode = first;
    while (currentNode != null)
    {
        Buf.Append(currentNode.getData());
        Buf.Append(' ');
        currentNode = currentNode.getNext();
    }
    return Buf.ToString();
}/*toString*/


text:
Q: Correct solution for dynamics problem (F=ma)? Any help appreciated with this problem.
A train consists of a railway engine of mass $M$ tonne coupled to two trucks, each of mass $m$ tonne. Initially the train is at rest and each coupling is slack to the extent of $a$ meters.  A constant force $P$ tonne wt is then applied to the engine to drive the train forwards.  Neglecting frictional resistance, find the time that elapses before the second truck starts to move.  $\bigg[Ans : \sqrt{\dfrac{2a(2M + m)}{Pg}} \bigg]$.
My attempt.
Using Newton's 2nd Law of motion ($F = ma$) and $s = ut + \frac{1}{2} at^2$ I found the time when the first couple becomes taut.   $t_1 = \sqrt{\dfrac{2aM}{Pg}}$.
Using the the same logic I found the time taken for the second couple to become taut.  In this case the mass is $(M + m)$.  This gives  $t_2 = \sqrt{\dfrac{2a(M +m)}{Pg}}$.
So I just added $t_1 + t_2 = \sqrt{\dfrac{2aM}{Pg}} + \sqrt{\dfrac{2a(M +m)}{Pg}}$.
Which obviously isn't the answer given.
Thanks in advance.

A: I'll call the constant force $F$. The time until the first coupling is taut is; as you say
$$
t_1=\sqrt{\frac{2aM}{F}}
$$
The velocity of the engine at $t_1$ is $v_1=\frac{F}{M}t_1$.
At $t=t_1$, suppose the engine and first truck have a momentum conserving collision, and they move at the same velocity $V$ just after the collision. Then
$$
p_\text{initial}=Mv_1:=p_\text{final}=(M+m)V\\
\therefore V=\frac{M}{M+m}v_1=\frac{\sqrt{2aMF}}{M+m}
$$
After the collision, we have a new initial value problem $F=(M+m)\ddot{x}$. I'll define a new $t=0$, $x=0$ here, so the initial conditions are $x(0)=0$, $\dot{x}(0)=V$. The solution is
$$
x(t)=Vt+\frac{Ft^2}{2(M+m)}
$$
The second truck will move when $x(t_2)=a$. Solving the quadratic equation for $t_2$ (picking the positive root, and simplifying) yields
$$
t_2=-\sqrt{\frac{2aM}{F}}+\sqrt{\frac{2a(2M+m)}{F}}
$$
The total time is $t_1+t_2=\sqrt{\frac{2a(2M+m)}{F}}$


text:
Q: How can I generalize this getVisibleElement function? I'm using the selenium javascript webdriver, and I'd like to make a general 'getVisibleElement' function. I saw this version in the webdriver source code:
  var link = driver.findElement(firstVisibleLink);

  function firstVisibleLink(driver) {
    var links = driver.findElements(By.tagName('a'));
    return webdriver.promise.filter(links, function(link) {
      return links.isDisplayed();
    }).then(function(visibleLinks) {
      return visibleLinks[0];
    });
  }

Is there a way that I can generalize this such that I can pass in any css selector as parameter and get just the first visible version of it? I've been having issues with 'invalid locator' and 'undefined is not a function' errors the ways i have been trying.
Page:
var webdriverUtils = require('../../utils/extendWebdriver_utils');
    function contactCardPage(){
        var elements = Object.create({}, {
            viewToggle: { get: function(){
                return webdriverUtils.getFirstVisibleElement('[name="viewToggle"]');
            }
        }

        this.toggleView = function(){
            return elements.viewToggle.click();
        }
    });
module.exports = new contactCardPage();

WebdriverUtils:
function webdriverUtils(){
    this.getFirstVisibleElement = function(selectorString){
        var elements = session.driver.findElements(webdriver.By.css(selectorString));

        return webdriver.promise.filter(elements, function(el) {
            return el.isDisplayed();
        }).then(function(visibleElement) {
                return visibleElement[0];
        });
    }
});
module.exports = new webdriverUtils();

Spec:
var expect = require('chai').expect;
var contactCardPage = require('../../pageObjects/contactCardPage.js');
describe('Contacts', function () {
    it('Can be expanded', function(done){
        contactCardPage.toggleView().then(function(){
            //Expect here for making sure expanded elements are now displayed
            done();
        });
    });
});

Currently this gives me an 'Invalid Locator' error.
Is there any way to pass in a selector and get just the visible elements this way?


text:
Q: Does PDO care if query with place holders uses an non-associated array? I had a query in my application that looked like this:
$stmt = db::db()->prepare('INSERT INTO t(a,b) VALUES :a,:b)');
$stmt->execute(array(1,2));

Later, I had an unrelated error, and when reviewing this script, I asked myself why it ever worked previously.  I would have expected I should have used
$stmt->execute(array('a'=>1,'b'=>2));

But, it seems to work?
Is it acceptable to use an non-associated array with a prepared statement where the placeholders are array keys and not question marks?
Not that I will get into this practice, but this had me stumped and I just need to know.
Thank you

A: Yes PDO does care, In this scenario prepare would not fail because the client sends a partial query to the database server,
 this query has to be completely minus the data so it can be pre-processed.
 The client then sends the data, either once or multiple times, the server then executes the pre-processed query with the data.
Howerver the following exception should have been raised when executing:
{ "HY093",  "Invalid parameter number" }

If you read the source code of PDO for the execute function you will see the following piece of code that throws this error:
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_P(input_params),
            &param.name, &str_length, &num_index, 0, NULL)) {
    /* yes this is correct.  we don't want to count the null byte.  ask wez */
    param.namelen = str_length - 1;
    param.paramno = -1;
} else {
    /* we're okay to be zero based here */
    if (num_index < 0) {
        pdo_raise_impl_error(stmt->dbh, stmt, "HY093", NULL TSRMLS_CC);
        RETURN_FALSE;
    }
    param.paramno = num_index;
}

I am not sure how it worked for you so I would make sure PDO errormode attribute is set.
You still have to be careful because you must take care of proper order of the elements in the array that we are passing to the PDOStatement::execute() method.
execute() full function from source code
/* {{{ proto bool PDOStatement::execute([array $bound_input_params])
   Execute a prepared statement, optionally binding parameters */
static PHP_METHOD(PDOStatement, execute)
{
    zval *input_params = NULL;
    int ret = 1;
    PHP_STMT_GET_OBJ;

    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &input_params)) {
        RETURN_FALSE;
    }

    PDO_STMT_CLEAR_ERR();

    if (input_params) {
        struct pdo_bound_param_data param;
        zval **tmp;
        uint str_length;
        ulong num_index;

        if (stmt->bound_params) {
            zend_hash_destroy(stmt->bound_params);
            FREE_HASHTABLE(stmt->bound_params);
            stmt->bound_params = NULL;
        }

        zend_hash_internal_pointer_reset(Z_ARRVAL_P(input_params));
        while (SUCCESS == zend_hash_get_current_data(Z_ARRVAL_P(input_params), (void*)&tmp)) {
            memset(&param, 0, sizeof(param));

            if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_P(input_params),
                        &param.name, &str_length, &num_index, 0, NULL)) {
                /* yes this is correct.  we don't want to count the null byte.  ask wez */
                param.namelen = str_length - 1;
                param.paramno = -1;
            } else {
                /* we're okay to be zero based here */
                if (num_index < 0) {
                    pdo_raise_impl_error(stmt->dbh, stmt, "HY093", NULL TSRMLS_CC);
                    RETURN_FALSE;
                }
                param.paramno = num_index;
            }

            param.param_type = PDO_PARAM_STR;
            MAKE_STD_ZVAL(param.parameter);
            MAKE_COPY_ZVAL(tmp, param.parameter);

            if (!really_register_bound_param(&param, stmt, 1 TSRMLS_CC)) {
                if (param.parameter) {
                    zval_ptr_dtor(&param.parameter);
                }
                RETURN_FALSE;
            }

            zend_hash_move_forward(Z_ARRVAL_P(input_params));
        }
    }

    if (PDO_PLACEHOLDER_NONE == stmt->supports_placeholders) {
        /* handle the emulated parameter binding,
         * stmt->active_query_string holds the query with binds expanded and
         * quoted.
         */

        ret = pdo_parse_params(stmt, stmt->query_string, stmt->query_stringlen,
            &stmt->active_query_string, &stmt->active_query_stringlen TSRMLS_CC);

        if (ret == 0) {
            /* no changes were made */
            stmt->active_query_string = stmt->query_string;
            stmt->active_query_stringlen = stmt->query_stringlen;
            ret = 1;
        } else if (ret == -1) {
            /* something broke */
            PDO_HANDLE_STMT_ERR();
            RETURN_FALSE;
        }
    } else if (!dispatch_param_event(stmt, PDO_PARAM_EVT_EXEC_PRE TSRMLS_CC)) {
        PDO_HANDLE_STMT_ERR();
        RETURN_FALSE;
    }
    if (stmt->methods->executer(stmt TSRMLS_CC)) {
        if (stmt->active_query_string && stmt->active_query_string != stmt->query_string) {
            efree(stmt->active_query_string);
        }
        stmt->active_query_string = NULL;
        if (!stmt->executed) {
            /* this is the first execute */

            if (stmt->dbh->alloc_own_columns && !stmt->columns) {
                /* for "big boy" drivers, we need to allocate memory to fetch
                 * the results into, so lets do that now */
                ret = pdo_stmt_describe_columns(stmt TSRMLS_CC);
            }

            stmt->executed = 1;
        }

        if (ret && !dispatch_param_event(stmt, PDO_PARAM_EVT_EXEC_POST TSRMLS_CC)) {
            RETURN_FALSE;
        }

        RETURN_BOOL(ret);
    }
    if (stmt->active_query_string && stmt->active_query_string != stmt->query_string) {
        efree(stmt->active_query_string);
    }
    stmt->active_query_string = NULL;
    PDO_HANDLE_STMT_ERR();
    RETURN_FALSE;
}
/* }}} */


text:
Q: Поиск кода функции хука WooCommerce Если ленивый - читай сразу последний абзац!
Файл content-product.php, строка do_action( 'woocommerce_after_shop_loop_item' ); выводит кнопку "В корзину", при нажатии товар добавляется в корзину, пользователь остается на странице магазина.
Нужно заменить эту кнопку на кнопку "Посмотреть" (на сайте функционал корзины не используется, сайт не интернет-магазин, а интернет-каталог оффлайн-магазина) так, чтобы при нажатии пользователя отправляло на страницу товара , под которым эта кнопка находится(как при нажатии на изображение товара).
Чтобы вы понимали о чем речь: ссылка на сам сайт, не обессудьте ;-)
Я думал что do_action( 'woocommerce_after_shop_loop_item' ); возвращает echo "...html..." и попытался найти функцию которая этот код генерирует, но я не понимаю как искать функцию которая вызывается с помощью хука. Помогите мне с поиском пожалуйста)

A: Решил с помощью get_permalink()! Спасибо обидевшемуся на меня комментатору.

A: Как искать функцию которая вызывается с помощью хука - это хороший вопрос. Такие действия приходится выполнять по несколько раз на дню.
Понятно, что искать можно только по файлам исходных текстов. То есть, как минимум, должна быть полная локальная копия сайта. Учитывая, что WordPress - это примерно полмиллиона строк, а WooCommerce - 300 тысяч строк, поиск по подпапкам стандартными средствами (например, Total Commander) - это очень долго. Нужно индексирование.
Современные IDE (например, phpStorm) индексируют исходные тексты проекта, и поиск по всему проекту осуществляется практически мгновенно, по мере ввода символов в строке поиска.
В вашем случае: вызываем окно глобального поиска в phpStorm (ctrl+shift+f), вводим 'woocommerce_after_shop_loop_item'. Моментально получаем все упоминания в проекте:

Видим, что в самом WooCommerce есть файл wp-content/plugins/woocommerce/includes/wc-template-hooks.php, в котором присутствует строка (подсвечена на картинке)
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );

Кликаем на строку, открывается файл. Подводим указатель мыши к woocommerce_template_loop_add_to_cart, удерживая ctrl.

Видим, что IDE вывела краткое описание функции woocommerce_template_loop_add_to_cart и её параметров. Кликаем на woocommerce_template_loop_add_to_cart, удерживая ctrl.
И IDE открывает тот участок исходного текста, где объявлена woocommerce_template_loop_add_to_cart, причём неважно, в каком файле эта находится.

Таким образом, процесс поиска занимает 5 секунд, которые в основном уходят на чтение первой выдачи по ctrl+shift+f.


text:
Q: CRUD operation using jooq in spring boot + postman @RestController
public class BookController {

    @Autowired
    BookService bookService;

    @PostMapping("/saveBook")
    public void postBook(@RequestBody Book book) {

        this.bookService.insertBook(book);
    }

     @GetMapping("/allBooks")
     public Result<Record> getBooks(){
            return this.bookService.getBooks();
        }
}

I am trying to perform a crud operation using jooq+postgresql in spring boot, calling APIs from the postman. But it is not working. Please share some link and your ideas.
I am sending the JSON object from postman but is not convert in the book object.


text:
Q: create a column based on one other Python I would like to create a column called "target" which contains 0 value if name columns is "NaN" and 1 if it is non.
I did, like this:
df_opportunity['target'] = np.where(df_opportunity['name']=='NaN', '0', '1')

But it puts always 0
Any ideas?

A: I always found tricky the way to compare NaN in pandas. The appropriate would be:
df_opportunity['target'] = np.where(pd.isnull(df_opportunity['name']), '0', '1')


text:
Q: Netplan in Ubuntu Server 18.04. How to restart network fully? Ubuntu 18.04 LTS use netplan and systemd-networkd as default network config tool.
In earlier release, we can use service networking restart, or just ifdown & ifup to fully restart the network or an interface.
In 18.04, netplan tells just change the yaml file and use netplan apply .
When I change a bonding interface, just like hash policy, mtu, the netplan apply command doesn't make the new configuration effective.
Oh by the way, netplan shows render is networkd.
I search the whole internet to find a way to restart the network, but failed.
What I can do is reboot the server. This will make the new mtu and hash policy effective.
But just changing a network parameter, why i must reboot the whole server! Even a unstable windows server is not like this!
So, anyone can tell me what should I do?
List of methods I've already tried and failed:

*

*systemctl restart systemd-networkd : restarted but mtu and policy not change

A: For bond interfaces there is a problem. Currently after I modify the Netplan file, I do a Netplan apply for the Netplan to modify the systemd files. Then do a systemd restart for the changes to take effect. This has its own pitfalls.
In case the server has a nfs mounted, systemd never comes up and the network stack hangs. So we need to unmount the nfs, and restart the systemd networkd again.

A: netplan apply does the job.
In some cases you have to reboot.


text:
Q: pandas.dataframe.pop for all names in a array I'm trying to remove a list of columns from a pandas.DataFrame. I've created a list through
diff = df1.difference(df2)

I would like to do something like:
for name in diff:
    dataframe.pop(name)

Is there a way to apply the pop function in a vectorized way with all names in the diff index array?
Thanks all for the help!
Regards,
Jan

A: as MaxU said, cleanest way to do it is
dataframe.drop(diff, axis=1)

the .pop() method returns the series you are poping, which is not time effective if you only want to delete the column
also, you coulduse the del method which maps to the python magic method df.__delitem__('column'). I would not recommend that.
you can read this great SO answer to learn more about those


text:
Q: django - Query the list of objects and their objects field I want to check the MessageState of all the Message in each Threads (i.e. order_threads_message), and if any of the Threads has all the messages hidden then make that Thread as hidden too (/ or else remove it from order_threads_message). I want to do that in the view before passing it to the template. How do I do that? If you didn't get me, please ask. I will be happy to explain. Please help me how to do this in the views. I will be grateful. Thank you.
models.py:
class Thread(models.Model):
    subject = models.CharField(max_length=50, blank=True, null=True)
    user = models.ManyToManyField(User)

class ThreadState(models.Model):
    thread = models.ForeignKey(Thread)
    user = models.ForeignKey(User)
    thread_hidden = models.BooleanField(default=False)

class Message(models.Model):
    thread = models.ForeignKey(Thread)
    sender = models.ForeignKey(User)
    sent_date = models.DateTimeField(default=datetime.now)
    body = models.TextField()

class MessageState(models.Model):
    message = models.ForeignKey(Message)
    user = models.ForeignKey(User)
    read = models.BooleanField(default=False)
    message_hidden = models.BooleanField(default=False)

views.py
@login_required
def message(request):
    user = request.user
    threads = user.thread_set.all()
    order_threads_message = threads.annotate(max_sent_date=Max('message__sent_date')).order_by('-max_sent_date')
    if order_threads_message.count() > 0:
        recent_thread = order_threads_message[0]
        if recent_thread.message_set.all().count() > 0:
            recent_thread_conversations = recent_thread.message_set.all()
            return render(request, 'conversations.html', {
                'all_threads':order_threads_message,
                'conversations':recent_thread_conversations,
                'active': recent_thread.id
                })
        else:
            recent_thread_conversations = 0
            return render(request, 'conversations.html', {
                'all_threads':order_threads_message,
                'conversations':recent_thread_conversations,
                'active': recent_thread.id
                })
    else:
        order_threads_message = 0
        recent_thread_conversations = 0
        return render(request, 'conversations.html', {
            'all_threads':order_threads_message,
            'conversations':recent_thread_conversations,
            })

A: I have ran this query for the following models:
Models
class Thread(models.Model):
    subject = models.CharField(max_length=50, blank=True, null=True)
    user = models.ManyToManyField(User)

class ThreadState(models.Model):
    thread = models.ForeignKey(Thread)
    user = models.ForeignKey(User)
    thread_hidden = models.BooleanField(default=False)

class Message(models.Model):
    thread = models.ForeignKey(Thread, related_name = 'message_thread')
    sender = models.ForeignKey(User)
    sent_date = models.DateTimeField(default=datetime.now)
    body = models.TextField()

class MessageState(models.Model):
    message = models.ForeignKey(Message, related_name='messagestate_message')
    user = models.ForeignKey(User)
    read = models.BooleanField(default=False)
    message_hidden = models.BooleanField(default=False)

Query
Thread.objects.filter(message_thread__in = Message.objects.filter(messagestate_message__in=MessageState.objects.filter(message_hidden=False)))

This query will return the Thread objects if atleast one of its MessageState's message_hidden is False.


text:
Q: Mysql, escaped string fields couldn't be searched with "LIKE" keyword Consider one of the field( sample_field ) in Mysql table has as "your\'s data", when I query the same table as
SELECT * FROM sample_table WHERE sample_field = "your\'s data"
and also like as
SELECT * FROM sample_table WHERE sample_field = "your's data"
both of the above query returns 0 rows, even though the sample_field has the value as "your\'s data"
After a long search I came to know that, my search would be
SELECT * FROM sample_table WHERE sample_field = "your\\\'s data"
that is working very fine. but
SELECT * FROM sample_table WHERE sample_field LIKE "your\\\'s data"
is not working. So if I want to search any product or categories with quotes( like "your's data" ), in site search I must use LIKE keyword with wildcard patterns('%').
Now I have found the answer that if I try like this
SELECT * FROM sample_table WHERE sample_field LIKE "your\\\\'s data"
as given in http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like, it is working fine.
But please let me know why it needs this amount of 4 back slashes to achieve this ?
Thanks in advance

A: You'll have to escape the escaping backslash, if you want it to be a literal backslash:
WHERE sample_field = "your\\'s data"

But really, having a backslash in your database in the first place is the mistake, fix that instead.

A: Because MySQL uses C escape syntax in strings (for example, "\n" to represent a newline character), you must double any "\" that you use in LIKE strings. For example, to search for "\n", specify it as "\n". To search for "\", specify it as "\\"; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.

A: Try it like this:
... WHERE sample_field = 'your\'s data'


text:
Q: Having Problem with ipython notebook on ubuntu 14.04 I have installed ipython notebook in my system, but when I want to run it in terminal, the following error comes up:
  File "/usr/local/lib/python2.7/dist-packages/ipython-3.2.0-py2.7.egg/IPython/html/notebookapp.py", line 52, in <module>
    from tornado import httpserver
  File "/usr/local/lib/python2.7/dist-packages/tornado/httpserver.py", line 34, in <module>
    from tornado.http1connection import HTTP1ServerConnection, HTTP1ConnectionParameters
  File "/usr/local/lib/python2.7/dist-packages/tornado/http1connection.py", line 30, in <module>
    from tornado import iostream
  File "/usr/local/lib/python2.7/dist-packages/tornado/iostream.py", line 40, in <module>
    from tornado.netutil import ssl_wrap_socket, ssl_match_hostname, SSLCertificateError, _client_ssl_defaults, _server_ssl_defaults
  File "/usr/local/lib/python2.7/dist-packages/tornado/netutil.py", line 39, in <module>
    import certifi
ImportError: No module named certifi

Does any one know where the problem is? Any suggestion would be highly appreciated.

A: It looks like you are missing a dependency for IPython Notebook.  If you don't already have pip installed, I would recommend installing it for the ease of installing python packages:
sudo apt-get install python-pip python-dev build-essential
Once pip has been installed, you can install the IPython Notebook and all its dependencies by entering at the command line:
pip install "ipython[notebook]"
You may have to run that one with sudo as well if you get an error.


text:
Q: I can only get one value out of ODReader So I created an ODReader that executes a query where I get certain valeus out of a table.
However when I try to show this data in a mbox(just temporaraly) I can only show the first value.
And as soon as I try to get the second set of values it gives me this error  Object reference not set to an instance of an object.
the code is as follows
     public void betaaldgroep()
     {
        List<int> groepsres = new List<int>();
        OracleParameter[] Betaald = new OracleParameter[10];//moet flexibel worden gemaakt

        OracleDataReader ODReader = DBConnection.Select("SELECT GROEPRESERVERING_ID,BETAALD FROM         GROEPRESERVERING ", Betaald);
        ODReader.Read();
        for (int x = 0; x < 2; x++)
        {
            MessageBox.Show(ODReader["GROEPRESERVERING_ID"].ToString());
            MessageBox.Show(ODReader["BETAALD"].ToString());
            ODReader.NextResult();

        }

    }

Now my qeuistion is how can I show every set of valeus instead of just the first one?

A: ODReader.NextResult(); would return you the next "result set" from your query. You have just a single SELECT statement in your query so you will end up with one result set. Since there is no second result set, when you try to access ODReader["GROEPRESERVERING_ID"].ToString() you get a null reference exception.
What you should look for is to get the next row from your result set. Use
ODReader.Read(); to iterate to the next result set. If you want to only restrict yourself to reading two rows from the result set use:
OracleDataReader ODReader = DBConnection.Select("SELECT GROEPRESERVERING_ID,BETAALD FROM         GROEPRESERVERING ", Betaald);
int counter = 0;
while (ODReader.Read() && counter < 2)
{
    MessageBox.Show(ODReader["GROEPRESERVERING_ID"].ToString());
    MessageBox.Show(ODReader["BETAALD"].ToString());
    counter++;
}


text:
Q: PHP: Warning: sort() expects parameter 1 to be array, resource given I wanted to arrange the array of table list with sort() function but i am getting same kind of warning.
<?php
require_once("lib/connection.php");

$result = mysql_query("SHOW TABLES FROM `st_db_1`");

sort($result);
foreach ($result as $result){
    echo $result ;
}
?>

and the warning I am getting are:

Warning: sort() expects parameter 1 to be array, resource given in C:\wamp\www\Copy (4)       of st_db_1\test_2.php on line 9
Warning: Invalid argument supplied for foreach() in C:\wamp\www\Copy (4) of st_db_1\test_2.php on line 10

A: The warning is pretty clear: mysql_query does not return an array with results from the query, but a resource. You need a function like mysql_fetch_array() to return the data you need (and on which you can perform a sort operation).
See the manual for the use of mysql_query() http://nl3.php.net/mysql_query
And maybe unrelated, but you can sort your results in MySQL right away by adding ORDER BY <fieldname> to your query.

A: I'm not providing the most efficient code imaginable, but this should make it clear what's going on and solve your problem:
 $result = mysql_query("SHOW TABLES FROM `st_db_1`");

 $my_array_of_table_names = array();
 while ( $row = mysql_fetch_array($result, MYSQL_NUM)) {
     $my_array_of_table_names[] = $row[0];
 }
 sort($my_array_of_table_names);

 foreach ($my_array_of_table_names as $table_name){
     echo "$table_name\n";
 }

A: The variable $result is only a resource of the type result. You need to fetch then the data from the result set with e.g. mysql_fetch_assoc().
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
$array = array();
while ($row = mysql_fetch_assoc($result)) {
    $array[] = $row["Tables_in_st_db_1"];
}
sort($array);
foreach ($array as $item) {
   echo $item;
}

A: Your problem is that you aren't actually getting the data from the query.
mysql_query() doesn't give you a recordset.
What it does is query the database and returns a database resource which you can then use to get the data.
What you need is after calling mysql_query(), you then need to also call mysql_fetch_array() or similar. (there are a range of functions available, but that's probably the best one to use in this case). Then sort() the data from that, not $result.

A: It clearly says: it expects an array and you pass something else.
If you had checked the type of $result you would have seen that it is not an array, intead a resource.


text:
Q: error with global name when running a script from another script - python Let's say I have two scripts:
test_fun1.py
a = 1

def test1():
    print a
    execfile('test_fun2.py')

test1()

test_fun2.py
b = 2

def print_a():
    print 'a'

def test2():
    print_a()
    print b

test2()

When I run test_fun1.py I get this error:
NameError: global name 'print_a' is not defined

If I exclude the print_a() within test2() both a and b are printed. Why would variables be set to global but functions wouldn't?

A: This is a pretty interesting problem.  First a quick workaround, you can provide dictionaries to use as the local and global namespace when calling execfile(), using an empty dictionary for globals works fine:
# test_fun1.py
a = 1

def test1():
    print a
    execfile('test_fun2.py', {})

test1()

Alternatively, if you want the code to execute within the global scope of your module you can use globals() instead of {}.
Now on to why this isn't working... from the documentation on execfile():

If both dictionaries are omitted, the expression is executed in the environment where execfile() is called.

Here "both dictionaries" is referring to the optional globals and locals arguments to execfile().  In this case "the environment where execfile() is called" is the local scope of the function test1() in test_fun1.py.  Now it is reasonable to still expect this to work, because it seems like it should be doing something essentially equivalent to the following:
a = 1

def test1():
    print a
    # code executed by execfile
    b = 2

    def print_a():
        print 'a'

    def test2():
        print_a()
        print b

    test2()

test1()

However there is a note later on in the docs:

Note: The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function's locals.

So there you have it, there is an explicit warning here that execfile() cannot be used to reliably modify a function's locals, and that is exactly what this code is attempting to do.  The b = 2 and def print_a(): ... statements are executed within the scope of test1(), but they are not actually succeeding in adding those names to the namespace so attempting to access those names later on fails.


text:
Q: laravel-echo-server not listening all notification I want to make real time notification in my app. I am using Laravel Broadcast Notification, Laravel Echo and Laravel Echo Server.in my app in local notification listen for all user but in server if notification added for 5 users then listen for 2 to 3 users and else users log save in laravel.log file.
CODE
// controller file
$users = User::whereHas('dealerRoles', function ($query) {
                $query->where('name', DealerRole::DEALERSHIP_DIRECTOR);
                $query->orWhere('name', DealerRole::DEALERSHIP_PRINCIPAL);
                $query->orWhere('name', DealerRole::DEALERSHIP_MANAGER);
            })->whereHas('dealerships', function ($query) use ($listing) {
                $query->where('dealerships.id', $listing->owner_id);
            })->get();

            \Notification::send($users, (new ListingApproved($listing)));

// notification file(ListingApproved.php)
class ListingApproved extends Notification implements ShouldQueue{
use Queueable;

private $listing;

/**
 * Create a new notification instance.
 *
 * @return void
 */
public function __construct(Listing $listing)
{
    $this->listing = $listing;
}

/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return ['database', 'broadcast'];
}

public function toArray($notifiable)
{
    return [
        'listing_id' => $this->listing->id,
        'message' => 'Your Listing has been approved Successfully.'
    ];
}

}
// laravel-echo-server.json
{
"authHost": ["http://dealers.cc/", "http://admin.videocarsales.cc/"],
"authEndpoint": "/broadcasting/auth",
"clients": [
    {
        "appId": "31071dab508dc1bb",
        "key": "8262eb7c6589432f457ad25b83d4cb5a"
    }
],
"database": "redis",
"databaseConfig": {
    "redis": {},
    "sqlite": {
        "databasePath": "/database/laravel-echo-server.sqlite"
    }
},
"devMode": true,
"host": null,
"port": "7878",
"protocol": "http",
"socketio": {},
"sslCertPath": "",
"sslKeyPath": "",
"sslCertChainPath": "",
"sslPassphrase": "",
"apiOriginAllow": {
    "allowCors": true,
    "allowOrigin": "http://localhost:80",
    "allowMethods": "GET, POST",
    "allowHeaders": "Origin, Content-Type, X-Auth-Token, X-Requested-With, Accept, Authorization, X-CSRF-TOKEN, X-Socket-Id"
}

}
// front end for listen notification
Echo.private('App.Domain.User.User.' + '{{ auth()->user()->id }}')
            .notification((notification) => {
                console.log('yes');
                Messenger().post({
                    message: 'Your Listing las been approved Successfully.',
                    type: 'success',
                    showCloseButton: true
                });
            });

//laravel.log
[2018-06-13 08:13:09] production.INFO: Broadcasting [Illuminate\Notifications\Events\BroadcastNotificationCreated] on channels [private-App.Domain.User.User.49] with payload:
{
"listing_id": 1,
"message": "Your Listing has been approved Successfully.",
"id": "acb1f428-0116-43a4-88cd-53e35089084a",
"type": "App\\Notifications\\ListingApproved",
"socket": null}

please help me.
Thanks in advance!


text:
Q: Reproduction in R of the Linear trends models of Stata 17 recently Stata has introduced an interesting feature for the Difference-in-Difference Analysis which introduces a linear trend model to compare the Parallel trend assumptions prior to an intervention established in the command "estat trendplots"  (See more here https://sciexperts.com/difference-in-differences-did-and-ddd-models/ and here https://www.stata.com/manuals/tedidregresspostestimation.pdf)
I am mostly interested in this graphic

Since it shows an interesting representation of the trends (if they're linear) of the control and treatment groups. But I can't figure out how to carry out such a model in R, my intuition states that a single linear model having as a year in the dependent variable would be enough for each group, then average it and plot it. But when I do it I face some errors.
Here's a Data that I generated to work with it.
library(data.table)
library("fixest")

## Panel Data DiD for trends models

df <- data.table(ID=rep(1:1000, each=10),
                 year = rep(2001:2010,1000),
                 y = rnorm(10000),
                 treatment=rep(c(1,0), each=5000))

# Define the treatment intervention in 2005
df[treatment == 1 & year== 2005, y := y + 0.3]
df[treatment == 1 & year== 2006, y := y - 0.1]

# Event Study
df[, distance := year -2005]

eventstudy <- feols(y ~ i(as.factor(distance), treatment, -1) | ID + year, data = df)
iplot(eventstudy)

# means by group

df[treatment==1 , y_mean := mean(y), by=year]
df[treatment==0 , y_mean := mean(y), by=year]

# graph
ggplot(df, aes(x=year, y=y_mean)) +
  geom_line(aes(x=year, y=y_mean, group=treatment, color=treatment))

I'm not interested in the tests followed in Stata as the example I do of the Event Study DiD is enough in the pre-trends hypothesis testing, but I would like to enhance my analysis (as some reviewers asked me this plot) using the linear-trends model.
With regards,
John


text:
Q: Text next to Image vs. stacked on mobile I'm having trouble with making the text and image be responsive on mobile.
This is what I have
HTML:

Lorem Ipsum dolor sit amet consectetur
Sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem commodi.

And CSS:
<link href="https://fonts.googleapis.com/css?family=Lato:300" rel="stylesheet">

I want these images to show on top of their text on mobile

Can someone please help me, please?

A: i have an answer, you can use float values for this kind of approach and make float none in mobile resolution using media query , it would be same as you like to view image on top and them text for mobile resolution. Kindly check the example.
Code

.break {
  clear:both;
  display:block;
}
.right{
  float:right;
  width: 50%;
  height: 200px;
}
.left{
  float:left;
  width: 50%;
  height: 200px;
}
@media (max-width:767px){ .left, .right { float:none;}}

testtesttesttesttesttesttesttest

testtesttesttesttesttesttesttest

A: Here is the solution i have used in my website for similar situation  If you use flex-box display for content alignment and wrapping then you can add CSS order property to specify the order of elements in alignment i have modified the previous answer code with that property have a look
 Drop a comment if you dont understand any line...

.content{
  width: 50%;
  float:left;
  height: 200px;
}
@media (max-width:760px){
   .second{ order:1;}
  .first{ order:2;}
  .content{
    width: 90%;
    float: none;
  }
}

testtesttesttesttesttesttesttest

testtesttesttesttest

 Here is the codepen link you can view and edit that to clarify my procedure https://codepen.io/anon/pen/RZqEoy?editors=1100  Pardon me by any chance codepen doesnt work
As you said you are beginner then go through the flex box display properties you can make you website wire-frame alignment perfectly as you want with flex box display. Thank You...


text:
Q: How to change the the style of a vector layer programmatically? I want to change the style of the polygon contained in the vector layer.
Is there any API available?
(I can click the properties of the shapefile, then select the style and change the symbol properties, but I want to do this programmatically.)
I am using Python to customise QGIS.

A: The documentation can be found here: http://www.qgis.org/pyqgis-cookbook/vector.html#appearance-symbology-of-vector-layers
I haven't tried it yet, so I cannot provide any further pointers but the code examples there look good to go.


text:
Q: Sockets won't work in network I am working on an application that sends files via the network.
I used 2 classes to send and to receive the file that I selected.
The problem that I have faced, when I am working on localhost, is that the process goes correctly, but when I change the IP address to the network IP, it does not work.
Here is the two classes that I am using.
Class Server :
    package Test;

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class Server{
 public static void main (String [] args ) throws IOException {
// create socket
ServerSocket servsock = new ServerSocket(41111);
while (true) {
  System.out.println("Waiting...");

  Socket sock = servsock.accept();
  System.out.println("Accepted connection : " + sock);

  // sendfile
  File myFile = new File ("C:\\Users\\Marrah.Zakaria\\Desktop\\test\\test.txt");
  byte [] mybytearray  = new byte [(int)myFile.length()];
  FileInputStream fis = new FileInputStream(myFile);
  BufferedInputStream bis = new BufferedInputStream(fis);
  bis.read(mybytearray,0,mybytearray.length);
  OutputStream os = sock.getOutputStream();
  System.out.println("Sending...");
  os.write(mybytearray,0,mybytearray.length);
  os.flush();
  sock.close();
  }
}
}

Class Client:
 package Test;

 import java.io.BufferedOutputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.Socket;

 public class Client{
 public static void main (String [] args ) throws IOException {
 int filesize=6022386; // filesize temporary hardcoded

 long start = System.currentTimeMillis();
 int bytesRead;
 int current = 0;

Socket sock = new Socket("192.168.1.100",41111);
System.out.println("Connecting...");

 // receive file
 byte [] mybytearray  = new byte [filesize];
 InputStream is = sock.getInputStream();
 FileOutputStream fos = new FileOutputStream("C:\\Test\\test-copy.txt");
 BufferedOutputStream bos = new BufferedOutputStream(fos);
 bytesRead = is.read(mybytearray,0,mybytearray.length);
 current = bytesRead;

do {
   bytesRead =
      is.read(mybytearray, current, (mybytearray.length-current));
   if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
sock.close();
sock.getPort();
}
}

after running an exception shows up :
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at            java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)

Please would you tell me what shall i do to get rid of it.

I dis-activated the receivers firewall a different exception occurred :
 Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)

A: If you start up the server, can you telnet to this combination ?
telnet 192.168.1.100 41111

That'll tell you immediately if you have a routing issue (telnet will refuse to connect)

A: Have you check if there is any firewall blocking the custom port (41111) on your network (also check Windows firewall)?
This is the first thing to check when you have a timeout.

A: also try to ping 192.168.1.100 from the machine where you are running the client (i.e from the command prompt if you are in windows box)


text:
Q: My modal window is not transferring values to vb.net codebehind I am getting the username and password to run some scripts
  <act:ModalPopupExtender ID="unixLoginMPE" runat="server" TargetControlID="rdoUnix"
        PopupControlID="unixPanel" BackgroundCssClass="modalBackground" CancelControlID="unixCancel" OkControlID="unixSubmit"
          />
    <asp:Panel ID="unixPanel" runat="server"
        CssClass="modalPopup" align="center" Style="display: none">Unix Username: <asp:TextBox ID="unixName" ClientIDMode="Static" runat="server"  />

        Unix Password: <asp:TextBox ID="unixPass" runat="server" ClientIDMode="Static" TextMode="Password"  />

        <asp:Button ID="unixCancel" runat="server" Text="Cancel" />
        <asp:Button ID="unixSubmit" ClientIDMode="Static" runat="server" Text="Submit" OnClientClick="enableRDO()"  />
    </asp:Panel>

In my codebehind, I'm doing something like this just to test if the values have passed.
Dim UNIXPASSWORD As String = unixPass.text
                Dim UNIXUSERNAME As String = unixName.Text
                MsgBox(UNIXCOMPUTERNAME)
                MsgBox(UNIXUSERNAME)
                MsgBox(UNIXPASSWORD)

I do reference a script to enable the radio button. I asked a question to help me with that issue, it is all resolved Radio Button won't stay check if I have a modal window open up when it is selected

For some reason the values are passing just fine in Google Chrome but not in IE. I've been at this for a few hours and don't know what else to try...or search for
EDIT:
I'm still trying to attempt this. I setup up dummy text boxes which I will hide later on if I can pass to them. I'm still very lost with this...
<asp:TextBox ID="dummyUnixName" runat="server" />
    <asp:TextBox ID="dummyUnixPass" runat="server" />

A: If you aren't performing a postback or an AJAX call, nothing will be passed to the code behind.
During debugging, Console.WriteLine can be redirected to the output window in VS; in production, it's going to go nowhere. A logging solution is often appropriate for a web application which needs to know more of what happened than which page was requested by a user (IIS logs).


text:
Q: Не удается подключиться к виртуальной машине Azure Есть аккаунт Azure. Есть задача: надо создать виртуальную машину и подключиться к ней. Если первый шаг интуитивен, то со вторым возникает проблема.
Итак, есть стабильно работающая виртуальная машина. В ней прописаны EndPoints. Кнопка "подключение" недоступна, как и подключение при помощи родного виндового "Подключение к удаленному рабочему столу". Было перелопачено множество материалов на MSDN: виртуальная машина перезагружалась, настройки сбрасывались. Ничего не помогает. Подскажите новичку советом, как можно решить это проблему.

A: Подозреваю, что, т.к. виртуальная машина была создана на новом портале, был выбран по умолчанию тип Resource Manager (т.е. не классическая виртуальная машина).
В этом случае, у этой VM отсутвует публичный адрес, его нужно создать дополнительно. В Settings -> Network Interfaces -> IP Addresses -> Public IP Address -> Enabled -> Create New.

После этого иконка удаленного соединения должна стать активной (если мы говорим о Windows VM). В случае с Linux этот адрес следует использовать для подключения по SSH.


text:
Q: Backbone refresh/bookmark page doesn't work I have a webpage that I'm using Backbone to make it into a Single Page App thingy but refreshing a page or following a bookmark doesn't work - the JS says it is undefined etc.
This is a stripped down version for simplicity

this.LeBaron = new function() {
  this.Routing = new function() {
    var Router = Backbone.Router.extend({
      routes: {
        "index": "index",
        "other": "other"
      },

      index: function() {
        view("index", {});
      },
      other: function() {
        view("other", {});
      }
    });

    var view = function(id, model) {
      $("#content").html($("#" + id).html());

    }
    this.router = new Router();
    Backbone.history.start();
  }
}

$(document).ready(function() {

});

<!DOCTYPE html>

  <title>
    Single Page Test
  </title>

    Index

   Other

Index Page!

Other Page!

A: You have new before your constructor

var LeBaron = this.LeBaron = function() {
  this.Routing = function() {
    var Router = Backbone.Router.extend({
      routes: {
        "index": "index",
        "other": "other"
      },

      index: function() {
        view("index", {});
      },

      other: function() {
        view("other", {});
      }
    });

    var view = function(id, model) {
      $("#content").html($("#" + id).html());

    };

    this.router = new Router();

    Backbone.history.start();
  };

  this.Routing();
};

$(document).ready(function() {
  new LeBaron();
});
<!DOCTYPE html>

  <title>
    Single Page Test
  </title>

    Index

   Other

Index Page!

Other Page!


text:
Q: Select a random distinct row I have a table in mysql called drugs with 3 columns (id,illness,drug).
An illness may occur several times in the column but with different drug.
I need a code to select a distinct ilness but it should use a random criteria so that it can display different drug.
Example in mydb...
id | illness | drug
------------------------------
1  |malaria  |panadol
2  |malaria  |hedex
3  |malaria  |tripple action
4  |fever    |panadol

i tried this but it wasn't random in picking the rows for drug. selected only a single drug for malaria all the time.
$quotes="SELECT drug,remedy FROM drugs group by drug";

i need this outputs
 1   | malaria   | panadol or hedex or tripple action **//any but random**
 2   | fever     | panadol **//random drug if i add other rows of fever**

A: Try this
$quotes="SELECT drug,remedy FROM drugs WHERE id = (1+ RAND()*(SELECT MAX(id) FROM drugs)) group by drug";

A: Or in mysql

$select = 'select * from drugs order by rand() limit 1';

That will get the rows at random, and then limit answer just for one of it.
You can add where clause to the query as well.


text:
Q: Plot line from dataframe I have the following dataframe [1] which contains information relating to music listening. I would like to print a line graph like the following 2 (I got it by putting the data manually) in which the slotID and the average bpm are related, without writing the values by hand . Each segment must be one unit long and must match the average bpm.
[1]
        slotID  NUn  NTot     MeanBPM
2        2       3       13  107.987769
9       11       3       30  133.772100
10      12       3       40  122.354025
13      15       4       44  123.221659
14      16       4       30  129.083900
15      17       9       66  123.274409
16      18       4       25  131.323480
18      20       5       40  124.782625
19      21       6       30  127.664467
20      22       6       19  120.483579

The code I used to obtain the plot is the following:
import numpy as np
import pylab as pl
from matplotlib import collections  as mc

lines = [ [(2, 107), (3,107)], [(11,133),(12,133)], [(12,122),(13,122)], ]
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])

lc = mc.LineCollection(lines, colors=c, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)

To obtain data:
import numpy as np
import pandas as pd

dfLunedi = pd.read_csv( "5.sab.csv", encoding = "ISO-8859-1", sep = ';')

dfSlotMean = dfLunedi.groupby('slotID', as_index=False).agg( NSabUn=('date', 'nunique'),NSabTot = ('date', 'count'), MeanBPM=('tempo', 'mean') )

df = pd.DataFrame(dfSlotMean)
df.to_csv('sil.csv', sep = ';', index=False)

df.drop(df[df.NSabUn < 3].index, inplace=True)

A: You can loop through the rows and plot each segment like this:
for _, r in df.iterrows():
    plt.plot([r['slotID'], r['slotID']+1], [r['MeanBPM']]*2)

Output:


text:
Q: $_GET['variable'] into an Array Variable Okay, so I have an array named with three values:
$tutorials = array('introduction', 'get_started', 'basics')

I also have a link for example:
mysite.com/?tutorials=get_started

So the link above appears to be the first value of $tutorials but what if I want my anchor's href to be like the next value?
Next

Are there any shortcuts for this? Because my array is not just only 3 but 20 and I don't want to edit them one by one.
What I'm trying to do here is a Next and Previous links. Please help.
Thank you!

A: Retrieve the index of the current item in your array, and add 1 to get the index of the following tutorial.
Don't forget to check if you already are on the latest item of the array.
<?php

$tutorials = array('introduction', 'get_started', 'basics');

$index = array_search($_GET['tutorials'], $tutorials);

if ($index === FALSE) {
    echo 'Current tutorial not found';
} else if ($index < count($tutorials) - 1) {
    echo 'Next';
} else {
    echo 'You are already on the latest tutorial available';
}

Manual

A: Something like this should work:
<?php

   $value = $_GET['tutorials']; // get the current

   // find it's position in the array
   $key = array_search( $value, $tutorials );

   if( $key !== false ) {
      if( $key > 0 ) // make sure previous doesn't try to search below 0
          $prev_link = '?tutorials=' . $tutorials[$key-1];

      if( $key < count( $tutorials ) ) // Make sure we dont go beyond the end of the array
          $next_link = '?tutorials=' . $tutorials[$key+1];
   } else {
      // Some logic to handle an invalid key (not in the array)
   }

?>

A: Use array_search() to get the key and add / minus one to the key to get the next / previous link:
$key = array_search($_GET['tutorials'], $tutorials);


text:
Q: Unable to get data from Activity to Service I am pretty new to this but I was told I could get good help here. A friend and myself are playing around with creating Android apps (using ADT)
Here is how we are trying to make the program:  in an activity, a user sets threshold values for the X and Y axis on the accelerometer.  When the user hits button "Start", startService is invoked and starts TiltService.
TiltService is designed to run in the background always on the phone without user interaction.  TiltService constantly compares the threshold with the accelerometer values and will vibrate if they are off.
My problem is I can't seem to get the putExtra() data correctly. I have overridden the onStartCommand in my service but I get the message "unreachable code" when I save the getExtras() to a bundle.
Here is the relevant code (I can post the whole thing, just do not want to clog up page)
TiltMeterActivity
private Intent dataIntent = null;
private float FORWARD_THRESHOLD = 4f;
private float BACKWARD_THRESHOLD = -3f;
private float UPWARD_THRESHOLD = 3f;
private float DOWNWARD_THRESHOLD = -3f;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        bstart = (Button)findViewById(R.id.btnStart);

        dataIntent = new Intent();
        dataIntent.setClass(TiltMeterActivity.this, TiltService.class);
        dataIntent.putExtra("fowardThreshold", FORWARD_THRESHOLD);
        dataIntent.putExtra("backwardThreshold", FORWARD_THRESHOLD);
        dataIntent.putExtra("upwardThreshold", UPWARD_THRESHOLD);
        dataIntent.putExtra("downwardThreshold", DOWNWARD_THRESHOLD);

        bStart.setOnclickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startService(dataIntent);
            }
        });
    }

TiltService
private Bundle thresholdData = new Bundle();

private float Z_FORWARD_THRESHOLD = 0f;
private float Z_BACKWARD_THRESHOLD = 0f;
private float Y_UPWARD_THRESHOLD = 0f;
private float Y_DOWNWARD_THRESHOLD = 0f;

public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        return super.onStartCommand(intent, flags, startId);

        thresholdData = intent.getExtras(); // The problem area (Eclipse says this is unreachable code)

        Z_FORWARD_THRESHOLD = thresholdData.getFloat("forwardThreshold");
        Z_BACKWARD_THRESHOLD = thresholdData.getFloat("backwardThreshold");
        Y_UPWARD_THRESHOLD = thresholdData.getFloat("upwardThreshold");
        Y_DOWNWARD_THRESHOLD = thresholdData.getFloat("downwardThreshold");

        return START_STICKY;
    }

I thought I understood the basic of how Intents could pass data, but I guess I don't.  Is it obvious what I am missing?  Thanks for any help

A: put the return statement in your onstartcommand to the last line of the function.

A: I think you should use thresholdData.getString(forwardThreshold) to get the data.


text:
Q: MySQL not working on Ubuntu 11.04 I run the mysql command at the command line but I get this error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
I've Googled a lot but I'm unable to resolve the issue.
Please HELP!

A: It sounds like mysql isn't running. This will tell you if it is or not:
 sudo netstat -tap | grep mysql

A: That's because the path you specified doesnt have the socket required to connnect to the mysql. This problem has happened with me. Either you can reinstall mysql or search for the mysqld.sock and then move it to the specified directory.
Try running this command to start the mysql server
/etc/init.d/mysql start
 /etc/init.d/mysql restart


text:
Q: Как мне подключить созданную БД к сайту Пытаюсь подключить MySQL в консоли Ubuntu (Linux) в файле с сайтом на пхп (домашнее задание, а не рабочий проект).
Выдает ошибку когда захожу на сайт (вбиваю IP в браузер)

Попытка подключения не удалась.

Это похоже он не может подключиться к данным что я ввел, но они корректные, и БД с таким именем создана, в чем может быть проблема?
Снизу часть кода
<?php

  // Database access definition
  $dbname     = "abook";
  $dbserver   = "192.168.56.101";
  $dbuser     = "abook";
  $dbpass     = "asdffdsA1";
  $dbcnx = mysql_connect($dbserver,$dbuser,$dbpass);
if (!$dbcnx)
{
echo "
Попытка подключения не удалась MySQL
";
exit();
}
if (!mysql_select_db($dbname,$dbcnx) )
{
echo "
Выбрать базу данных невозможно
";
exit();
}
$ver = mysql_query("SELECT VERSION()");
if(!$ver)
{
echo "
Запрос неверен
";
exit();
}
echo mysql_result($ver, 0);
  // Define table prefix
  $table_prefix = "ab_";

  // Don't display groups
  $nogroups = false;

  // Disable all "edit/create" actions.
  $read_only  = false;

A: Какая версия PHP? Попробуйте mysqli писать вместо mysql.
Привожу пример рабочего кода:
<?php
    $link=mysqli_connect("HOST", "USER", "PASSWORD", "DBNAME", "DBPORT"); //подключаемся
    $query = mysqli_query($link, "SQL-ЗАПРОС"); //выполняем любой запрос

    //ну и гуглим команды mysqli, к примеру если запрос был SELECT и
    //результат - несколько строк, то получаем их следующим образом:
    $result = [];
    while($row = mysqli_fetch_assoc($query)) { //пробегаемся по каждой строке
        $result[] = $row; //записываем значение в массив
    }

    print_r($result); //тестируем - выводим массив

    //если запрос не выводящий результат, такой как INSERT, то что то вроде
    if (!$query) {
        echo 'Не удалось выполнить запрос';
    } else {
        echo 'Запрос выполнен успешно';
    }
?>

Потом уже, когда всё вышеописанное получится, можно углубляться и делать более грамотно, с выводом ошибок, выводом успешного результата в формате API (например JSON) и так далее. Успехов!

A: 6 возможностей:

*

*Или IP неправильное,

*или MySQL сервер во время вашего тестирования не работал,

*или сервер работает на нестандартном порте (т.е. не на 3306) - тогда нужно его добавить к IP адресу, например $dbserver   = "192.168.56.101:8888";

*или имя неправильное,

*или пароль неправильный,

*или общие проблемы с подключением к компьютеру-серверу (хардвер, TCP/IP софтвер — на пути от вашего компютера к серверу).


text:
Q: Kafka Error serializing Avro message Caused by: java.net.SocketException: Connection reset Im trying out Kafka streams, managed to stream normal string from one topic to another, but now i want to serialize it as AVRO message. Ive looked around the internet for a solution but i didnt find one so this is kinda my last hope. This is my code
    public static void main(String[] args) throws IOException {
        String url = "http://url:9092";
        Properties props = new Properties();
        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "TestAvro222");
        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, url);
        props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        //props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, GenericAvroSerde.class);
        props.put("schema.registry.url", url);

        final Map<String, String> serdeConfig = Collections.singletonMap("schema.registry.url",
                url);
        final Serde<GenericRecord> valueGenericAvroSerde = new GenericAvroSerde();
        valueGenericAvroSerde.configure(serdeConfig, false);
        StreamsBuilder builder = new StreamsBuilder();
        KStream<String, String> textLines = builder.stream
                ("topic1",
                        Consumed.with(stringSerde, stringSerde));
        File file = new File("urltoschema");
        Schema schema = new Schema.Parser().parse(file);
        KTable<String, GenericRecord> textLines_table = textLines.mapValues(value -> avroMaker(schema, value)).toTable();
        //KTable textLines_table = textLines.toTable();
        textLines_table.toStream().to("TEST-AVRO22", Produced.with(Serdes.String(), valueGenericAvroSerde));

        KafkaStreams streams = new KafkaStreams(builder.build(), props);
        streams.start();
    }

When i run it i get the following error:
org.apache.kafka.streams.errors.StreamsException: Error encountered sending record to topic TEST-AVRO22 for task 0_0 due to:
org.apache.kafka.common.errors.SerializationException: Error serializing Avro message
    at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:177)
    at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:139)
    at org.apache.kafka.streams.processor.internals.SinkNode.process(SinkNode.java:85)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forwardInternal(ProcessorContextImpl.java:253)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:232)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:191)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:42)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:146)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forwardInternal(ProcessorContextImpl.java:253)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:232)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:191)
    at org.apache.kafka.streams.kstream.internals.KTableSource$KTableSourceProcessor.process(KTableSource.java:152)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:146)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forwardInternal(ProcessorContextImpl.java:253)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:232)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:191)
    at org.apache.kafka.streams.kstream.internals.KStreamMapValues$KStreamMapProcessor.process(KStreamMapValues.java:42)
    at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:146)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forwardInternal(ProcessorContextImpl.java:253)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:232)
    at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:191)
    at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:84)
    at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$1(StreamTask.java:731)
    at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:809)
    at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:731)
    at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:1296)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:784)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:604)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:576)
Caused by: org.apache.kafka.common.errors.SerializationException: Error serializing Avro message
    at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:101)
    at io.confluent.kafka.serializers.KafkaAvroSerializer.serialize(KafkaAvroSerializer.java:53)
    at io.confluent.kafka.streams.serdes.avro.GenericAvroSerializer.serialize(GenericAvroSerializer.java:63)
    at io.confluent.kafka.streams.serdes.avro.GenericAvroSerializer.serialize(GenericAvroSerializer.java:39)
    at org.apache.kafka.common.serialization.Serializer.serialize(Serializer.java:62)
    at org.apache.kafka.streams.processor.internals.RecordCollectorImpl.send(RecordCollectorImpl.java:157)
    ... 28 common frames omitted
Caused by: java.net.SocketException: Connection reset
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:186)
    at java.base/java.net.SocketInputStream.read(SocketInputStream.java:140)
    at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:252)
    at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:292)
    at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:351)
    at java.base/sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:787)
    at java.base/sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:722)
    at java.base/sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:896)
    at java.base/sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:722)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1615)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:294)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.httpRequest(RestService.java:384)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:561)
    at io.confluent.kafka.schemaregistry.client.rest.RestService.registerSchema(RestService.java:549)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.registerAndGetId(CachedSchemaRegistryClient.java:290)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:397)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:376)
    at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient.java:364)
    at io.confluent.kafka.schemaregistry.client.SchemaRegistryClient.register(SchemaRegistryClient.java:51)
    at io.confluent.kafka.serializers.AbstractKafkaAvroSerializer.serializeImpl(AbstractKafkaAvroSerializer.java:70)
    ... 33 common frames omitted

No idea whats wrong, and ive searched multiple websites to find a solution, to no avail. please help

A: Yea, I figured out my schema registry has a different url than the one i provided in the code, so that fixed it


text:
Q: How can I base my Spring Boot app on an external Servlet? I'm trying to turn this example into a Spring Boot application, the problem lying in that RestfulServer is a servlet, and I"m not really trying to make a separate app, but a single one that, more or less extends that servlet. Problem I seem to be running into though is that things I've tried with WebApplicationInitializer and SpringBootApplicationInitializer is that they are not initializing the servlet before doing other @Configuration classes. How can I convert the JpaServerDemo class to Spring Boot? (note: we don't need the 2nd servlet)
update this is the last thing I tried, however I also tried various iterations of just WebApplicationInitializer, or doing things in the configure method which seems tricky because it has no servletContext, and onStartup has no ApplicationContext
@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    public void onStartup( ServletContext servletContext ) throws ServletException {
        super.onStartup( servletContext );

        RestfulServer server = new RestfulServer();
        servletContext.addServlet( "restful", server );
            /*
         * We want to support FHIR DSTU3 format. This means that the server
         * will use the DSTU3 bundle format and other DSTU3 encoding changes.
         *
         * If you want to use DSTU1 instead, change the following line, and change the 3 occurrences of dstu2 in web.xml to dstu1
         */
        server.setFhirContext( FhirContext.forDstu3() );
        WebApplicationContext myAppCtx = this.createRootApplicationContext( servletContext );

        // Get the spring context from the web container (it's declared in web.xml)

    /*
     * The BaseJavaConfigDstu3.java class is a spring configuration
     * file which is automatically generated as a part of hapi-fhir-jpaserver-base and
     * contains bean definitions for a resource provider for each resource type
     */
        List<IResourceProvider> beans = myAppCtx.getBean( "myResourceProvidersDstu3", List.class );
        server.setResourceProviders( beans );

        /*
         * The system provider implements non-resource-type methods, such as
         * transaction, and global history.
         */
        server.setPlainProviders( myAppCtx.getBean( "mySystemProviderDstu3", JpaSystemProviderDstu3.class ) );

    /*
     * The conformance provider exports the supported resources, search parameters, etc for
     * this server. The JPA version adds resource counts to the exported statement, so it
     * is a nice addition.
     */
        IFhirSystemDao<Bundle, Meta> systemDao = myAppCtx.getBean( "mySystemDaoDstu3", IFhirSystemDao.class );
        DaoConfig daoConfig = myAppCtx.getBean( DaoConfig.class );
        JpaConformanceProviderDstu3 confProvider = new JpaConformanceProviderDstu3( server, systemDao, daoConfig );
        confProvider.setImplementationDescription( "Example Server" );
        server.setServerConformanceProvider( confProvider );

        /*
         * Enable ETag Support (this is already the default)
         */
        server.setETagSupport( ETagSupportEnum.ENABLED );

    /*
     * This server tries to dynamically generate narratives
     */
        FhirContext ctx = server.getFhirContext();
        ctx.setNarrativeGenerator( new

                DefaultThymeleafNarrativeGenerator() );

        /*
         * Default to JSON and pretty printing
         */
        server.setDefaultPrettyPrint( true );
        server.setDefaultResponseEncoding( EncodingEnum.JSON );

        /*
         * -- New in HAPI FHIR 1.5 --
         * This configures the server to page search results to and from
         * the database, instead of only paging them to memory. This may mean
         * a performance hit when performing searches that return lots of results,
         * but makes the server much more scalable.
         */
        server.setPagingProvider( myAppCtx.getBean( DatabaseBackedPagingProvider.class ) );

    /*
     * Load interceptors for the server from Spring (these are defined in FhirServerConfig.java)
     */
        Collection<IServerInterceptor> interceptorBeans = myAppCtx.getBeansOfType( IServerInterceptor.class ).values();
        for (
                IServerInterceptor interceptor : interceptorBeans )

        {
            server.registerInterceptor( interceptor );
        }

        /*
         * If you are hosting this server at a specific DNS name, the server will try to
         * figure out the FHIR base URL based on what the web container tells it, but
         * this doesn't always work. If you are setting links in your search bundles that
         * just refer to "localhost", you might want to use a server address strategy:
         */
        //setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/baseDstu2"));

        /*
         * If you are using DSTU3+, you may want to add a terminology uploader, which allows
         * uploading of external terminologies such as Snomed CT. Note that this uploader
         * does not have any security attached (any anonymous user may use it by default)
         * so it is a potential security vulnerability. Consider using an AuthorizationInterceptor
         * with this feature.
         */
        server.registerProvider( myAppCtx.getBean( TerminologyUploaderProviderDstu3.class ) );

    }

    @Override
    protected SpringApplicationBuilder configure( final SpringApplicationBuilder builder ) {
        return builder;
    }

    public static void main( String[] args ) {
        configureApplication( new SpringApplicationBuilder() ).run( args );
    }

    private static SpringApplicationBuilder configureApplication( final SpringApplicationBuilder builder ) {
        return builder.sources( Application.class );
    }
}

A: This seems to work, I added @WebServlet to the class, and injected the WebApplicationContext using Spring 4.3's annotationless constructor injection feature. I also added @ServletComponentScan to my Application which is in the same package
@WebServlet( "/fhir/*" )
public class FhirServlet extends RestfulServer {

    private static final long serialVersionUID = 3341258540126825379L;
    private final WebApplicationContext myAppCtx;

    public FhirServlet( WebApplicationContext myAppCtx ) {
        this.myAppCtx = myAppCtx;
    }

    @Override
    protected void initialize() throws ServletException {
        this.setFhirContext( FhirContext.forDstu3() );
        this.setServerAddressStrategy( new IncomingRequestAddressStrategy() );
        this.setDefaultPrettyPrint( true );
        this.setDefaultResponseEncoding( EncodingEnum.JSON );
        this.setETagSupport( ETagSupportEnum.ENABLED );

        /*
         * The BaseJavaConfigDstu3.java class is a spring configuration
         * file which is automatically generated as a part of hapi-fhir-jpaserver-base and
         * contains bean definitions for a resource provider for each resource type
         */
        List<IResourceProvider> beans = myAppCtx.getBean( "myResourceProvidersDstu3", List.class );
        setResourceProviders( beans );

        /*
         * The system provider implements non-resource-type methods, such as
         * transaction, and global history.
         */
        setPlainProviders( myAppCtx.getBean( "mySystemProviderDstu3", JpaSystemProviderDstu3.class ) );

        /*
         * The conformance provider exports the supported resources, search parameters, etc for
         * this server. The JPA version adds resource counts to the exported statement, so it
         * is a nice addition.
         */
        IFhirSystemDao<Bundle, Meta> systemDao = myAppCtx.getBean( "mySystemDaoDstu3", IFhirSystemDao.class );
        JpaConformanceProviderDstu3 confProvider = new JpaConformanceProviderDstu3( this, systemDao, myAppCtx.getBean( DaoConfig.class ) );
        confProvider.setImplementationDescription( "Example Server" );
        setServerConformanceProvider( confProvider );

        /*
         * This server tries to dynamically generate narratives
         */
        getFhirContext().setNarrativeGenerator( new DefaultThymeleafNarrativeGenerator() );

        /*
         * -- New in HAPI FHIR 1.5 --
         * This configures the server to page search results to and from
         * the database, instead of only paging them to memory. This may mean
         * a performance hit when performing searches that return lots of results,
         * but makes the server much more scalable.
         */
        setPagingProvider( myAppCtx.getBean( DatabaseBackedPagingProvider.class ) );

        /*
         * Load interceptors for the server from Spring (these are defined in FhirServerConfig.java)
         */
        Collection<IServerInterceptor> interceptorBeans = myAppCtx.getBeansOfType( IServerInterceptor.class ).values();
        for ( IServerInterceptor interceptor : interceptorBeans ) {
            this.registerInterceptor( interceptor );
        }

        /*
         * If you are hosting this server at a specific DNS name, the server will try to
         * figure out the FHIR base URL based on what the web container tells it, but
         * this doesn't always work. If you are setting links in your search bundles that
         * just refer to "localhost", you might want to use a server address strategy:
         */
        //setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/baseDstu2"));

        /*
         * If you are using DSTU3+, you may want to add a terminology uploader, which allows
         * uploading of external terminologies such as Snomed CT. Note that this uploader
         * does not have any security attached (any anonymous user may use it by default)
         * so it is a potential security vulnerability. Consider using an AuthorizationInterceptor
         * with this feature.
         */
        registerProvider( myAppCtx.getBean( TerminologyUploaderProviderDstu3.class ) );
    }
}


text:
Q: Parallel doesnt work with Entity Framework I have a list of IDs, and I need to run several stored procedures on each ID.
When I am using a standard foreach loop, it works OK, but when I have many records, it works pretty slow.
I wanted to convert the code to work with EF, but I am getting an exception:

The underlying provider failed on Open.

I am using this code, inside the Parallel.ForEach:
using (XmlEntities osContext = new XmlEntities())
{
    //The code
}

But it still throws the exception.
Any idea how can I use Parallel with EF? Do I need to create a new context for every procedure I am running? I have around 10 procedures, so I think its very bad to create 10 contexts, one for each.

A: EF is not thread safe, so you cannot use Parallel.
Take a look at Entity Framework and Multi threading
and this article.

A: The underlying database connections that the Entity Framework are using are not thread-safe.  You will need to create a new context for each operation on another thread that you're going to perform.
Your concern about how to parallelize the operation is a valid one; that many contexts are going to be expensive to open and close.
Instead, you might want to invert how your thinking about parallelizing the code.  It seems you're looping over a number of items and then calling the stored procedures in serial for each item.
If you can, create a new Task<TResult> (or Task, if you don't need a result) for each procedure and then in that Task<TResult>, open a single context, loop through all of the items, and then execute the stored procedure.  This way, you only have a number of contexts equal to the number of stored procedures that you are running in parallel.
Let's assume you have a MyDbContext with two stored procedures, DoSomething1 and DoSomething2, both of which take an instance of a class, MyItem.
Implementing the above would look something like:
// You'd probably want to materialize this into an IList<T> to avoid
// warnings about multiple iterations of an IEnumerable<T>.
// You definitely *don't* want this to be an IQueryable<T>
// returned from a context.
IEnumerable<MyItem> items = ...;

// The first stored procedure is called here.
Task t1 = Task.Run(() => {
    // Create the context.
    using (var ctx = new MyDbContext())
    // Cycle through each item.
    foreach (MyItem item in items)
    {
        // Call the first stored procedure.
        // You'd of course, have to do something with item here.
        ctx.DoSomething1(item);
    }
});

// The second stored procedure is called here.
Task t2 = Task.Run(() => {
    // Create the context.
    using (var ctx = new MyDbContext())
    // Cycle through each item.
    foreach (MyItem item in items)
    {
        // Call the first stored procedure.
        // You'd of course, have to do something with item here.
        ctx.DoSomething2(item);
    }
});

// Do something when both of the tasks are done.

If you can't execute the stored procedures in parallel (each one is dependent on being run in a certain order), then you can still parallelize your operations, it's just a little more complex.
You would look at creating custom partitions across your items (using the static Create method on the Partitioner class).  This will give you the means to get IEnumerator<T> implementations (note, this is not IEnumerable<T> so you can't foreach over it).
For each IEnumerator<T> instance you get back, you'd create a new Task<TResult> (if you need a result), and in the Task<TResult> body, you would create the context and then cycle through the items returned by the IEnumerator<T>, calling the stored procedures in order.
That would look like this:
// Get the partitioner.
OrdinalPartitioner<MyItem> partitioner = Partitioner.Create(items);

// Get the partitions.
// You'll have to set the parameter for the number of partitions here.
// See the link for creating custom partitions for more
// creation strategies.
IList<IEnumerator<MyItem>> paritions = partitioner.GetPartitions(
    Environment.ProcessorCount);

// Create a task for each partition.
Task[] tasks = partitions.Select(p => Task.Run(() => {
        // Create the context.
        using (var ctx = new MyDbContext())
        // Remember, the IEnumerator<T> implementation
        // might implement IDisposable.
        using (p)
        // While there are items in p.
        while (p.MoveNext())
        {
            // Get the current item.
            MyItem current = p.Current;

            // Call the stored procedures.  Process the item
            ctx.DoSomething1(current);
            ctx.DoSomething2(current);
        }
    })).
    // ToArray is needed (or something to materialize the list) to
    // avoid deferred execution.
    ToArray();

A: This is what I use and works great. It additionally supports handling of the error exceptions and has a debug mode which makes it far easier to track things down
public static ConcurrentQueue<Exception> Parallel<T>(this IEnumerable<T> items, Action<T> action, int? parallelCount = null, bool debugMode = false)
{
    var exceptions = new ConcurrentQueue<Exception>();
    if (debugMode)
    {
        foreach (var item in items)
        {
            try
            {
                action(item);
            }
            // Store the exception and continue with the loop.
            catch (Exception e)
            {
                exceptions.Enqueue(e);
            }
        }
    }
    else
    {
        var partitions = Partitioner.Create(items).GetPartitions(parallelCount ?? Environment.ProcessorCount).Select(partition => Task.Factory.StartNew(() =>
        {
            while (partition.MoveNext())
            {
                try
                {
                    action(partition.Current);
                }
                // Store the exception and continue with the loop.
                catch (Exception e)
                {
                    exceptions.Enqueue(e);
                }
            }
        }));
        Task.WaitAll(partitions.ToArray());
    }
    return exceptions;
}

You use it like the following where as db is the original DbContext and db.CreateInstance() creates a new instance using the same connection string.
        var batch = db.Set<SomeListToIterate>().ToList();
        var exceptions = batch.Parallel((item) =>
        {
            using (var batchDb = db.CreateInstance())
            {
                var batchTime = batchDb.GetDBTime();
                var someData = batchDb.Set<Permission>().Where(x=>x.ID = item.ID).ToList();
                //do stuff to someData
                item.WasMigrated = true; //note that this record is attached to db not batchDb and will only be saved when db.SaveChanges() is called
                batchDb.SaveChanges();
            }
        });
        if (exceptions.Count > 0)
        {
            logger.Error("ContactRecordMigration : Content: Error processing one or more records", new AggregateException(exceptions));
            throw new AggregateException(exceptions); //optionally throw an exception
        }
        db.SaveChanges(); //save the item modifications

A: Here's something I did to solve my problem.  I was trying to get an order inside my Parallel.ForEach with a unique connection to EF, this is what I tought it was but wasn't really true and I was having the same last order each time.  After removing the using and closing the connection at the end of the operation it was working just fine.
In a nutshell if you utilize a using, don't and close the connection at the end of the operation inside the Parallel.Foreach
I did replace this
using ApplicationDbContext Context = CubiCommon.GetContext<ApplicationDbContext>("APIConnection");

by this
ApplicationDbContext Context = CubiCommon.GetContext<ApplicationDbContext>("APIConnection");

and added this at the end of the operation
Context.Dispose();
Context = null;

Maybe this can solve similar issue


text:
Q: Why does our implementation of the Facebook Like button only post a URL on a user's Facebook profile? We thought we added the proper tags to enable Facebook to display our Likes in plain english, such as:
Bob likes Why We Sold TechCrunch To AOL, And Where We Go From Here on TechCrunch
However, Facebook is only posting:
Bob likes http://techcrunch.com/2010/09/28...
Some guidance would be greatly appreciated.  Thanks for your expertise.

A: Uhh.. are you forgetting to write the link text?
Why We Sold TechCrunch To AOL, And Where We Go From Here on TechCrunch


text:
Q: Adding integers to an ArrayList depending on the modulus of their indexes import java.util.*;
public class AddingIntegers{

     public static void main(String []args){
        ArrayList <Integer> list = new ArrayList<>(Arrays.asList(10,20,30));

        add(list);
     }

public static void add(ArrayList<Integer> list) {
    for (int i = list.size() - 1; i >= 0; i--) {
        if (i % 2 == 0) {
            list.add(list.get(i));
        } else {
            list.add(0, list.get(i));
        }
    }
    System.out.println(list);
}

}

Expected output: [20, 10, 20, 30, 30, 10]
Actual output:  [20, 10, 20, 30, 30, 20]
So I don't understand why, for the last index, when i = 0, 20 is added at the end of the list, which should be 10 as far as I'm concerned.

A: Let's see what happens with each loop.  Start: [10, 20, 30].

*

*i = 2
The expression i % 2 is 0, so the element at index 2 (30) is appended to the end of the list.  The list is now [10, 20, 30, 30].

*i = 1
The expression i % 2 is 1, so the element at index 1 (20) is inserted at the beginning of the list.  The list is now [20, 10, 20, 30, 30].  Note that 20 is now at the beginning of the list.

*i = 0
The expression i % 2 is 0, so the element at index 0 (20) is appended to the end of the list.  The list is now [20, 10, 20, 30, 30, 20].  Note that 20 is appended, not 10, because 10 is no longer at the beginning of the list, 20 is.


text:
Q: Split View Controllers: Initiate a segue from a detail view that effects the Master View Ok So I am very new to XCode and IOS but essentially what I have is this:
I have a split view controller that is used in my app to display a small amount of basic information on an attraction or loaction on the left (in the master view controller) and presents the user with the options/reviews/ or other choices in the detail view controller.
Now what I am trying to do:
- when the user selects an attraction from the dynamically generated table of attractions in the detail view I want it to not only trigger a segue that reveals more information on that in the detail view but also trigger a segue in the master view to change to a short blurb of the attraction.
does anyone know how I'd go about this? I am using Xcode 5
Thank you for your Help
screenshot can be found here:

A: There is plenty of ways you could go about this, but probably the best way is to implement a custom protocol-delegate paradigm that will trigger a piece of code in your master view, which will then invoke a segue in that view.
There is a similar question in this question regarding the navigation stack, but it will work with concurrent controllers as well:
How do I set up a simple delegate to communicate between two view controllers?
Here are Apple's basics regarding the protocols:
https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html
In a nutshell, you would define a protocol in your master view, with one method that invokes the segue depending on the selected cell in the detail view, you would probably pass the model of the location through the method as well.
@protocol LocationDelegate

- (void)didSelectLocation:(MyLocation *)location;

@end

Your table of attractions would have a delegate property pointing to the master view which you would set up at the creation time.
@property (nonatomic, weak) id <LocationDelegate> *delegate;

When you select a cell in the table of attractions, you would call the delegate method to do it's magic.
[self.delegate didSelectLocation:location];