text:
Q: Reversing the order or an array in Excel from last to first In a workbook containing several sheets, I am referencing data from several csv files in one sheet each, sorted in ascending order by date. The original csv files are organized that way. Is it possible to invert this range by "newest to oldest" in the target sheet, without copying the data, and without VBA? Many thanks for any pointers?
The way I am doing this now is with referencing the last valid value in a row, then the second last, third last, and so on until the first. The formula I use for the first cell is:
=INDEX([A17U.SI.csv]A17U.SI!A:A,MATCH(9.99999999999999E+307,[A17U.SI.csv]A17U.SI!A:A))
The second cell:
=OFFSET(INDEX([A17U.SI.csv]A17U.SI!A:A,MATCH(9.99999999999999E+307,[A17U.SI.csv]A17U.SI!A:A)), -1, 0, 1)
The third cell:
=OFFSET(INDEX([A17U.SI.csv]A17U.SI!A:A,MATCH(9.99999999999999E+307,[A17U.SI.csv]A17U.SI!A:A)), -2, 0, 1)
And so on. This takes a long time, and I stil have to know how many rows exist with valid entries. It would be good to have the -1, -2 in the offset function autoincrement according to the number of rows with valid entries.

A: Say we have data in column A.  In cell C1 (the helper cell) enter:
=SUMPRODUCT(MAX((ROW(A:A))*(A:A<>"")))

This gets us the last row in column A with a value.  In B1 enter:
=INDEX(A:A,C$1+1-ROW())

and copy down:

If the number of items in column A were variable, then the formula in B1 would be:
=IF(ROW()>$C$1,"",INDEX(A:A,C$1+1-ROW()))

and B1 would be copied down as far as the maximum length of column A.


text:
Q: Hibernate Migration from 4.3.x to 5.x for method org.hibernate.cfg.Configuration.getClassMapping(className) In Hibernate 4.3.x, there is a method getClassMapping(className) of class org.hibernate.cfg.Configuration.
But in Hibernate 5.x, this getClassMapping(className) method is removed from Configuration class.
What will be the code substitution in Hibernate-5?
Please help on this migration issue.

A: I posted to Broadleaf Commerce because they also needed PersistentClass:

I've been tooling with Hibernate 5, and some of these changes ....
  To get metadata now use the Serviceloader:

package org.broadleafcommerce.openadmin.server.dao;

import org.hibernate.boot.SessionFactoryBuilder;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.boot.spi.SessionFactoryBuilderFactory;
import org.hibernate.boot.spi.SessionFactoryBuilderImplementor;

public class EntityMetaData implements SessionFactoryBuilderFactory {

    private static final ThreadLocal<MetadataImplementor> meta = new ThreadLocal<>();

    @Override
    public SessionFactoryBuilder getSessionFactoryBuilder(MetadataImplementor metadata, SessionFactoryBuilderImplementor defaultBuilder) {
        meta.set(metadata);
        return defaultBuilder;
    }

    public static MetadataImplementor getMeta() {
        return meta.get();
    }
}

You will need the file:
/resources/META-INF/services/org.hibernate.boot.spi.SessionFactoryBuilderFactory

with the fully qualified class name, which in my example is:
org.broadleafcommerce.openadmin.server.dao.EntityMetaData

A: Get an object of PersisterCreationContext and then try this :-
PersistentClass persistentClass =
persisterCreationContext.getMetadata().getEntityBinding(className);

Pls check this link (Example 3.8. Native Bootstrapping - Putting it all together) to understand how to get standardRegistry, metadata and sessionFactory in Hibernate 5.x
Now as we were pulling metadata from persisterCreationContext and now we already had it so we can right away get the required PersistentClass object of any entity by
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
PersistentClass persistentClass = metadata.getEntityBinding(className);

A: In Hibernate 3 and 4 you would do something like this
URL configFileURL = getResource(); //some method to get hold of the location of your hibernate.cfg.xml
Configuration configuration = (new Configuration()).configure(configFileURL);
Iterator classMappings = configuration.getClassMappings();
  while (classMappings.hasNext()) {
    PersistentClass persistentClass = (PersistentClass) classMappings.next();
    //do somthing
    }

In Hibernate 5 initialise Metadata like this
URL configFileURL = getResource(); //some method to get hold of the location of your hibernate.cfg.xml
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure(configFileURL).build();
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();

And use getEntityBindings() on metadata
Collection<PersistentClass> entityBindings = metadata.getEntityBindings();
Iterator<PersistentClass> iterator = entityBindings.iterator();
  while (iterator.hasNext()) {
    PersistentClass persistentClass = iterator.next();
    //do somthing
  }

A: This is discussed in the Hibernate 5.0 Migration Guide as well as the Bootstrap chapter in the Hibernate User Guide (see especially the "Legacy Bootstrapping" appendix).
In short, while Configuration is still supported for straight-line bootstrapping, if you want to "hook into" the bootstrap process you are going to have to use the new bootstrap APIs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a select from a cursor that returns from a plsql function ORACLE i have a function that return a cursor my package is like this
FUNCTION SEDIRUNTIME (sede varchar2) return SYS_REFCURSOR
this cursor return x number of row with only one value, for example :
 ROW1 - 34
 ROW2 - 55
 ROW3 - 56  ecc. ecc.

now i have i select like this
.. AND field in  (select DBK_ENIN_REPORT.*SEDIRUNTIME*(sede) from dual)

this will simulate a clause IN which we can know the values at run time.
for example, based on the location parameter, the cursor can give me 22 and 34 rather than just 56 or 78 98 09.
written so i do not work from error number 00932 incoherent data types.
solutions?

A: You cannot use a CURSOR like that.
But you can change the function to return a collection:
CREATE TYPE Numberlist IS TABLE OF NUMBER;
/

CREATE FUNCTION DBK_ENIN_REPORT.SEDIRUNTIME (
  sede varchar2
) return NumberList
IS
  out_numbers NumberList;
BEGIN
  SELECT id
  BULK COLLECT INTO out_numbers
  FROM   your_table;

  RETURN out_numbers;
END;
/

Then you can do:
.. AND field MEMBER OF DBK_ENIN_REPORT.SEDIRUNTIME(sede)

or
.. AND field IN ( SELECT COLUMN_VALUE FROM TABLE( DBK_ENIN_REPORT.SEDIRUNTIME(sede) ) )

A: Well I would say you CAN do it but you need to twist little bit. You can see how i have done it as below. I take employee table as and example.
Create function:
CREATE OR REPLACE FUNCTION SEDIRUNTIME (sede VARCHAR2)
   RETURN SYS_REFCURSOR
AS
   cur   SYS_REFCURSOR;
BEGIN
   OPEN cur FOR SELECT employee_id FROM employee;

   RETURN cur;
END;
/

Anonymous block which you can implement in your package as Procedure;
DECLARE
   x       SYS_REFCURSOR;
   y       NUMBER;
   v       VARCHAR2 (100);
   v_sql   VARCHAR2 (200);

   TYPE var_emp IS TABLE OF employee%ROWTYPE
      INDEX BY PLS_INTEGER;

   v_emp   var_emp;
BEGIN
   x := SEDIRUNTIME ('sede');

   LOOP
      FETCH x INTO y;

      v := v || ',' || y;

      EXIT WHEN x%NOTFOUND;
   END LOOP;
   --Created the IN clause list
   v := LTRIM (v, ',');

   v_sql := 'Select * from employee where employee_id in (' || v || ')';

   EXECUTE IMMEDIATE v_sql BULK COLLECT INTO v_emp;

   FOR i IN 1 .. v_emp.COUNT
   LOOP
      DBMS_OUTPUT.put_line ( v_emp (i).employee_id || '--' || v_emp (i).first_name);
   END LOOP;
END;

OUTPUT:
SQL> /
1--XXX
2--YYY

PL/SQL procedure successfully completed.

SQL>

PS: Ofcourse the solution provided by MTO is going to be much faster that this.


text:
Q: PHP !is_resource($RS) vs ($RS === false) vs !$RS When checking for a valid resource in PHP, I'm wondering if these are interchangeable. The first two methods are being used where I work and as far as I can tell they are accomplishing the same thing.
Edit: When I first asked this question I was using some code copied from the PHP manual for my example, which contained mysql commands. Since I'm not using mysql I decided it would be better to rewrite the question.
Method 1 - use !is_resource, which has a little more overhead than a direct comparison such as in method 2
$RS = sqlsrv_query($con, $SQL);
if (!is_resource($RS)) {
    die('not a resource');
}

Method 2 - a direct comparison
$RS = sqlsrv_query($con, $SQL);
if ($RS === false) {
    die('not a resource');
}

Method 3 - is this the same as method 2, just less wordy? Or is there some nuance with the === that I'm missing?
$RS = sqlsrv_query($con, $SQL);
if (!$RS) {
    die('not a resource');
}

Thanks

A: mysql_connect will only return either a resource, or false.
Effectively, !$db_link and $db_link === false are the same. Edit: "in this instance." They aren't actually the same, as === performs strict type checking, but for the purposes of this discussion, they are effectively the same.
is_resource is effectively the same as well, just slightly more overhead but not enough to be concerned for such a micro-optimization.
You should not be writing new code using mysql_ functions. It has been deprecated for a very long time. The replacement was mysqli_.

A: If you know what possible values you're dealing with, and these values can clearly be distinguished by a simple boolean test, then that is perfectly fine enough. mysql_connect returns either a resource or a boolean false. The boolean false will always be falsey and the resource will always be truthy, hence if (!$db_link) is a perfectly adequate and concise test. There is no case in which this would fail given the two possible values that $db_link can be here.
=== false is more explicit about the boolean comparison, but unnecessarily so. It doesn't add anything, except verbosity.
is_resource also works for your purpose and is more explicit the other way, but again unnecessarily so. It won't match any additional case a simple boolean comparison wouldn't here.


text:
Q: How can I make subclasses with multiple inheritances, inherit desired value of a specified constructor? I am currently learning c++ and I've come across a problem with multiple inheritance. I've made a simple a program where I have 4 classes named: A, B, C and D A is the parent, B and C are child of A and D is a subclass of B and C.
My problem is that I would expect the D Object to have it's value initialized as it his stated in it's constructor by taking the value of A::a for a which is 1 but instead I get the value 5, more precisely the value that I get in   D is the value of the previous constructor which is C in this case. How can I make D pick value of the specified constructor like stated in D constructor ? First here is the implementation of the Class A
#include <iostream>
#include <string>

class A
{
    public:
        A():a(1){};
        ~A(){std::cout << "Destructor Called\n";};
    protected:
        int a;
};

class B: virtual public A
{
    public:
        B(){a = 3;};
        ~B(){std::cout << "Destructor Called\n";};
};

class C : virtual public A
{
    public:
        C(){a = 5;};
        ~C(){std::cout << "Destructor Called\n";};
};

class D : public B, public C
{
    public:
        D()
        {
            a = A::a;
            std::cout << "a value is: " << a << " for d objects\n";
        }
        ~D(){std::cout << "Destructor Called\n";};
};

int main (void)
{
    D test;
}

Here is what I get on my terminal
a value is: 5 for d objects //value of a in C constructor
Destructor Called
Destructor Called
Destructor Called
Destructor Called

However What I expect is :
a value is: 1 for d objects // value of a in A constructor
Destructor Called
Destructor Called
Destructor Called
Destructor Called


text:
Q: scrape a div with auto generated class with python selenium Hello I'm trying to scrape some questions from a web forum
I am able to scrape questions with a

find_elements_by_xpath

it's something like this :
questions = driver.find_elements_by_xpath('//div[@class="autu-generated"]//div[@class="corpus"]//div[@class="body-bd"]//p')

I made a diagram so you can understand my situation :

my problem is if I didn't specify the auto-generated class in the XPath it's gonna return all the values from the other divs (which I don't want )
and writing the auto-generated class manually like I did to test isn't a valid idea because I'm scraping multiple questions with multiple classes
do you guys have any ideas on how to resolve this problem ??
here is the web forum
thank you
my code :
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time
from fastparquet.parquet_thrift.parquet.ttypes import TimeUnit
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import pandas as pd

driver = webdriver.Chrome('/Users/ossama/Downloads/chromedriver_win32/chromedriver')
page = 1
#looping in pages
while page <= 10:
      driver.get('https://forum.bouyguestelecom.fr/questions/browse?flow_state=published&order=created_at.desc&page='+str(page)+'&utf8=✓&search=&with_category%5B%5D=2483')
      # checking to click the pop-up cookies interfaces
      if page == 1:
                   #waiting 10s for the pop-up to show up before accepting it
                   time.sleep(10)
                   driver.find_element_by_id('popin_tc_privacy_button_3').click()
                   # store all the links in a list
                   #question_links = driver.find_elements_by_xpath('//div[@class="corpus"]//a[@class="content_permalink"]')
                   links = driver.find_elements_by_xpath('//div[@class="corpus"]//a[@class="content_permalink"]')
                   forum_links= []
                   for link in links:
                       value = link.get_attribute("href")
                       print(value)
                       forum_links.append(value)

      else:
          links = driver.find_elements_by_xpath('//div[@class="corpus"]//a[@class="content_permalink"]')
          for link in links:
              value = link.get_attribute("href")
              print(value)
              forum_links.append(value)
              q_df = pd.DataFrame(forum_links)
              q_df.to_csv('forum_links.csv')
      page = page + 1

for link in forum_links:
    driver.get(link)
    #time.sleep(5)
    #driver.find_element_by_id('popin_tc_privacy_button_3').click()
    questions = driver.find_elements_by_xpath('//div[@class="corpus"]//div[@class="body-bd"]//p')
    authors = driver.find_elements_by_xpath('//div[@class="corpus"]//div[@class="metadata"]//dl[@class="author-name"]//dd//a')
    dates = driver.find_elements_by_xpath('//div[@class="corpus"]//div[@class="metadata"]//dl[@class="date"]//dd')
    questions_list = []
    for question in questions:
        for author in authors:
            for date in dates:
                questions_list.append([question.text, author.text, date.text])
                print(question.text)
                print(author.text)
                print(date.text)
                q_df = pd.DataFrame(questions_list)
                q_df.to_csv('colrow.csv')

A: Improved XPATH, and removed second loop.
page = 1
while page <= 10:
    driver.get(
        'https://forum.bouyguestelecom.fr/questions/browse?flow_state=published&order=created_at.desc&page=' + str(
            page) + '&utf8=✓&search=&with_category%5B%5D=2483')
    driver.maximize_window()
    print("Page  url: " + driver.current_url)
    time.sleep(1)

    if page == 1:
        AcceptButton = driver.find_element(By.ID, 'popin_tc_privacy_button_3')
        AcceptButton.click()

    questions = driver.find_elements(By.XPATH, '//div[@class="corpus"]//a[@class="content_permalink"]')

    for count, item in enumerate(questions, start=1):
        print(str(count) + ": question detail:")
        questionfount = driver.find_element(By.XPATH,
                                            "(//div[@class='corpus']//a[@class='content_permalink'])[" + str(
                                                count) + "]")
        questionfount.click()
        questionInPage = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
            (By.XPATH, "(//p[@class='old-h1']//following::div[contains(@__uid__, "
                       "'dim')]//div[@class='corpus']//a["
                       "@class='content_permalink'])[1]")))
        author = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
            (By.XPATH, "(//p[@class='old-h1']//following::div[contains(@__uid__, 'dim')]//div["
                       "@class='corpus']//div[contains(@class, 'metadata')]//dl["
                       "@class='author-name']//a)[1]")))
        date = WebDriverWait(driver, 20).until(EC.visibility_of_element_located(
            (By.XPATH, "(//p[@class='old-h1']//following::div[contains(@__uid__, 'dim')]//div["
                       "@class='corpus']//div[contains(@class, 'metadata')]//dl[@class='date']//dd)[1]")))

        print(questionInPage.text)
        print(author.text)
        print(date.text)
        print(
            "-----------------------------------------------------------------------------------------------------------")
        driver.back()
        driver.refresh()
    page = page + 1

driver.quit()

Output (in Console):
Page  url: https://forum.bouyguestelecom.fr/questions/browse?flow_state=published&order=created_at.desc&page=1&utf8=%E2%9C%93&search=&with_category%5B%5D=2483
1: question detail:
Comment annuler ma commande bbox
ELHADJI
17 novembre 2021
-----------------------------------------------------------------------------------------------------------
2: question detail:
BBOX adsl : Interruption Service Internet ?
GABRIELA
17 novembre 2021
-----------------------------------------------------------------------------------------------------------

A: to overcome this issue i found that the div with auto-generated class had a uid
so here is what the xpath looks like now :
 questions = driver.find_elements_by_xpath('//div[@__uid__="dim2"]//div[@class="corpus"]//div[@class="body-bd"]//p')

sometimes we just gotta focus right !


text:
Q: PDF viewer with print option using pyqt5 or other module I need to show the user a PDF file with the option to print it, and I've seen that pyqt5 has an option to do so, with a pretty interface (this one), but I've tried many times with no result at all. The closest I've got was when I watched this YouTube video https://www.youtube.com/watch?v=22cDr5zdiP4&t=155s, I tried something similar, as I use PyQt5 instead of pyside but they are similar, and also using PyQtWebEngine instead of PyQtWebKit as it is deprecated, but I just get a simple view window with no options this one.
code:
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *

# pip install PyQtWebEngine

app = QApplication(sys.argv)
web = QWebEngineView()
web.settings().setAttribute(QWebEngineSettings.PluginsEnabled, True)
web.load(QUrl('table_with_headers_on_every_page.pdf'))
web.show()
app.exec_()

Note: This script/app should work on linux and windows
edit: I also get this error when scrolling: js: Uncaught Error: Assertion failed


text:
Q: How to filter PrimeNG Data table column, where field is a JSON I have a Data Table with two columns, each one having a filter input. Values are populating in rows as expected. The only problem lies with "director" filter. Fields are defined as:
this.moviecols = [
    { field: "name", header: 'NAME' },
    { field: "directorstatus", header: 'DIRECTOR STATUS' }
]

Response from Server:
{
    director: {name: null, status: "Pro"}
    name: "Star Wars"
}

I am able to filter movies with "name" column:
<input *ngIf="col.field != 'director'" pInputText type="text" (input)="table.filter($event.target.value, col.field, col.filterMatchMode)">

But for "director status" column, where I'm displaying the status field, following code is not working:
<input *ngIf="col.field == 'directorstatus'" pInputText type="text" (input)="table.filter($event.target.value, col.field['status'], col.filterMatchMode)">


text:
Q: Disable the Drop down column based on the text value I am working with SharePoint 2010 form library.
I have a drop down column which is dependent on text input column value .
The value in the Text input column comes from the infopath form.
What i want is :-
Suppose the text column value is "AU" then disable the Drop down column otherwise enable it.
I want to code this in Sharepoint Form library Edit page(Editpage.aspx).
I think it would be possible with Jquery.
Any help/suggestion would be highly appreciated.
--
Update:
This is the code which i am using in the Sharepoint Edit Page:
<script type="text/javascript" src="/SiteAssets/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        if ($("#Test Value").val() != null) {
            $("Select[Title='Test_Status']").attr('disabled', 'disabled');
        }
    });
</script>

But it's not working! In nutshell I want is when the text column(Test Value) value is blank then the Choice column(Test_Status) should be disabled and vice versa. For Refernence See the image below :

A: Try:
$(document).ready(function() {
    if ($("input[title='Test Value']").val()) {
        $("select[title='Test_Status']").attr('disabled', 'disabled');
    }
    else {
        $("select[title='Test_Status']").removeAttr('disabled');
    }
});

A: I have solved this problem:
Below is the source of the Javascript attach it with code.
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"
write this all code in the javasrcipt tag
$(document).ready(function() {
// add change handler
$("input[title='Test Value']").change(function() {
    MasterSelectChange();
});
// call the change function to set up form for first display:
MasterSelectChange();

});
function MasterSelectChange()
{
var thisVal =  $("input[title='Test Value']").val();

if(thisVal == "AU")
{
  $("select[title='Test_Status']").closest("tr").hide();

    }
else
{
      $("select[title='Test_Status']").show();

}

}


text:
Q: How to handle aggregates relationship in Event Sourcing properly? When having a somehow "complex" domain model, it's unavoidable to have related entities (that's the sense of aggregate root). But how should I reconstitute relationships from events? Searching by other aggregate id in serialized events is obviously not an option.
I have an idea to use such DB structure (for example). It has aggregates tables with just id and foreign keys, to simplify retrieving all necessary events from different entities. Doesn't this break the ES principles?

A:
DDD says that "rich domain model" consists from entities which handles business logic, and we work with them as they model the domain objects

Yes, and that's still true when you use event sourcing.

So I can imagine i.e. order.addItem(product) method, where OrderItem creating and making relationship with Order and Product.

Aha, no -- not in either approach.  If Order and Product are different aggregates, then order.addItem(product) is not a spelling that you would use.  The order and the product don't share responsibility for the product's state.  Or, put another way, we never nest aggregates roots inside each other.
The usual spelling, per the rules of DDD, would be order.addItem(product.id).  Note this important difference: changing an Order cannot change any of the details of a Product.
It's part of the point: each bit of state in your domain has a single authority responsible for maintaining its consistency.
Note: the spelling order.addItem(product) makes sense for a model where Product is an entity that is not an aggregate root, but instead is subordinate to Order (and more precisely, each Product is associated with exactly one order).

But if Item has many-to-one relationship to Order, shouldn't it contain orderId instead? (Not Order containing list of ItemId). But that would mean it should be Item.AddToOrder(order.Id), which makes not so much sense.

The short answer is that you get different spellings for the methods depending on how you decide to model the data, and which items are responsible for maintaining the integrity of aggregates.
Working backwards - part of the motivation for aggregates at all (rather than just having one large consistency boundary around you entire model) is the idea of concurrent modification of different parts of the model.  Whether or not OrderItem is a separate aggregate from Order is going to depend -- in part -- on how important it is that two different OrderItems can be modified concurrently.
For cases like online shopping carts, that's probably not super important.
For a setting where many parties are trying to modify the same order at the same time, something like
OrderItem.create(order.id, product.id)

Wouldn't be unreasonable.

And still, aggregate root contains other aggregates, and OrderItem in that case is aggregate, not aggregate root or value object.

An aggregate root has responsibility for one aggregate.  That aggregate (which fundamentally is just "state") can conceptually be the current state of multiple entities subordinate to the root, each managing a specific part of the whole.

And if I'm right, aggregate root contains business logic to control inner aggregates, so we still need to build aggregate root which contains other entities in it.

"Inner aggregate" doesn't make sense -- aggregates don't nest.  Entities nest, with the outermost entity playing the role of the aggregate root.
So, how do we build nested entities?
Let's step back, and look at how we typically create a single entity.  We run some query (like getById) to get the State that we had previously saved.
Factory {
    Entity fromState(currentState) {
        return new (entity);
    }

    State fromEntity(theEntity) {
        return theEntity.getState();
    }
}

Nested entities work the same way, with the subordinate entities taking over part of the work.  For an Order, it might look like...
Factory {
    Order fromState(currentState) {
        List<OrderItem> items = ...

        for (State.Item itemState : currentState.items()) {
            OrderItem orderItem = OrderItem.from(itemState)
            items.add(orderItem)
        }

        return new Order(items);
    }
}

Order {
    State getState() {
        State currentState = State.EMPTY;

        for(OrderItem orderItem : this.items) {
            currentState = currentState.addItemState(orderItem.getState())

        return currentState
    }
}

When we use event sourcing, the bit that changes is that we use collections of events instead of state.
Factory {
    Order fromEvents(history) {

        // The one tricky bit -- the history we will be looking
        // at is a mix of histories from all of the entities that
        // coordinate the changes to the aggregate, so we may need
        // to untangle that.

        Map<OrderItemId, Events> = itemHistories
        for (Event e : history )
            items.put(e.orderItemId, e)

        List<OrderItem> items = ...

        for (Events events: itemHistories.values) {
            OrderItem orderItem = OrderItem.from(events)
            items.add(orderItem)
        }
        return new Order(items);
    }
}

Order {
    List<Event> getEvents () {
        List<Event> events = new List();

        for(OrderItem orderItem : this.items) {
            events.addAll(orderItem.getEvents())
        }
        return events
    }
}

A: You take care of any relationships with keys but they are not enforced by anything like foreign key constraints like in a DB. In fact the key of a user in your shop event may be a human readable ID. There is no requirement to link via the Guids.
Mapping from one to the other is done in projections that help you make correct information displayed and the proper fields in your commands.


text:
Q: Python 3.x function:Converting string to list and printing output which excludes certain characters I have a problem wrapping my head around trying to convert strings into lists and producing the desired output. So far I have this code:
def func():

    characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
    new_lst = []
    user = input("String: ")
    for i in user:
        if (i not in characters):
            #new_lst = user.split(' ')
            new_lst += i # I know this is the problem but I just don't know where to go from here

    print(new_lst)

For example:
Keep. hyphen- and apostrophe's only.

Current output:
'K', 'e', 'e', 'p', ' ', 'h', 'y', 'p', 'h', 'e', 'n', '-', ' ', 'a', 'n', 'd', ' ', 'a', 'p', 'o', 's', 't', 'r', 'o', 'p', 'h', 'e', "'", 's', ' ', 'o', 'n', 'l', 'y']

Desired output:
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']

Thanks for any help!

A: Split the sentence into its words first, and then iterate over the words to rebuild (in the inside loop) the modified words and (in the outside loop) the list of words:
def func():

    characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
    new_lst = []
    user = input("String: ")
    for word in user.split():
        x = ''
        for i in word:
            if (i not in characters):
                x += i # I know this is the problem but I just don't know where to go from here
        new_lst.append(x)

    print(new_lst)

func()

Output:
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']

This isn't necessarily a code-review site, but I would definitely consider naming your variables more meaningfully and using a list comprehension for the inner loop:
def get_stripped_word_list(s):
    """Return a list of words in string s, excluding certain characters."""

    # Sequence of characters to strip, keeping ' and -
    characters = '?/><,.:;"[]{}=+()*&^%$#@!'
    words = s.split()
    modified_words = []
    for word in words:
        modified_word_letters = [c for c in word if c not in characters]
        modified_words.append(''.join(modified_word_letters))
    return modified_words

s = input("String: ")
print(get_stripped_word_list(s))

A: you can replace the characters and you can split it
def func():

    characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
    user = raw_input("String: ")
    for i in characters:
        user=user.replace(i,"")
    new_lst=user.split(" ")
    new_lst = [i.strip('.') for i in new_lst]
    print(new_lst)
func()

output
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']

A: You can use sub from the re module:
import re
string = "Keep. hyphen- and apostrophe's only."

re.sub("[^\w '-]", '', string).split()

Out[672]: ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']


text:
Q: monthlyReturn for multivariate XTS I have an XTS called AUM which has 5 columns
head(AUM)
             FXI.Adjusted X2823.HK.Adjusted HSCE.Adjusted X3049.HK.Adjusted HSI.Adjusted
2010-04-08     100.0000          100.0000      100.0000          100.0000     100.0000
2010-04-09     100.9009          100.9009      100.9009          100.9009     100.9009
2010-04-12     100.4474          100.6022      100.1916          100.1448     100.0890
2010-04-13     101.7668          101.8123      101.6008          101.4299     101.4111
2010-04-14     102.1177          102.3792      101.9873          101.7272     101.7813
2010-04-15     102.0445          102.1387      101.7266          101.5462     101.4893

I want to calculate monthly returns for each column.  I can do it for one column by calling monthlyReturn(AUM[,1]) but I cannot get it calculate monthly returns for all five columns and return a multivariate XTS.
I tried this apply(AUM, 2, monthlyReturn) but I get the error
Error in array(r, dim = d, dimnames = if (!(is.null(n1 <- names(x[[1L]])) &  :
  length of 'dimnames' [1] not equal to array extent

Any help much appreciated.  Thanks in advanced.

A: It should work with the function lapply:
lapply(AUM, monthlyReturn)

This command will return a list of xts objects.


text:
Q: How can i change innerHTML +1? I want to change the innerHTML so for every circle thats the same it adds +1
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
    document.getElementById("point2").innerHTML = +1
}

if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
    document.getElementById("point2").innerHTML = +1
}

A: I suggest you to use innerText then. First get the old value and cast to Number then add by 1 and replace the old value. Example:
if (document.getElementById("circle1").style.backgroundColor == document.getElementById("circle5").style.backgroundColor) {
    let obj = document.getElementById("point2");
    let oldValue = Number(obj.innerText);
    obj.innerText = oldValue + 1;
}

if (document.getElementById("circle2").style.backgroundColor == document.getElementById("circle6").style.backgroundColor) {
    let obj = document.getElementById("point2");
    let oldValue = Number(obj.innerText);
    obj.innerText = oldValue + 1;
}

See difference between innerText and innerHtml.

A: document.getElementById("point2").innerHTML doesn't give you a number, so you cannot add 1 to it. first you need to parse the content to a number (like with parseInt or Number), and then you can add 1.

// creating the reference variable (for smaller code)
var point2 = document.getElementById("point2").innerHTML

if (document.getElementById("circle1").style.backgroundColor ==
  document.getElementById("circle5").style.backgroundColor) {
  document.getElementById("point2").innerHTML = increment(point2)
}
if (document.getElementById("circle2").style.backgroundColor ==
  document.getElementById("circle6").style.backgroundColor) {
  document.getElementById("point2").innerHTML = increment(point2)
}

// function to increment the value of point2
function increment(html) {
  return Number(document.getElementById("point2").innerHTML) + 1
}
#circle1 {
  background-color: red;
}

#circle5 {
  background-color: red;
}

#circle2 {
  background-color: red;
}

#circle6 {
  background-color: red;
}

C1

C5

C2

C6

0


text:
Q: Instert into table when the table is empty? i have this code to update a value in the database, but this only works if there is already something in the database. is it possible to check if the database is empty first and if its empty INSTERT something into the databse, else just update it with this code.
 $name = $_POST['example'];
        if (isset($_POST['example'])) {
            $sql = 'UPDATE `table` SET `column` = "' . $name . '"';
            $stmt = $this->db->pdo->prepare($sql);
            $stmt->execute();
            return $stmt->rowCount();
        }

A: Try the below code. It's working for you.
<?php
    $name = $_POST['example'];
    if (isset($_POST['example'])) {
        $sql = 'SELECT COUNT(*) from `table` where `column` = "' . $name . '"';
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->execute();

        if ($stmt->fetchColumn() > 0) {
            $sql = 'UPDATE `table` SET `column` = "' . $name . '"';
        } else {
            $sql = 'INSERT INTO `table` (`column`) VALUES("' . $name . '")';
        }
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->rowCount();
    }
?>

A: Prepare stmt for prevent sql injection like:
<?php
    $name = $_POST['example'];
    if (isset($_POST['example'])) {
        $sql = 'SELECT COUNT(*) from `table` where `column` = ?';
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->bind_param('s',$name);
        $stmt->execute();

        if ($stmt->fetchColumn() > 0) {
            $sql = 'UPDATE `table` SET `column` = ?';
        } else {
            $sql = 'INSERT INTO `table` (`column`) VALUES(?)';
        }
        $stmt = $this->db->pdo->prepare($sql);
        $stmt->bind_param('s',$name);
        $stmt->execute();
        return $stmt->rowCount();
    }
?>


text:
Q: Question about jQuery and reload a page this is a noob question, so, be generous with me please.
Take for example Twitter. There's an input text form at the top for writing tweet and below the tweets list. If you write a new tweet and click "Tweet" button, you'll see the your new tweet instantly in the tweet list, without reloading a page. I know this is a banal situation but by the way I want to ask you.
I've a page with a form at the top and below it there's a message list. When you fill the form and submit a new message the page it reloads and you see the updated message list with the new message. I want implement the same technique that Twitter use. Maybe should I use jQuery, and send data to a page with $.post. Can you explain me something about?

A: Fred ,
you can use jquery ajax for the same ,
on the ajax success update your DOM html
http://api.jquery.com/jQuery.ajax/

A: As you are a beginner, I think the easiest way would be the one i'll describe.
If you have this div (where you want the new feed to appear):
Markup:

 Feed 1

 Feed 2

Javascript:
$("div.feed:last").clone().appendTo("#feeds").load("newfeed.php?param1=val1");

Server (asuming php):
<? //newfeed.php
   $param1 = $_GET['param1'];
   $content = "Here put your latest feed";
   echo $content;
?>

And that's it.
Now I'll explain what we are doing in that javascript line
$("div.feed:last")      //Select the last div with class "feed"
   .clone()             //We clone it, to make space for the new feed
   .appendTo("#feeds")  //We add the clone to the final of the feed list
   .load("newfeed.php?param1=val1");  //Load it's content with a value got from server

When you feel more confortable with jquery, use $.ajax instead.
Hope this helps, cheers


text:
Q: How could this be done better? I am trying to target the background of my navigation and 4 other divs in the body copy when mousing over any navigation links or the divs in the body copy.

*

*when mousing over any one of the four divs in the body copy the other three divs should fade and the navigation divs backgroun dcolor should change as well

i have it working but i am new to javascript/jquery and i know there is a better way to do it.
What would that be?
link to dev site is http://www.alienfactory.com/vision1/
Its kinda funny everytime i look at it it looks like i am trying to write javascript like it is CSS
here is a code snippet it repeats 3 more time for the various mouseover targets

$('#services, #navservices').hover(
    function () {
        $('#vision, #approach, #team').stop().fadeTo('slow', .2);
        $('#navigation').stop().animate({ backgroundColor: "#8ac2b7" }, 500);
},
    function () {
    $('#vision, #approach, #team').stop().fadeTo('slow', 1);
    $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
    }
);

for further clarification here is the full script. I know there is a better way but how?

$('#services, #navservices').hover(
    function () {
        $('#vision, #approach, #team').stop().fadeTo('slow', .2);
        $('#navigation').stop().animate({ backgroundColor: "#8ac2b7" }, 500);
    },
    function () {
        $('#vision, #approach, #team').stop().fadeTo('slow', 1);
    $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
    }
    );
$('#vision, #navvision').hover(
    function () {
        $('#services, #approach, #team').stop().fadeTo('slow', .2);
        $('#navigation').stop().animate({ backgroundColor: "#9e97ca" }, 500);
    },
    function () {
        $('#services, #approach, #team').stop().fadeTo('slow', 1);
        $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
        }
    );
$('#approach, #navapproach').hover(
    function () {
        $('#services, #vision, #team').stop().fadeTo('slow', .2);
        $('#navigation').stop().animate({ backgroundColor: "#e5b120" }, 500);
        },
    function () {
        $('#services, #vision, #team').stop().fadeTo('slow', 1);
    $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
    }
    );
$('#team, #navteam').hover(
    function () {
        $('#services, #vision, #approach').stop().fadeTo('slow', .2);
    $('#navigation').stop().animate({ backgroundColor: "#cf1858" }, 500);
    },
    function () {
        $('#services, #vision, #approach').stop().fadeTo('slow', 1);
        $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
    }
    );

A: You could cache the elements:
var e1 = $('#vision, #approach, #team'),
    e2 = $('#navigation');
$('#services, #navservices').hover(
    function() {
        e1.stop().fadeTo('slow', .2);
        e2.stop().animate({ backgroundColor: "#8ac2b7" }, 500);
    },
    function() {
        e1.stop().fadeTo('slow', 1);
        e2.stop().animate({ backgroundColor: "#404040" }, 500);
    }
);

A: Ah, I see what you mean.  How about this:
var eventOver = function() {
    $('#vision, #approach, #team').stop().fadeTo('slow', .2);
    $('#navigation').stop().animate({ backgroundColor: $(this).data('fadeTo') }, 500);
};
var eventOut = function() {
    $('#vision, #approach, #team').stop().fadeTo('slow', 1);
    $('#navigation').stop().animate({ backgroundColor: '#404040' }, 500);
}
$('#services, #navservices').data('fadeTo', '#8ac2b7').hover(eventOver, eventOut);
$('#vision, #navvision').data('fadeTo', '#9e97ca').hover(eventOver, eventOut);
$('#approach, #navapproach').data('fadeTo', '#e5b120').hover(eventOver, eventOut);
$('#team, #navteam').data('fadeTo', '#cf1858').hover(eventOver, eventOut);

A: Use target events to sum everything in only one hover function for all divs. Here is a possible snipet:
$( document ).hover( function( ev){
    function () {
        var target = $( ev.target);
        var elements = {'div_1', 'div_2', 'div_3', 'div_4'}; // all divs
        elements[target.attr('id')] = null; // only the other ones
        $(target ).doSomething(); // with the main div
        $.each( elements , function(i, el){
            $(el).doSomethingElse(); // with other divs
        });
    },
    function () {
        // the same concept as above
    }
});

A: Looking at your dev site, I can see that you want the top bar to be the same color as the area you hover over at the bottom.   This means you can remove your hardcoded colors and simply look up the color of the item you are hovering over.
To make things simpler, I'd advise that you take all of your sections at the bottom and give them a common CSS class.  For this example I'll use navSection.
$('.navSection').hover(function() {
    var bgColor = $(this).css('background-color');
    $(this).siblings().stop().fadeTo('slow', .2);
    $('#navigation').stop().animate({ backgroundColor: bgColor }, 500);
}, function() {
    $(this).siblings().stop().fadeTo('slow', 1);
    $('#navigation').stop().animate({ backgroundColor: "#404040" }, 500);
});

This will work on the page you linked to, provided that you add the navSection class to the areas you want to hover over.


text:
Q: Swagger codegen failed: missing swagger input or config I have this json file and I have been trying to create models and API code through swagger codegen. This has not been quiet effective as it throws error.
Exception in thread "main" java.lang.RuntimeException: missing swagger input or config!
    at io.swagger.codegen.DefaultGenerator.generate(DefaultGenerator.java:735)
    at io.swagger.codegen.cmd.Generate.run(Generate.java:285)
    at io.swagger.codegen.SwaggerCodegen.main(SwaggerCodegen.java:35)

The swagger docs version is 1.2. And I am using swagger-codegen version 2.4.0.
java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i ./json/docs.json -l python -o C:/Users/sk/projects/generated-sdk

A: In the yaml file, if you do not strictly have the indent, you can get the error like this. For swagger-codegen-cli-2.1.6.jar, the error message won't tell you which row is wrong. (Just not sure whether this get fixed in the newer version. )


text:
Q: IOS Переключение на другой язык в приложении У меня проект в котором все строки локализованы и используется NSLocalizedString. Приложение само выбирает язык в соответствии с языком системы, но мне нужно реализовать переключение вручную. как это сделать?

A: У функции NSLocalizedString очень много аргументов, хотя у многих из них есть значение по умолчанию. Так как Вы не предоставили никакого кода в вопросе, то смею предположить, что Вы используете её вот так:
NSLocalizedString("key", comment: "")

В таком случае Вы не используете аргумент bundle, который отвечает за пакет, из которого будут извлекаться переводы. И это плохо, без него Вам будет сложно управлять языками для переводов.
Предположим, что для описания языков Вы используете такое перечисление:
enum Language: String {

    case en
    case ru
}

Тогда переключение языков можно попробовать выполнить с помощью такой функции:
func switchApplicationLanguage(language: Language) {

    UserDefaults.standard.set([language.rawValue], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()
}

Основная идея заключается в том, что функция NSLocalizedString при выборе языка для перевода использует UserDefaults. В нашем случае мы устанавливаем 1 предпочитаемый язык. Однако опыт показывает, что установленные таким образом языки подхватываются лишь при следующем запуске приложения. Я не думаю, что пользователи оценят по достоинству необходимость перезапуска приложения каждый раз после изменения языка. Поэтому рекомендую использовать следующий вариант вызова NSLocalizedString:
NSLocalizedString("key", bundle: selectedBundle, comment: "")

Переменная selectedBundle вычисляется следующим образом:
var selectedBundle: Bundle {

    if let path = Bundle.main.path(forResource: currentLanguage.rawValue, ofType: "lproj"),
       let bundle = Bundle(path: path) {

        return bundle
    }
    return Bundle.main
}

Выбранный язык у Вас должен храниться в глобальной переменной:
var currentLanguage: Language = .ru


text:
Q: VS Developer Express for Windows Phone new project shows XamlParseException I recently installed windows 8 along with Visual Studio Express 2012 for Windows Phone. However, if I start a new Windows Phone App project (7.1, although 8 has the same issue) and open the MainPage.xaml file, an error appears in the designer window as follows:
XamlParseException: Cannot find a Resource with the Name/Key PhoneBackgroundBrush [Line: 47 Position: 111]

The MainPage.xaml file is as follows:
<phone:PhoneApplicationPage
    x:Class="PhoneApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"></Grid>
    </Grid>

</phone:PhoneApplicationPage>

The App.xaml file contains this:
<Application
    x:Class="PhoneApp1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone">

    <!--Application Resources-->
    <Application.Resources>
    </Application.Resources>

    <Application.ApplicationLifetimeObjects>
        <!--Required object that handles lifetime events for the application-->
        <shell:PhoneApplicationService
            Launching="Application_Launching" Closing="Application_Closing"
            Activated="Application_Activated" Deactivated="Application_Deactivated"/>
    </Application.ApplicationLifetimeObjects>

</Application>

The solution looks like this:

There doesn't appear to be any other style related files anywhere. Can anyone shed any light on this? its driving me insane.

A: Phew! fixed this as follows:
Right click the project in the solution explorer panel on the right
Select Add -> Existing Item
Select C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Design\ThemeResources.xaml in he file browser
Click 'Add' button
In your App.xaml file, add the following replace the  section with this:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ThemeResources.Xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Open the designer at MainPage.xaml - should now work ok. Hope this saves someone a bit of time!

A: Based on your own answer instead of copying the original ThemesResources.xaml I'd create a new one and merge it with the original.
Create a new Resource Dictionary (e.g. FixedDictionaryResources.xaml). In Visual Studio you need to create a Windows Phone Page or use any other template that creates a XAML file. In Blend you can create a resource dictionary directly. In VS you need to remove then all the content and put in the following code. In Blend just add the

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- Resource dictionary entries should be defined here. -->
    <SolidColorBrush x:Key="PhoneBackgroundBrush" Color="{StaticResource PhoneBackgroundColor}"/>
</ResourceDictionary>

Open App.xaml and add the following code to merge the new dictionary with the default resources dictionary.
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/FixingResourceDictionary.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Reopen the pages that are still showing the PhoneBackgroundBrush missing issue and everything should work now.


text:
Q: jqtree moving the childnodes I want to move subchild to child nodes but I don't want to move subchild to parent node. I can move the childnode to another parent node, but it cannot be a parent node. Is jqtree better or jstree better for binding the conditions.
var data = [
    {
        label: 'node1',
        children: [
            { label: 'child1',
             children: [
                { label: 'sub-child1' }
            ]
            },
            { label: 'child2' }
        ]
    },
    {
        label: 'node2',
        children: [
            { label: 'child3' }
        ]
    }
];

$(function() {
    $('#tree1').tree({
        data: data,
        dragAndDrop: true,
        /*onCanMove: function(node) {
            if (! node.parent.parent) {
                // Example: Cannot move root node
                return false;
            } else {
                return true;
            }
        },*/
        onCanMoveTo: function(moved_node, target_node, position) {
            console.log(node);
            if (target_node == moved_node.parent.parent) {
                return (position == 'inside');
            }
            else {
                return true;
            }
        }
    });
});

$('#tree1').on("click",function() {
    var node = $('#tree1').tree('getSelectedNode');
    console.log(node.name);
});

fiddle

A: I got the solution, if anyone is looking for a similar problem, this might help
All I had to do is this
onCanMove: function(node) {
            if (!node.parent.parent) {
                return false;
            }
            else {
                return true;
            }
        },
        onCanMoveTo: function(moved_node, target_node, position) {
           if(position == 'inside' && target_node !== moved_node.parent.parent && target_node.getLevel() < moved_node.getLevel()) {
                return true;
            }
            else {
                return false;
            }
        }

fiddle


text:
Q: Consume Json in Python Django I am trying to consume data from API which is in the following format. Where count can be more than one -
{u'count': 1, u'previous': None, u'results': [{u'url': u'http://127.0.0.1:8000/offapp/cities/', u'city_name': u'Kolkata', u'id': 1}], u'next': None}

I am using the following method to consume json -
views.py
def employee(request):
    data = requests.get('http://127.0.0.1:8000/offapp/cities/').json()
     context = RequestContext(request, {
    'cities': data.results,
})
return render_to_response('template.html', context)

template.py
{% for city in cities %}

{{city.city_name}}

{% endfor %}

But django can't seem to resolve the name or id and gives the error -
AttributeError: 'dict' object has no attribute 'city_name'

What is the correct way to use this data? I want to be able to use all the data in results of json in my template and use id to reverse match and go to the next view using id.

A: I have not used requests json but looking at the documentation you should be using it as a dictionary as the regular json module.
In your code use 'cities': data['results'] and then in your template use city.city_name.
Django templates use dot lookups: when the template system encounters a dot in a variable name, it tries a dictionary lookup.

A: It looks like 'city_name' is a property of data.results[0], not data.city. Sorry I can't test the requests.get(url).json(), so it may need to be data['results'][0]


text:
Q: Solve by using generating functions: There are eight married couples in a room I was hoping somebody could help me out with this problem:
Solve by using generating functions:
There are eight married couples in a room. If these sixteen  people were divided into eight  pairs, in how many pairings are there such that each pair isn't married?
I am struggling with how to model this as a generating function.
Please help me to get the correct generating function.
Any help is appreciated.
Thanks!

A: There are $6$ ways of choosing a couple as part of the $4$ member group.
Having chosen $1$ couple, there are then $5$ couples remaining. Possible pairs from among $10$ remaining people = $10!/(8!)(2!) = 45$. Just $5$ of these pairs are actual couples. Thus there are 40 possible pairs of the $10$ person group of $5$ couples that are not couples.
Thus, in response to the question, there are $6\times 40 = 240$ possible arrangements (distinct combinations) of $1$ of 6 couples together with a pair of people from among $5$ couples ($10$ people) but not such as to be $1$ of the $5$ couples.


text:
Q: Processing Drawing Problems I'm kind of new to processing so bear with me. I'm creating a basic drawing program where you click on a colored box to get that color and then you can draw and stuff. Well I already created a red box color and an eraser so I decided to create a blue box but when I click it, it doesn't change the color to blue. I have tried troubleshooting this with no luck.
Here's the code (note this works best with Eclipse and importing the processing core https://processing.org/tutorials/eclipse/):
// note: many imports aren't used yet
import java.util.ArrayList;
import java.util.Scanner;
import processing.core.PApplet;
import processing.core.PShape;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends PApplet{

PShape rectangle;

int color;
int color2;
int color3;
boolean red = false;
boolean blue = false;
boolean green = false;
boolean eraser = false;

// needed to create this in order for Eclipse to work
public static void main(String[] args) {
    PApplet.main("Main");
}

public void settings(){
    size(1280, 720);
}

public void setup() {
    size(1280, 720);
    smooth();
    background(255, 255, 255);
    noStroke();

}

public void draw() {
    // nothing here yet
    if (keyPressed) {

    }
    else {
        color = 0;
    }
    fill(0);

    fill(255, 0, 0);
    // red square
    rect(0, 50, 50, 50);
    fill(0, 10, 255);
    // blue square
    rect(0, 100, 50, 50);
    fill(0);

}

public void mousePressed() {
    if(red) {
        color = 255;
        color2 = 0;
        color3 = 0;
    }
    if(eraser) {
        color = 255;
        color2 = 255;
        color3 = 255;
    }
    if(blue) {
        color = 0;
        color = 10;
        color = 255;
    }
    else{
        fill(0);
    }
    // check if mouse is in drawing area
    if (mouseX >= 50 && mouseX <= 1280 && mouseY >= 0 && mouseY <= 720) {
        // change the drawing color
        fill(color, color2, color3);
        rect(mouseX, mouseY, 50, 50);
    }
    // if red
    if (mouseX >= 0 && mouseX <= 50 && mouseY >= 50 && mouseY <= 100) {
        eraser = false;
        blue = false;
        red = true;
    }
    // if eraser (note: in top left corner)
    if (mouseX >= 0 && mouseX <= 50 && mouseY >= 0 && mouseY <= 50) {
        red = false;
        blue = false;
        eraser = true;
    }
    // if blue
    if (mouseX >= 0 && mouseX <=50 && mouseY >= 100 && mouseY <= 150) {
        eraser = false;
        red = false;
        blue = true;
    }
}

// basically the same code for mousePressed
public void mouseDragged() {
    if(red) {
        color = 255;
        color2 = 0;
        color3 = 0;
    }
    if(eraser) {
        color = 255;
        color2 = 255;
        color3 = 255;
    }
    if(blue) {
        color = 0;
        color = 10;
        color = 255;
    }
    if (mouseX >= 50 && mouseX <= 1280 && mouseY >= 0 && mouseY <= 720) {
        fill(color, color2, color3);
        rect(mouseX, mouseY, 50, 50);
    }
    if (mouseX >= 0 && mouseX <= 50 && mouseY >= 50 && mouseY <= 100) {
        eraser = false;
        blue = false;
        red = true;
    }
    if (mouseX >= 0 && mouseX <= 50 && mouseY >= 0 && mouseY <= 50) {
        red = false;
        blue = false;
        eraser = true;
    }
    if (mouseX >= 0 && mouseX <=50 && mouseY >= 100 && mouseY <= 150) {
        eraser = false;
        red = false;
        blue = true;
    }
}

}

A: First of all, you shouldn't use a variable named color. That might not cause an error if you're using eclipse, but it's going to be confusing because it clashes with Processing's special color data type.
Secondly, look at this if statement:
if(blue) {
    color = 0;
    color = 10;
    color = 255;
}

You're just setting color over and over again. Maybe you meant to use color2 and color3?
That if statement is in two different places. If I change that to color1, color2, and color3, your code works okay.


text:
Q: How to use FlatList to render heterogenous data in react-native? I have two types of data one is a list of Transactions and the other are some details of the User. Since these are different types of data. How do I render them inside the same FlatList?
Sample transactionData = [{amount: 200, date: '2020-08=02', desc: 'bill'}, {amount: 200, date: '2020-08=02', desc: 'bill'}]
Sample userData = {name: 'John Doe', gender: 'Male'}

A: write render item function to deal with it
const renderItem = ({item})=>{
  if(//checkIfType1){
    return(<Type1Component data={item} />)
  }
  return(<Type2Component data={item}/>)
}

and use that function in renderItem attribute
renderItem={renderItem}


text:
Q: Can I select United States if my country is not listed? apparently my country is not listed so I'm unable to finish my registration
for the apple ID thing. I'm thinking of selecting United States in there but it keeps asking me for a billing address/phone which I don't have since I don't live in there. So my question is what might happen if I put my friend's US address and phone there? Will it work? or will i face backlash from apple and they're going to disable my device permanently? Thanks

A: You can put United States as the country for your Apple ID and, if necessary, use your friend's US address (or any US address at all) as yours. Apple does not try to verify that you are actually from the US or, by any means, you or someone else is associated with that address. However, Apple will ask for a US-based credit or debit card or a US-based PayPal account whenever you want to buy anything from Apple such as music, videos, an app or a service like iCloud.
Or you might keep buying US iTunes gift cards off of the internet (or you may buy them yourself if you are visiting the US frequently or your friend may buy them for you and send them to you once in a while) but the first option is a bit costly and slightly risky and it is up to you to decide about the sustainability of the latter two.
In addition, if you would like or need to change your Apple ID country in the future, you might eventually lose some of the stuff you have bought from Apple until then under that Apple ID.
You can find here at Apple's support site payment options accepted by Apple.
P.S. You shouldn't need a phone number to create an Apple ID. But if you put your friend's phone number in and confirm it for another purpose later on, then, unlike the address, s/he would not be able to use that number for another Apple ID.


text:
Q: Javascript variable in form I'm creating a process which pulls down a static Google map image using their API.
I have a form which has radio buttons with the following map image options:
 Satellite
 Roadmap
 Hybrid
 Terrain

The radio buttons are in a form - part of which is below:
Basemap

Select a Map Style:

        <input type="radio" name="basemapStyle" id="basemapStyle" value="Satellite" checked /> Satellite
        <input type="radio" name="basemapStyle" id="basemapStyle" value="Roadmap"/> Roadmap
        <input type="radio" name="basemapStyle" id="basemapStyle" value="Hybrid" /> Hybrid
        <input type="radio" name="basemapStyle" id="basemapStyle" value="Terrain" /> Terrain

I have an underlying javascript document which is called from the html page.
It contains the following code:
var bmStyle = document.getElementById("basemapStyle").value;

if (bmStyle = "Satellite" ) {
    var basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
}
else if (bmStyle = "Roadmap" ) {
    var basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
}
else if (bmStyle = "Hybrid" )  {
    var basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
}
else if (bmStyle = "Terrain" )  {
    var basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
}

The page loads successfully and a "basemap" is generated.  However, the selected radio button makes no difference and the only first variable in the if else statement seems to get loaded.
I feel there's some logic error in the if else statement but I can't seem to get my head round it.

A: First:
You have this in your conditional:

if (bmStyle = "Satellite")

Instead you should use:

if (bmStyle == "Satellite")

if (bmStyle == "Satellite" ) {
        var basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Roadmap" ) {
        var basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Hybrid" )  {
        var basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Terrain" )  {
        var basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
        }

Second:
IDs should be unique, so you must change it.
Solution on your code (using duplicated IDs):
var bmStyle = $('#basemapStyle:checked').val()

if (bmStyle == "Satellite" ) {
        var basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Roadmap" ) {
        var basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Hybrid" )  {
        var basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
        }
    else if (bmStyle == "Terrain" )  {
        var basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
        }

A: You cannot use the same id for different elements.
So:
var bmStyle = document.getElementById("basemapStyle").value;

is not returning what you expect. Check it by adding this line:
alert(bmStyle);

So remove the id's.
Read more here how to get radio value:
How to get the selected radio button's value?

A: *

*Firstly you have Assignment = in if instead of ==

*You have to declare basemapStyle outsite

*You cannot use same id to all your radio buttons
Here i have redesigned Your Code To Get A Proper Output using Function

function fun(radio){
var bmStyle = radio.value;

  var basemapStyle;
  if (bmStyle == "Satellite" )
             basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";

        else if (bmStyle == "Roadmap" )
             basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";

        else if (bmStyle == "Hybrid" )
             basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";

        else if (bmStyle == "Terrain" )
             basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
alert(basemapStyle);
 }
Basemap

Select a Map Style:

<input type="radio" name="basemapStyle"  value="Satellite" checked onclick=fun(this) /> Satellite
<input type="radio" name="basemapStyle"  value="Roadmap" onclick=fun(this) /> Roadmap
<input type="radio" name="basemapStyle" value="Hybrid" onclick=fun(this) /> Hybrid
<input type="radio" name="basemapStyle"  value="Terrain" onclick=fun(this) /> Terrain

A: Instead of using multiple if statements, you should store all the data in an object an retrieve the values from there. And as already mentioned, an id must be unique. So use classes instead.
Example

var radios = document.querySelectorAll(".basemapStyle");
var basemapStyle = "";

var bmStyles = {
  "Satellite": "&maptype=satellite&scale=4&format=png32&key=xxxx",
  "Roadmap": "&maptype=roadmap&scale=4&format=png32&key=xxxx",
  "Hybrid": "&maptype=hybrid&scale=4&format=png32&key=xxxx",
  "Terrain": "&maptype=terrain&scale=4&format=png32&key=xxxx"
}

for (var i = 0; i < radios.length; i += 1) {
  var radio = radios[i];
  if (radio.checked === true) {
    basemapStyle = bmStyles[radio.value];
    console.log(basemapStyle);
  }
}
Basemap

Select a Map Style:

        <input type="radio" name="basemapStyle" class="basemapStyle" value="Satellite"  /> Satellite

        <input type="radio" name="basemapStyle" class="basemapStyle" value="Roadmap" /> Roadmap

        <input type="radio" name="basemapStyle" class="basemapStyle" value="Hybrid" /> Hybrid

        <input type="radio" name="basemapStyle" class="basemapStyle" value="Terrain" checked/> Terrain

A: In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element.
Check out W3C

A: First assign different ids to the form elements:
<input type="radio" name="basemapStyle" id="basemapStyle_Satellite" value="Satellite" checked /> Satellite
<input type="radio" name="basemapStyle" id="basemapStyle_Roadmap" value="Roadmap"/> Roadmap
<input type="radio" name="basemapStyle" id="basemapStyle_Hybrid" value="Hybrid" /> Hybrid
<input type="radio" name="basemapStyle" id="basemapStyle_Terrain" value="Terrain" /> Terrain

Set the default value to the first value. Then check all other form elements:
var basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
if (document.getElementById('basemapStyle_Roadmap').checked) {
    basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
} else if (document.getElementById('basemapStyle_Hybrid').checked) {
    basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
} else if (document.getElementById('basemapStyle_Terrain').checked) {
    basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
}

A: Firstly, you have used an Assignment Operator [=] in your if statement.
Instead, you have to use a Comparison Operator [==] or [===].
This means that your code if (bmStyle = "Satellite") should be if (bmStyle == "Satellite" )
Read about this on W3 JavaScript Operators Reference.

Secondly, you have assigned the same `ID` to all of your radio buttons; you can't do that. `ID's` are made to make the element unique.

Thirdly, it's neater to assign your `basemapStyle` variable outside of the if statements like so:

// Specify all radio buttons by their 'Unique ID'
var bmStyle1 = document.getElementById("basemapStyle1").value;
var bmStyle2 = document.getElementById("basemapStyle2").value;
var bmStyle3 = document.getElementById("basemapStyle3").value;
var bmStyle4 = document.getElementById("basemapStyle4").value;

// Declared outside
var basemapStyle;

if (bmStyle1 == "Satellite") {
  basemapStyle = "&maptype=satellite&scale=4&format=png32&key=xxxx";
} else if (bmStyle2 == "Roadmap") {
  basemapStyle = "&maptype=roadmap&scale=4&format=png32&key=xxxx";
} else if (bmStyle3 == "Hybrid") {
  basemapStyle = "&maptype=hybrid&scale=4&format=png32&key=xxxx";
} else if (bmStyle4 == "Terrain") {
  basemapStyle = "&maptype=terrain&scale=4&format=png32&key=xxxx";
}

console.log(basemapStyle);
Basemap

Select a Map Style:

    <input type="radio" name="basemapStyle" id="basemapStyle1" value="Satellite" checked /> Satellite
    <input type="radio" name="basemapStyle" id="basemapStyle2" value="Roadmap"/> Roadmap
    <input type="radio" name="basemapStyle" id="basemapStyle3" value="Hybrid" /> Hybrid
    <input type="radio" name="basemapStyle" id="basemapStyle4" value="Terrain" /> Terrain

Follow this JSFiddle link to see an updated and optimized version.


text:
Q: Dynamic allocation of string in shared memory I have 2 programs (writer-reader style) and a shared memory struct established between them + of course the needed semaphores. Struct is:
struct shared_stuff{
    int action;
    char* text;
};

What I want to do is read input from user and then dynamically allocate the text string and read it from the reader end. My writer code narrowed down to the important stuff (ss is a pointer to the shared memory segment cast as a struct shared_stuff*) is this:
ss->text=NULL;
while(1){
    printf("Waiting for user input:\n");
    char input[200];
    fgets(input,200,stdin); //i ignore the '\0' with a loop
    sem_wait(empty);
    ss->action=x;
    ss->text=(char*)realloc(ss->text,sizeof(ss->text)*strlen(input));
    strcpy(ss->text,input);
    sem_post(full);
}

The reader:
while(1){
    sem_wait(full);

    struct shared_stuff *ss;
    ss=(struct shared_stuff*) shared_memory;

    printf("Found action:%d\n",ss->action);
    printf("And text:%s\n",ss->text);

    sem_post(empty);
}

The printf("And text... is never even printed. It is faulty code. When I use the SAME code in the main though it prints the text perfectly.


text:
Q: Need advice on Encrypting whole Hard Disk I need to send private data overseas on a hard disk.
It is 500 GB HDD with Win-7 Ultimate 64 bit.
It has 5 Partitions including system partition.
What is the best & Easiest way of Encrypting the entire hard disk ?
I don't mind spending to Buy any kind of software.
I did look at " Folder Lock " software which allows you to make individual lockers which are encrypted but I don't know how good that encryption is & whether the system partition can encrypted. It doesn't say what algorithm is used. Plus point is that it is fairly easy to use.
Does the type of algorithm make any difference ?
Thanks

A: I use truecrypt in production, 1 year so far no problems.
Update
The stronger the algorithm typically the better the encryption, truecrypt gives you options and usually list them as less secure all the way to paranoid(!).

A: Since you have Windows 7 Ultimate you can use the built-in BitLocker Drive Encryption to help protect all files stored on the drive Windows is installed on (operating system drive) and on fixed data drives (such as internal hard drives). Your can use BitLocker To Go to help protect all files stored on removable data drives (such as external hard drives or USB flash drives).


text:
Q: Three.js engrave a mesh I want to Real-time engrave ring service. So, I want how to engraving ring in Three.js.
I bring a ring in a gltf file.Then I tried ThreeCSG.js and the error is not convex!
This is the example code.
var ring, temp;

THREE.DRACOLoader.setDecoderPath('');
THREE.DRACOLoader.setDecoderConfig({type:'js'});

var loader = new THREE.GLTFLoader();
loader.setDRACOLoader(new THREE.DRACOLoader());
loader.load('files/test.gltf', function(gltf){
    gltf.scene.traverse(function(child)){
        if(child.name === 'ring'){
            child.material = new THREE.MeshStandardMaterial({
                color : 0xffffff
            });
            ring = THREE.CSG.fromMesh(child);
            temp = child;
        }
    }
    scene.add(gltf.scene);
})

function engrave(text){
    var fLoader = new THREE.FontLoader();
    fLoader.load('font.json', function (font){
        var fGeometry = new THREE.TextGeometry(text, {
            ...
        });

        var fMaterial = new THREE.MeshStandardMaterial({
            ...
        });

        var font = new THREE.Mesh(fGeometry, fMaterial);

        var csg = THREE.CSG.fromMesh(font);

        var result = mesh.subtract(csg);

        temp.visible = false;
        scene.add(THREE.CSG.toMesh(result, fMaterial);
    });
}

I wish somebody answer my question.

A: The most commonly available CSG library for THREE has a few issues that make it unusable for some cases.
I have ported my own version of a CSG library that has less of these issues.. perhaps you'd like to try this library instead?
https://github.com/manthrax/THREE-CSGMesh


text:
Q: Regular expression in an Apache Velocity template to check if a string contains a URL I'm trying to write a regular expression in an Apache Velocity template to check if a string contains a URL.
My code is below.  The variable $quoteValue is currently set to contain the string "This is a pullquote test: http://www.google.com"
##Set the regular expression to be used to find a URL
            #set($urlRegex = '(.*)(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?(.*)')
            Is there a match? $quoteValue.matches($urlRegex)

However, the $quoteValue.matches($urlRegex) method always returns false, when I would expect it to return true in this case.  How can I get it to recognise that the string contains a URL? I'm assuming this is something to do with escaping special characters.

A: .matches() is implicitly anchored with ^$
In other words, it only returns true when the entire thing matches.
Replace it with .find().

A: I have managed to resolve this issue using the following code for the regular expression:
#set($urlRegex = '(?s).*(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?.*')

It was the (?s) at the start which made it work!


text:
Q: Prototyping Array to inherit from EventEmitter in Node.js Am currently working on a project where I require to inherit from EventEmitter. I need an array to emit events on certain cases, say, when some length has been exceeded.
I used this snippet:
var events = require('events');
Array.prototype.__proto__ = events.EventEmitter.prototype;

It works fine, but it is said it is anti-pattern.
In another question, it is suggested to use:
util.inherits(Array, events.EventEmitter.prototype);

But it does NOT work. So what is the right way to do this?

A: The problem here is, that this will change all Arrays in your application and not only one. In this situation it would be better to use a new Type that extends from EventEmitter and delegates to an Array.
i.e.
// Create a new object that ...
function MyEventArray() {
    // ...owns an Array as property...
    this.array = new Array();
}

// ... and extends from EventEmitter...
MyEventArray.prototype = Object.create(EventEmitter.prototype);
MyEventArray.prototype.constructor = MyEventArray;

// ... and has functions that delegate to the array.
MyEventArray.prototype.push(obj) {
    this.array.push(obj);
}
...

// This object is an EventEmitter and can be used like an Array:
var myArray = new MyEventArray();
myArray.push(someStuff);


text:
Q: hbase: regionserver is automatically shutdown I have my hbase installed and running on a single node local mode at the moment.
For unknown reason, I can start regionserver but it will be shutdown automatically and rightaway.
Here is the screenshot:

I did not make any configuration in hbase-site.xml
I can still start the hbase shell as below:

How can I get this fixed?
Thank you very much.

A: There's nothing to fix.
If you check the content of /opt/hadoop/hbase/logs/hbase-root-regionserver-xie1.log, you will found logs like bellow:
Not starting a distinct region server because hbase.cluster.distributed is false

In hbase standalone mode, the process HMaster will provide the service.
You can just run bin/start-hbase.sh to start the service.


text:
Q: Getting "FTP server reports 550 Could not get file size." when using FTP URL in fopen I want to read a file which is on a remote ftp server to a variable. I tried reading with address
fopen("ftp://user:pass@localhost/filetoread");

and
$contents = file_get_contents('ftp://ftpuser:123456789@localhost/file.conf');
echo $contents;

Neither does work. I also tried to send directly GET request to the URL which also doesn't work. How can I read the FTP file without downloading?
I checked the php warning which says:

PHP Warning:  file_get_contents(ftp://...@localhost/file.conf): failed to open stream: FTP server reports 550 Could not get file size.
    in /var/www/html/api/listfolder.php on line 2

I'm sure that the file exists

A: The PHP FTP URL wrapper seems to require FTP SIZE command, what your FTP server does not support.
Use the ftp_fget instead:
$conn_id = ftp_connect('hostname');

ftp_login($conn_id, 'username', 'password');
ftp_pasv($conn_id, true);

$h = fopen('php://temp', 'r+');

ftp_fget($conn_id, $h, '/path/to/file', FTP_BINARY, 0);

$fstats = fstat($h);
fseek($h, 0);
$contents = fread($h, $fstats['size']);

fclose($h);
ftp_close($conn_id);

(add error handling)
See PHP: How do I read a .txt file from FTP server into a variable?

A: Based on @Martin Prikryl's answer, here a revised one to work with any url format.
function getFtpUrlBinaryContents($url){
    $path_info = parse_url($url);
    $conn_id = ftp_connect($path_info['host'], $path_info['port'] ?? 21);
    if(isset($path_info['user'])){
        ftp_login($conn_id, $path_info['user'], $path_info['pass'] ?? '');
    }
    ftp_pasv($conn_id, true);

    $h = fopen('php://temp', 'r+');

    ftp_fget($conn_id, $h, $path_info['path'], FTP_BINARY, 0);
    $fstats = fstat($h);
    fseek($h, 0);
    $contents = fread($h, $fstats['size']);
    fclose($h);
    ftp_close($conn_id);
    return $contents;
}
$contents = getFtpUrlBinaryContents('ftp://ftpuser:123456789@localhost/file.conf');
echo $contents;


text:
Q: User not Defined in Models.py Function How do I turn this into a function that can be called from a template?
>>> var1 = coremodels.Recommendation.objects.get(title="test5")
>>> user = User.objects.get(username='admin') // should get self.request.user
>>> var1.vote.exists(user)

Current Attempt:
I currently have it in models.py but getting error global name 'user' not defined:
class Recommendation(models.Model):
    user = models.ForeignKey(User)
    def check_user_voted(self):
        user_voted = self.votes.exists(user)
        return user_voted

This is the html request:
{% if recommendation.check_user_voted %}

User Voted

{% endif %}

A: As long as your function doesn't need parameters, it can be called from templates:
https://docs.djangoproject.com/en/1.8/topics/templates/#variables
In your check_user_voted function, user is not defined. It should be:
def check_user_voted(self):
    user_voted = self.votes.exists(self.user)
    return user_voted

A: To call a function from template, you need to use the decorator @property
class Recommendation(models.Model):
    ...

    @property
    def check_user_voted(self):
        ....
        return something

Then you call it from a Recommendation object: reco_object.check_user_voted
Finally, to reference the user associated to the current recommendation object, you need to use self.user which will return the User object once the recommendation object has one associated.
def check_user_voted(self):
    user_voted = self.votes.exists(self.user)
    return user_voted


text:
Q: Dark filled Links being displayed when downloading d3 hierarchical edge bundling visualization as PNG I have created a D3 hierarchical edge bundling visualization.When i download this visualization as PNG,the links in downloaded image are filled with dark color which is not displayed in actual visualization.
Downloaded image is
Actual visualization being displayed is

How to get the same visualization in downloaded image.
My current code is:
<html>
    <head>

        <style>
            .node {
              font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
            }
            .link {
              stroke: steelblue;
              stroke-opacity: .4;
              fill: none;
            }
        </style>

    </head>
    <body>
            <script src="http://d3js.org/d3.v3.min.js"></script>
            <script>
            var classes=[
{"name":"a","size":3938,"imports":["b","f"]},
{"name":"b","size":3938,"imports":[]},
{"name":"c","size":3938,"imports":["a"]},
{"name":"d","size":3938,"imports":[]},
{"name":"e","size":3938,"imports":[]},
{"name":"f","size":3938,"imports":[]}

];
                    var diameter = 700,
                        radius = diameter / 2,
                        innerRadius = radius - 120;
                    var cluster = d3.layout.cluster()
                        .size([360, innerRadius]);

                    var bundle = d3.layout.bundle();

                    var line = d3.svg.line.radial()
                        .interpolate("bundle")
                        .tension(.85)
                        .radius(function(d) { return d.y; })
                        .angle(function(d) { return d.x / 180 * Math.PI; });

                    var svg = d3.select("body").append("svg")
                    .attr("id","networkSvg")
                        .attr("width", diameter)
                        .attr("height", diameter)
                      .append("g")
                        .attr("transform", "translate(" + radius + "," + radius + ")");

                      var nodes = cluster.nodes(packageHierarchy(classes)),
                          links = packageImports(nodes);

                      svg.selectAll(".link")
                          .data(bundle(links))
                        .enter().append("path")
                          .attr("class", "link")
                          .attr("d", line);

                      svg.selectAll(".node")
                          .data(nodes.filter(function(n) { return !n.children; }))
                        .enter().append("g")
                          .attr("class", "node")
                          .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
                        .on("mouseover", function(d){
                          d3.selectAll(".node").style("fill", "black");
                          d3.selectAll(".link").style("stroke", "steelblue");
                          colorSource(d.name);

                          d.imports.forEach(function(name){
                            colorTarget(name);
                            colorOutgoingLink(d.name, name);
                          });

                          d.parent.children.forEach(function(data){
                              if(data.imports.indexOf(d.name)>-1)
                              {
                                colorTarget(data.name);
                                colorIncomingLink(data.name, d.name);
                              }
                          });
                        })
                        .on("mouseout",function(d)
                        {
                          d3.selectAll(".node").style("fill", "black");
                          d3.selectAll(".link").style("stroke", "steelblue");

                        })
                        .append("text")
                          .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
                          .attr("dy", ".31em")
                          .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
                          .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; })
                          .text(function(d) { return d.key; });

                    // Lazily construct the package hierarchy from class names.

                    function packageHierarchy(classes) {
                      var map = {};
                      function find(name, data) {
                        var node = map[name], i;
                        if (!node) {
                          node = map[name] = data || {name: name, children: []};
                          if (name.length) {
                            node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
                            node.parent.children.push(node);
                            node.key = name.substring(i + 1);
                          }
                        }
                        return node;
                      }
                      classes.forEach(function(d) {
                        find(d.name, d);
                      });
                      return map[""];
                    }

                    // Return a list of imports for the given array of nodes.
                    function packageImports(nodes) {
                      var map = {},
                          imports = [];
                      // Compute a map from name to node.
                      nodes.forEach(function(d) {
                        map[d.name] = d;
                      });
                      // For each import, construct a link from the source to target node.
                      nodes.forEach(function(d) {
                        if (d.imports) d.imports.forEach(function(i) {
                          imports.push({source: map[d.name], target: map[i]});
                        });
                      });
                      return imports;
                    }

                    function colorIncomingLink(src,tgt){
                      var link = d3.selectAll(".link")[0].filter(function(d){
                        return (d3.select(d).data()[0][0].name == src && d3.select(d).data()[0][2].name == tgt);
                      });
                      d3.selectAll(link).style("stroke", "green");
                    }

                    function colorOutgoingLink(src,tgt){
                      var link = d3.selectAll(".link")[0].filter(function(d){
                        return (d3.select(d).data()[0][0].name == src && d3.select(d).data()[0][2].name == tgt);
                      });
                      d3.selectAll(link).style("stroke", "red");
                    }

                    function colorTarget(name){
                      //iterate through all teh dom and get the DOM which has the data
                      var node = d3.selectAll(".node")[0].filter(function(d){
                        return d3.select(d).data()[0].name == name;
                      });
                      d3.selectAll(node).style("fill", "red");
                    }

                    function colorSource(name){
                      //iterate through all teh dom and get teh DOM which has the data
                      var node = d3.selectAll(".node")[0].filter(function(d){
                        return d3.select(d).data()[0].name == name;
                      });
                      d3.selectAll(node).style("fill", "green");
                    }

                     function download()
                    {

                        img = new Image(),
                        serializer = new XMLSerializer(),
                        svgStr = serializer.serializeToString(document.getElementById('networkSvg'));

                    img.src = 'data:image/svg+xml;base64,'+window.btoa(svgStr);

                    // You could also use the actual string without base64 encoding it:
                    //img.src = "data:image/svg+xml;utf8," + svgStr;

                    var canvas = document.createElement("canvas");

                    var w=2000;
                    var h=2000;

                    canvas.width = w;
                    canvas.height = h;
                    canvas.getContext("2d").drawImage(img,0,0,w,h);

                    var imgURL = canvas.toDataURL("image/png");

                var dlLink = document.createElement('a');
                    dlLink.download = "down";
                    dlLink.href = imgURL;
                    dlLink.dataset.downloadurl = ["image/png", dlLink.download, dlLink.href].join(':');

                    document.body.appendChild(dlLink);
                    dlLink.click();
                    document.body.removeChild(dlLink);

                    }
                    </script>
                    <button onclick="download()">Download</button>

    </body>
</html>

A: As mentioned by Cyril, you can set all styles through d3 rather than using external style sheet.
Here is the working code snippet.

var classes = [{
    "name": "a",
    "size": 3938,
    "imports": ["b", "f"]
  }, {
    "name": "b",
    "size": 3938,
    "imports": []
  }, {
    "name": "c",
    "size": 3938,
    "imports": ["a"]
  }, {
    "name": "d",
    "size": 3938,
    "imports": []
  }, {
    "name": "e",
    "size": 3938,
    "imports": []
  }, {
    "name": "f",
    "size": 3938,
    "imports": []
  }

];
var diameter = 700,
  radius = diameter / 2,
  innerRadius = radius - 120;
var cluster = d3.layout.cluster()
  .size([360, innerRadius]);

var bundle = d3.layout.bundle();

var line = d3.svg.line.radial()
  .interpolate("bundle")
  .tension(.85)
  .radius(function(d) {
    return d.y;
  })
  .angle(function(d) {
    return d.x / 180 * Math.PI;
  });

var svg = d3.select("body").append("svg")
  .attr("id", "networkSvg")
  .attr("width", diameter)
  .attr("height", diameter)
  .style("background-color","white")
  .append("g")
  .attr("transform", "translate(" + radius + "," + radius + ")");

var nodes = cluster.nodes(packageHierarchy(classes)),
  links = packageImports(nodes);

svg.selectAll(".link")
  .data(bundle(links))
  .enter().append("path")
  .attr("class", "link")
  .style("stroke", "steelblue")
  .style("stroke-opacity", .4)
  .style("fill", "none")
  .attr("d", line);

svg.selectAll(".node")
  .data(nodes.filter(function(n) {
    return !n.children;
  }))
  .enter().append("g")
  .attr("class", "node")
  .style("font", "11px Helvetica Neue Helvetica, Arial, sans-serif")
  .attr("transform", function(d) {
    return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
  })
  .on("mouseover", function(d) {
    d3.selectAll(".node").style("fill", "black");
    d3.selectAll(".link").style("stroke", "steelblue");
    colorSource(d.name);

    d.imports.forEach(function(name) {
      colorTarget(name);
      colorOutgoingLink(d.name, name);
    });

    d.parent.children.forEach(function(data) {
      if (data.imports.indexOf(d.name) > -1) {
        colorTarget(data.name);
        colorIncomingLink(data.name, d.name);
      }
    });
  })
  .on("mouseout", function(d) {
    d3.selectAll(".node").style("fill", "black");
    d3.selectAll(".link").style("stroke", "steelblue");

  })
  .append("text")
  .style("stroke","black")
  .attr("dx", function(d) {
    return d.x < 180 ? 8 : -8;
  })
  .attr("dy", ".31em")
  .attr("text-anchor", function(d) {
    return d.x < 180 ? "start" : "end";
  })
  .attr("transform", function(d) {
    return d.x < 180 ? null : "rotate(180)";
  })
  .text(function(d) {
    return d.key;
  });

// Lazily construct the package hierarchy from class names.

function packageHierarchy(classes) {
  var map = {};

  function find(name, data) {
    var node = map[name],
      i;
    if (!node) {
      node = map[name] = data || {
        name: name,
        children: []
      };
      if (name.length) {
        node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
        node.parent.children.push(node);
        node.key = name.substring(i + 1);
      }
    }
    return node;
  }
  classes.forEach(function(d) {
    find(d.name, d);
  });
  return map[""];
}

// Return a list of imports for the given array of nodes.
function packageImports(nodes) {
  var map = {},
    imports = [];
  // Compute a map from name to node.
  nodes.forEach(function(d) {
    map[d.name] = d;
  });
  // For each import, construct a link from the source to target node.
  nodes.forEach(function(d) {
    if (d.imports) d.imports.forEach(function(i) {
      imports.push({
        source: map[d.name],
        target: map[i]
      });
    });
  });
  return imports;
}

function colorIncomingLink(src, tgt) {
  var link = d3.selectAll(".link")[0].filter(function(d) {
    return (d3.select(d).data()[0][0].name == src && d3.select(d).data()[0][2].name == tgt);
  });
  d3.selectAll(link).style("stroke", "green");
}

function colorOutgoingLink(src, tgt) {
  var link = d3.selectAll(".link")[0].filter(function(d) {
    return (d3.select(d).data()[0][0].name == src && d3.select(d).data()[0][2].name == tgt);
  });
  d3.selectAll(link).style("stroke", "red");
}

function colorTarget(name) {
  //iterate through all teh dom and get the DOM which has the data
  var node = d3.selectAll(".node")[0].filter(function(d) {
    return d3.select(d).data()[0].name == name;
  });
  d3.selectAll(node).style("fill", "red");
}

function colorSource(name) {
  //iterate through all teh dom and get teh DOM which has the data
  var node = d3.selectAll(".node")[0].filter(function(d) {
    return d3.select(d).data()[0].name == name;
  });
  d3.selectAll(node).style("fill", "green");
}

function download() {

  img = new Image(),
    serializer = new XMLSerializer(),
    svgStr = serializer.serializeToString(document.getElementById('networkSvg'));

  img.src = 'data:image/svg+xml;base64,' + window.btoa(svgStr);

  // You could also use the actual string without base64 encoding it:
  //img.src = "data:image/svg+xml;utf8," + svgStr;

  var canvas = document.createElement("canvas");

  var w = 2000;
  var h = 2000;

  canvas.width = w;
  canvas.height = h;
  canvas.getContext("2d").drawImage(img, 0, 0, w, h);

  var imgURL = canvas.toDataURL("image/png");

  var dlLink = document.createElement('a');
  dlLink.download = "down";
  dlLink.href = imgURL;
  dlLink.dataset.downloadurl = ["image/png", dlLink.download, dlLink.href].join(':');

  document.body.appendChild(dlLink);
  dlLink.click();
  document.body.removeChild(dlLink);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<button onclick="download()">Download</button>


text:
Q: Azure DevOps pipelines and Team Foundation Server workflow We are using Azure DevOps for our .NET source control. We operate projects using both the Git and TFS workflow (the former being newer work, the latter being legacy projects). This has come about because when Azure DevOps was simply TFS, we just had the 'Source' root folder, with sub folders for different types of software, and then projects within each. This works fine for the type of check in / commit process used by TFS. Now with DevOps and the Git workflow, instead of a single 'Root' repository called Source with folders breaking up the different solutions, we have different repositories representing each different software solution.
For the projects under the GIT workflow, we can use Azure pipelines confidently to create a CI/CD release process. However, I'm unsure how we can use this to work with our TFS based repository. In the Azure DevOps portal, our TFS repository - even though it contains many different solutions/projects, is represented as a single 'Project' called 'Source' in the portal.
This means that I'm unclear how to get a CI/CD pipeline to work, as we only want to build the pipeline for certain projects within that \Source project. Does anyone know how this can be achieved? If we look at the Git projects its easy, each project is separate and self contained, but \Source is made up of folders and sub-folders with projects within each. It's not one massive project that can be checked into and released from. I hope this makes sense, perhaps someone with some past experience with this 'dual workflow' type of source control in Azure DevOps could comment?

A: You can create multiple Azure Pipelines that each look at the TFVC repository (Team Foundation Version Control). Each Pipeline is then configured with its own Mapping where you'll have to be pretty specific to grab just the files you need to build the solution for that pipeline.
You can define a Workspace Mapping using includes (map) and excludes (cloak). You can cloak individual files, but you'll have to enter their server path manually last time I checked.

The next step is to configure the CI filters to look at the right paths. This could be the same as your workspace mappings, but I've also seen cases where more specific filters were configured.

You'll end up with one or more pipelines for each Solution in the project that hosts the TFVC repository. Naming your pipelines will probably be important.