问:
Strange behavior while scaling treatments over many CPUs
I am studying performances while scaling java code over many CPUs. For that, I wrote a simple program that runs 50000 fibonacci on one thread, then 2*50000 on two threads, 3*50000 on three threads and so on, until the number of CPU of the target host is reached.

Here is my code:

```<code>import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadScalability {

    static final int MAX_THREADS = 4;
    static final int NB_RUN_PER_THREAD = 50000;
    static final int FIBO_VALUE = 25;

    public static void main(String[] args) {
        MultiThreadScalability multiThreadScalability = new MultiThreadScalability();
        multiThreadScalability.runTest();
    }

    private void runTest() {
        int availableProcs = Runtime.getRuntime().availableProcessors();
        System.out.println(availableProcs + " processors available");

        for (int i = 1 ; i <= availableProcs ; i++) {
            System.out.println("Running scalability test for " + i + " threads");
            long timeInMillisecs = runTestForThreads(i);
            System.out.println("=> " + timeInMillisecs + " milli-seconds");
        }
    }

    private long runTestForThreads(int threadsNumber) {
        final int nbRun = NB_RUN_PER_THREAD * threadsNumber;
        ExecutorService executor = Executors.newFixedThreadPool(threadsNumber);

        long startTime = System.currentTimeMillis();

        for (int i = 0 ; i < nbRun ; i++) {
            Runnable worker = new Runnable()
            {
                public void run()
                {
                    fibo(FIBO_VALUE);
                }
            };

            executor.execute(worker);
        }

        executor.shutdown();

        while (!executor.isTerminated())
        {}

        return (System.currentTimeMillis() - startTime);
    }

    private static long fibo(int n) {
        if (n < 2) {
            return (n);
        }

        return (fibo(n - 1) + fibo(n - 2));
    }

}
</code>```

In the given condtions, I expected that - independent of the number of threads - the execution time remain constant.

I ran it on a power-full machine and I had the following output:

```<code>48 processors available
Running scalability test for 1 threads
=> 34199 milli-seconds
Running scalability test for 2 threads
=> 34141 milli-seconds
Running scalability test for 3 threads
=> 34009 milli-seconds
Running scalability test for 4 threads
=> 34000 milli-seconds
Running scalability test for 5 threads
=> 34034 milli-seconds
Running scalability test for 6 threads
=> 34086 milli-seconds
Running scalability test for 7 threads
=> 34094 milli-seconds
Running scalability test for 8 threads
=> 34673 milli-seconds
Running scalability test for 9 threads
=> 35297 milli-seconds
Running scalability test for 10 threads
=> 35486 milli-seconds
Running scalability test for 11 threads
=> 35913 milli-seconds
Running scalability test for 12 threads
=> 36324 milli-seconds
Running scalability test for 13 threads
=> 35722 milli-seconds
Running scalability test for 14 threads
=> 35750 milli-seconds
Running scalability test for 15 threads
=> 35634 milli-seconds
Running scalability test for 16 threads
=> 35970 milli-seconds
Running scalability test for 17 threads
=> 37914 milli-seconds
Running scalability test for 18 threads
=> 36560 milli-seconds
Running scalability test for 19 threads
=> 36720 milli-seconds
Running scalability test for 20 threads
=> 37028 milli-seconds
Running scalability test for 21 threads
=> 37381 milli-seconds
Running scalability test for 22 threads
=> 37529 milli-seconds
Running scalability test for 23 threads
=> 37632 milli-seconds
Running scalability test for 24 threads
=> 39942 milli-seconds
Running scalability test for 25 threads
=> 40090 milli-seconds
Running scalability test for 26 threads
=> 41238 milli-seconds
Running scalability test for 27 threads
=> 42336 milli-seconds
Running scalability test for 28 threads
=> 43377 milli-seconds
Running scalability test for 29 threads
=> 44394 milli-seconds
Running scalability test for 30 threads
=> 46245 milli-seconds
Running scalability test for 31 threads
=> 45928 milli-seconds
Running scalability test for 32 threads
=> 47490 milli-seconds
Running scalability test for 33 threads
=> 47674 milli-seconds
Running scalability test for 34 threads
=> 48775 milli-seconds
Running scalability test for 35 threads
=> 56456 milli-seconds
Running scalability test for 36 threads
=> 50557 milli-seconds
Running scalability test for 37 threads
=> 51393 milli-seconds
Running scalability test for 38 threads
=> 52971 milli-seconds
Running scalability test for 39 threads
=> 53077 milli-seconds
Running scalability test for 40 threads
=> 54015 milli-seconds
Running scalability test for 41 threads
=> 55924 milli-seconds
Running scalability test for 42 threads
=> 55560 milli-seconds
Running scalability test for 43 threads
=> 56554 milli-seconds
Running scalability test for 44 threads
=> 57073 milli-seconds
Running scalability test for 45 threads
=> 65193 milli-seconds
Running scalability test for 46 threads
=> 58549 milli-seconds
Running scalability test for 47 threads
=> 59302 milli-seconds
Running scalability test for 48 threads
=> 60662 milli-seconds
</code>```

The time remains almost the same until 24 threads. The it becomes slower and slower You can see it on this graph

I asking for help in order to understand why such a "break" happens

Last but not least, the CPU configuration of the host on which I ran the test is the following one:

```<code>$ cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 46
model name      : Intel(R) Xeon(R) CPU           E7540  @ 2.00GHz
stepping        : 6
cpu MHz         : 1997.885
cache size      : 18432 KB
physical id     : 0
siblings        : 12
core id         : 0
cpu cores       : 6
apicid          : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 11
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat p
se36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc id
a nonstop_tsc pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lah
f_lm
bogomips        : 3995.77
clflush size    : 64
cache_alignment : 64
address sizes   : 44 bits physical, 48 bits virtual
power management: [8]
</code>```

Here, I see that the real number of cores is only 6. Runtime.getRuntime().availableProcessors() does not return the number of pysical CPU but the number of "hyper-threads": 48

Do you think it can explain the "break" I observe at 24 threads?

答:
With hyper-threading enabled you have 1 physical core running 2  "hardware threads" and they count as a logical processor each.

So your machine have 24 physical cores and 48 logical CPUs (easier to see with command lscpu)

Now, the two hardware threads shares the resources of a physical core.

There are resources that are duplicated, shared and partitioned.

It depends on the CPU but usually register state and instruction queues are duplicated, L1 cache and execution units are shared and store/reorder buffers are partitioned.

Usually hyperthreading only give an advantage if the CPU spends good time waiting for (cached) memory.

The OS should try to avoid putting load on a hyper-threaded sibling when there are physcal cores free to use.

Your example is highly CPU intensive, and once the OS starts scheduling two software threads on the same physical CPU core, then the 2 threads start fighting for the same execution units, reducing the scalability.

Body:
I am studying performances while scaling java code over many CPUs. For that, I wrote a simple program that runs 50000 fibonacci on one thread, then 2*50000 on two threads, 3*50000 on three threads and so on, until the number of CPU of the target host is reached.

Here is my code:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MultiThreadScalability {

    static final int MAX_THREADS = 4;
    static final int NB_RUN_PER_THREAD = 50000;
    static final int FIBO_VALUE = 25;

    public static void main(String[] args) {
        MultiThreadScalability multiThreadScalability = new MultiThreadScalability();
        multiThreadScalability.runTest();
    }

    private void runTest() {
        int availableProcs = Runtime.getRuntime().availableProcessors();
        System.out.println(availableProcs + " processors available");

        for (int i = 1 ; i <= availableProcs ; i++) {
            System.out.println("Running scalability test for " + i + " threads");
            long timeInMillisecs = runTestForThreads(i);
            System.out.println("=> " + timeInMillisecs + " milli-seconds");
        }
    }

    private long runTestForThreads(int threadsNumber) {
        final int nbRun = NB_RUN_PER_THREAD * threadsNumber;
        ExecutorService executor = Executors.newFixedThreadPool(threadsNumber);

        long startTime = System.currentTimeMillis();

        for (int i = 0 ; i < nbRun ; i++) {
            Runnable worker = new Runnable()
            {
                public void run()
                {
                    fibo(FIBO_VALUE);
                }
            };

            executor.execute(worker);
        }

        executor.shutdown();

        while (!executor.isTerminated())
        {}

        return (System.currentTimeMillis() - startTime);
    }

    private static long fibo(int n) {
        if (n < 2) {
            return (n);
        }

        return (fibo(n - 1) + fibo(n - 2));
    }

}

In the given condtions, I expected that - independent of the number of threads - the execution time remain constant.

I ran it on a power-full machine and I had the following output:

48 processors available
Running scalability test for 1 threads
=> 34199 milli-seconds
Running scalability test for 2 threads
=> 34141 milli-seconds
Running scalability test for 3 threads
=> 34009 milli-seconds
Running scalability test for 4 threads
=> 34000 milli-seconds
Running scalability test for 5 threads
=> 34034 milli-seconds
Running scalability test for 6 threads
=> 34086 milli-seconds
Running scalability test for 7 threads
=> 34094 milli-seconds
Running scalability test for 8 threads
=> 34673 milli-seconds
Running scalability test for 9 threads
=> 35297 milli-seconds
Running scalability test for 10 threads
=> 35486 milli-seconds
Running scalability test for 11 threads
=> 35913 milli-seconds
Running scalability test for 12 threads
=> 36324 milli-seconds
Running scalability test for 13 threads
=> 35722 milli-seconds
Running scalability test for 14 threads
=> 35750 milli-seconds
Running scalability test for 15 threads
=> 35634 milli-seconds
Running scalability test for 16 threads
=> 35970 milli-seconds
Running scalability test for 17 threads
=> 37914 milli-seconds
Running scalability test for 18 threads
=> 36560 milli-seconds
Running scalability test for 19 threads
=> 36720 milli-seconds
Running scalability test for 20 threads
=> 37028 milli-seconds
Running scalability test for 21 threads
=> 37381 milli-seconds
Running scalability test for 22 threads
=> 37529 milli-seconds
Running scalability test for 23 threads
=> 37632 milli-seconds
Running scalability test for 24 threads
=> 39942 milli-seconds
Running scalability test for 25 threads
=> 40090 milli-seconds
Running scalability test for 26 threads
=> 41238 milli-seconds
Running scalability test for 27 threads
=> 42336 milli-seconds
Running scalability test for 28 threads
=> 43377 milli-seconds
Running scalability test for 29 threads
=> 44394 milli-seconds
Running scalability test for 30 threads
=> 46245 milli-seconds
Running scalability test for 31 threads
=> 45928 milli-seconds
Running scalability test for 32 threads
=> 47490 milli-seconds
Running scalability test for 33 threads
=> 47674 milli-seconds
Running scalability test for 34 threads
=> 48775 milli-seconds
Running scalability test for 35 threads
=> 56456 milli-seconds
Running scalability test for 36 threads
=> 50557 milli-seconds
Running scalability test for 37 threads
=> 51393 milli-seconds
Running scalability test for 38 threads
=> 52971 milli-seconds
Running scalability test for 39 threads
=> 53077 milli-seconds
Running scalability test for 40 threads
=> 54015 milli-seconds
Running scalability test for 41 threads
=> 55924 milli-seconds
Running scalability test for 42 threads
=> 55560 milli-seconds
Running scalability test for 43 threads
=> 56554 milli-seconds
Running scalability test for 44 threads
=> 57073 milli-seconds
Running scalability test for 45 threads
=> 65193 milli-seconds
Running scalability test for 46 threads
=> 58549 milli-seconds
Running scalability test for 47 threads
=> 59302 milli-seconds
Running scalability test for 48 threads
=> 60662 milli-seconds

The time remains almost the same until 24 threads. The it becomes slower and slower You can see it on this graph

I asking for help in order to understand why such a "break" happens

Last but not least, the CPU configuration of the host on which I ran the test is the following one:

$ cat /proc/cpuinfo
processor       : 0
vendor_id       : GenuineIntel
cpu family      : 6
model           : 46
model name      : Intel(R) Xeon(R) CPU           E7540  @ 2.00GHz
stepping        : 6
cpu MHz         : 1997.885
cache size      : 18432 KB
physical id     : 0
siblings        : 12
core id         : 0
cpu cores       : 6
apicid          : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 11
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat p
se36 clflush dts acpi mmx fxsr sse sse2 ss ht tm syscall nx rdtscp lm constant_tsc id
a nonstop_tsc pni monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr sse4_1 sse4_2 popcnt lah
f_lm
bogomips        : 3995.77
clflush size    : 64
cache_alignment : 64
address sizes   : 44 bits physical, 48 bits virtual
power management: [8]

Here, I see that the real number of cores is only 6. Runtime.getRuntime().availableProcessors() does not return the number of pysical CPU but the number of "hyper-threads": 48

Do you think it can explain the "break" I observe at 24 threads?


来源: stackexchange

问:
How to place a Xul window as "Always On Top"?
I found this file at google code with the function:

```<code>function SetAlwaysOnTop() {
    var chkTop = document.getElementById("itmAlwaysOnTop");
    var xulWin = window.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem)
        .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIXULWindow);
    if(chkTop.getAttribute("checked") == "true") {
        xulWin.zLevel = xulWin.raisedZ;
    } else {
        xulWin.zLevel = xulWin.normalZ;
    }
}
</code>```

The parts of it that I need are just:

```<code>var xulWin = window.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem)
        .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIXULWindow);
xulWin.zLevel = xulWin.raisedZ;
</code>```

But I'm not finding what where's the Ci defined. Any idea what can it be? Or any other idea of how to set a window always on top? (that solution "just for windows" don't fits to me).

--update

I'm reading about the nsIWindowMediator, which has some methods to handle the window Z order. But it's saying that the methods should be used from c++, not javascript. That means the code should be used from XPCOM components (I should as XPCOM component to open the window)? Does anyone that already used it could confirm?

I'm still reading anyway.

--update

I've tried the nsIWindowMediator (with a XPCOM component) but it just does nothing when I set the Z level.

Still look for a way to put the window aways on top..

--attempt with 'alwaysraised':

test.xul:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    onload="open('top.xul','GreenfoxChannelWindow','chrome, alwaysraised');"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <label value="MAIN WINDOW"/>

</window>
</code>```

top.xul:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <label value="ON TOP"/>

</window>
</code>```

didn't worked.

--attempt with 'zlevel':

test.xul:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    onload="open('top.xul','GreenfoxChannelWindow','chrome');"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <label value="MAIN WINDOW"/>

</window>
</code>```

top.xul:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300" zlevel="6"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

    <label value="ON TOP"/>

</window>
</code>```

didn't worked. Nither with alwaysraised setted, or adding a higher or lower zlevel to the test.xul (with top.xul zlevel="6")

答:
If you always want the window to be on top, then the easiest way is to use the alwaysraised chrome flag when opening the window.

If you don't get to open the window yourself, the second easiest way is to use <window zlevel="6"> in your XUL. You can even persist the zlevel; SeaMonkey's Help window does this, using a context menu option to toggle the zLevel.

By the way, Ci is a common abbreviation for Components.interfaces since writing (e.g.) Components.interfaces.nsIXULWindow.rasiedZ is difficult to do on 80-character lines.

ContentLicense: CC BY-SA 2.5

Body:
I found this file at google code with the function:

function SetAlwaysOnTop() {
    var chkTop = document.getElementById("itmAlwaysOnTop");
    var xulWin = window.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem)
        .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIXULWindow);
    if(chkTop.getAttribute("checked") == "true") {
        xulWin.zLevel = xulWin.raisedZ;
    } else {
        xulWin.zLevel = xulWin.normalZ;
    }
}

The parts of it that I need are just:

var xulWin = window.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem)
        .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor)
        .getInterface(Ci.nsIXULWindow);
xulWin.zLevel = xulWin.raisedZ;

But I'm not finding what where's the Ci defined. Any idea what can it be? Or any other idea of how to set a window always on top? (that solution "just for windows" don't fits to me).

--update

I'm reading about the nsIWindowMediator, which has some methods to handle the window Z order. But it's saying that the methods should be used from c++, not javascript. That means the code should be used from XPCOM components (I should as XPCOM component to open the window)? Does anyone that already used it could confirm?

I'm still reading anyway.

--update

I've tried the nsIWindowMediator (with a XPCOM component) but it just does nothing when I set the Z level.

Still look for a way to put the window aways on top..

--attempt with 'alwaysraised':

test.xul:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    onload="open('top.xul','GreenfoxChannelWindow','chrome, alwaysraised');"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

</window>

top.xul:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

</window>

didn't worked.

--attempt with 'zlevel':

test.xul:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300"
    onload="open('top.xul','GreenfoxChannelWindow','chrome');"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

</window>

top.xul:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="400" height="300" zlevel="6"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

</window>

didn't worked. Nither with alwaysraised setted, or adding a higher or lower zlevel to the test.xul (with top.xul zlevel="6")


问:
Django rest framework: unit testing database issue
I am doing unit testing of the rest Apis. I am using django rest framework.
Apis are saving data into and getting data from the database. Both of the operations are not working or if it is working i am not able to see that in the databases. Apis are also using django-fsm, because of which i need same data from the db for the other tests. Tests depends on previous tests due to django-fsm. There is always state changing with the api. But now i am not able to see any data in database during test runs. Don't know where it is saving the data or in which database.

Below is my test settings:-

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': join(PROJECT_ROOT, 'run', 'db_for_testing.sqlite3'),
    'TEST': {
        'NAME': 'test_db_for_testing',
    },
 },
}
</code>```

below is my api:-

```<code>class DummyView(CreateAPIView):
    def post(self, request, *args, **kwargs):
        data = request.data.copy()
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        order = self.model(book=serializer.data.get('book'))
        order.save()
        data = {
        'status_code': 200,
        'message': 'successfully.'
        }
        return Response(data, status=status.HTTP_200_OK)
</code>```

As my tests depends on the previous test saving the data to db, so the other tests also fails. I am using APITestCase of rest_framework.
Help guys.
thanks in advance.

答:
TL;DR - Solution: Use SimpleTestCase - See example below

Explanation

The thing is that the recommended test classes provided by Django for tests involving database queries, TransactionTestCase and the subclass TestCase, wraps every test in a transaction to speed up the process of resetting the database after each test. Source: Django TransactionTestCase docs

It is possible to avoid this behaviour by using SimpleTestCase which is the parent class of TransactionTestCase. You then have to specify explicitly that you want to allow database queries by setting allow_database_queries to True-

Also note that you are then responsible for any cleaning that needs to be done after the test. You can do that by overriding the tearDownClass class method. Similarly there's a setUpClass class method for any initialization prior to running the test. Remember to call the super methods. See full details in the docs

Example

```<code>from django.test import SimpleTestCase

class MyTestCase(SimpleTestCase):
    allow_database_queries = True

    @classmethod
    def setUpClass(cls):
        # Do your pre test initialization here.
        super(MyTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        # Do your post test clean uphere.
        super(MyTestCase, cls).tearDownClass()

    def test_add_data_through_api(self):
        # Add 'dat data
        ...

    def test_work_with_data_from_previous_test(self):
        # Work 'dat data
        ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am doing unit testing of the rest Apis. I am using django rest framework.
Apis are saving data into and getting data from the database. Both of the operations are not working or if it is working i am not able to see that in the databases. Apis are also using django-fsm, because of which i need same data from the db for the other tests. Tests depends on previous tests due to django-fsm. There is always state changing with the api. But now i am not able to see any data in database during test runs. Don't know where it is saving the data or in which database.

Below is my test settings:-

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': join(PROJECT_ROOT, 'run', 'db_for_testing.sqlite3'),
    'TEST': {
        'NAME': 'test_db_for_testing',
    },
 },
}

below is my api:-

class DummyView(CreateAPIView):
    def post(self, request, *args, **kwargs):
        data = request.data.copy()
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        order = self.model(book=serializer.data.get('book'))
        order.save()
        data = {
        'status_code': 200,
        'message': 'successfully.'
        }
        return Response(data, status=status.HTTP_200_OK)

As my tests depends on the previous test saving the data to db, so the other tests also fails. I am using APITestCase of rest_framework.
Help guys.
thanks in advance.

Body:
TL;DR - Solution: Use SimpleTestCase - See example below

Explanation

The thing is that the recommended test classes provided by Django for tests involving database queries, TransactionTestCase and the subclass TestCase, wraps every test in a transaction to speed up the process of resetting the database after each test. Source: Django TransactionTestCase docs

It is possible to avoid this behaviour by using SimpleTestCase which is the parent class of TransactionTestCase. You then have to specify explicitly that you want to allow database queries by setting allow_database_queries to True-

Also note that you are then responsible for any cleaning that needs to be done after the test. You can do that by overriding the tearDownClass class method. Similarly there's a setUpClass class method for any initialization prior to running the test. Remember to call the super methods. See full details in the docs

Example

from django.test import SimpleTestCase

class MyTestCase(SimpleTestCase):
    allow_database_queries = True

    @classmethod
    def setUpClass(cls):
        # Do your pre test initialization here.
        super(MyTestCase, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        # Do your post test clean uphere.
        super(MyTestCase, cls).tearDownClass()

    def test_add_data_through_api(self):
        # Add 'dat data
        ...

    def test_work_with_data_from_previous_test(self):
        # Work 'dat data
        ...


问:
How to deal with properties and their default values inside the class?
I create a class with strict properties' types, their values can be passed to constructor:

```<code>declare(strict_types=1);

class Position
{
    protected $hours;
    protected $minutes;
    protected $seconds;
    protected $frames;

    public function __construct(int $hours = 0, int $minutes = 0, int $seconds = 0, int $frames = 0)
    {
        $this->setHours($hours);
        $this->setMinutes($minutes);
        $this->setSeconds($seconds);
        $this->setFrames($frames);
    }

    public function getHours(): int
    {
        return $this->hours;
    }

    public function setHours(int $hours): void
    {
        $this->hours = $hours;
    }

    // and so on...
}
</code>```

Is it good to set properties' values with setters inside the constructor?

Is it good to get their values inside class' methods with getters?

Where it would be better to set the default properties' values: explicitly initialize properties with them, set them as default arguments values (as it's done for now) or specify them in both places?

Thanks.

答:
Is it good to set properties' values with setters inside the constructor?

In other words: is it ok to delegate to a setter when initializing a property in the constructor? The short answer is: It doesn't really matter. If there is no validation (other than the type) made, then there's really no point in it, but there's also no downside. If the is more validation to be made, then one could make the point that it keeps the constructor clean while reducing the amount of duplicate code. If there is additional checks to be made, then delegating to the setter for the common validation and implementing the additional one in the constructor will help keep the two workflows separate.

In the end, I don't think there's really a concern here. It's neither good nor bad practice to do it. Do what feels best for your specific use case.

Is it good to get their values inside class' methods with getters?

If you mean "should I access object properties through getters", then: Yes. A thousand times yes. Object properies should always be private and accessed through getters. Public properties violate one of the core concepts of Object-Oriented: Encapsulation. Whether or not each member has a getter and has logic or not is completely up to you and will depend on the use case.

if you mean "should I use the getter to access a propery from within the object" then it really doesn't matter and depends on the scenario. There may be times where using the public getter makes no practical sense and doesn't help the readability/maintainability of the code. There may be cases where it totally makes sense to call the public getter. For example when dealing with a function in the style of isFoo() which returns true or false based on a couple of conditions, it makes sense to simply call isFoo() instead of repeating the conditions again.

Where it would be better to set the default properties' values: explicitly initialize properties with them, set them as default arguments values (as it's done for now) or specify them in both places?

This one is a little more complex. In my mind there are three possible scenarios when choosing how to initialize an object property.

The value MUST be passed to the constructor.

This is a case where a certain property must be specified when instantiating the object. If a value is not specified, the code should fail. For example, when creating an object of type User, then it is probably safe to assume it requires a firstName, lastName and email. If one or all of those variables are not passed to the constructor, the code should simply fail: the contract set by the constructor is not fulfilled.

```<code>class User {
    private $firstName;
    private $lastName;
    private $email;

    public function __construct(string $firstName, string $lastName, string $email) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->email = $email;
    }
}

$user = new User();
</code>```

Exception: Argument 1 passed to User::__construct() must be of the type string, none given

The value MAY be passed to the constructor.

This is a case where you want to allow a value to be set in the constructor, but is not required to instatiate the object. Taking the User example from before, we could also have an middleName property that a user can have, and we want to be able to set it the constructor.

```<code>class User {
    private $firstName;
    private $lastName;
    private $middleName;
    private $email;

    public function __construct(string $firstName, string $lastName, string $email, $middleName = null) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->email = $email;
        $this->middleName = $middleName;
    }
}

$user = new User('John', 'Doe', 'johndoe@email.com'); // does not throw an Exception
</code>```

in my opinion there are very little reasons to actually implement a constructor in this way. It adds unnecessary complexity to the constructor while not actually solving any real problem. Sure it may be a quick and dirty way to add a parameter to the constructor without breaking any existing code, however if you are modifying the rules for creating an instance of an object, then the existing code should probably be updated to reflect this change.

The value MUST be initialized to a default value.

This is a case where you want a certain property to be initialized to a specific default value as soon as the object is instantiated. This way there is no need to constantly check if the property has been initialized or not, or check for a null value when dealing with this property. If a specific use case requires that value to be overwritten right away, simply call the setter after instantiating the object.

```<code>class User {
    const USER_DEFAULT = 'default';

    private $firstName;
    private $email;
    private $propertyToInitialize = self::USER_DEFAULT;

    public function __construct(string $firstName, string $email) {
        $this->firstName = $firstName;
        $this->email = $email;
    }

    public function getInitializedProperty() {
        return $this->propertyToInitialize;
    }
}

$user = new User('John', 'johndoe@email.com');
echo $user->getInitializedProperty(); // outputs: 'default'
</code>```

If you need a property's value to be part of a specific subset of values, I recommend checking out Enums

Body:
I create a class with strict properties' types, their values can be passed to constructor:

declare(strict_types=1);

class Position
{
    protected $hours;
    protected $minutes;
    protected $seconds;
    protected $frames;

    public function __construct(int $hours = 0, int $minutes = 0, int $seconds = 0, int $frames = 0)
    {
        $this->setHours($hours);
        $this->setMinutes($minutes);
        $this->setSeconds($seconds);
        $this->setFrames($frames);
    }

    public function getHours(): int
    {
        return $this->hours;
    }

    public function setHours(int $hours): void
    {
        $this->hours = $hours;
    }

    // and so on...
}

Is it good to set properties' values with setters inside the constructor?

Is it good to get their values inside class' methods with getters?

Where it would be better to set the default properties' values: explicitly initialize properties with them, set them as default arguments values (as it's done for now) or specify them in both places?

Thanks.

Body:
Is it good to set properties' values with setters inside the constructor?

In other words: is it ok to delegate to a setter when initializing a property in the constructor? The short answer is: It doesn't really matter. If there is no validation (other than the type) made, then there's really no point in it, but there's also no downside. If the is more validation to be made, then one could make the point that it keeps the constructor clean while reducing the amount of duplicate code. If there is additional checks to be made, then delegating to the setter for the common validation and implementing the additional one in the constructor will help keep the two workflows separate.

In the end, I don't think there's really a concern here. It's neither good nor bad practice to do it. Do what feels best for your specific use case.

Is it good to get their values inside class' methods with getters?

If you mean "should I access object properties through getters", then: Yes. A thousand times yes. Object properies should always be private and accessed through getters. Public properties violate one of the core concepts of Object-Oriented: Encapsulation. Whether or not each member has a getter and has logic or not is completely up to you and will depend on the use case.

if you mean "should I use the getter to access a propery from within the object" then it really doesn't matter and depends on the scenario. There may be times where using the public getter makes no practical sense and doesn't help the readability/maintainability of the code. There may be cases where it totally makes sense to call the public getter. For example when dealing with a function in the style of isFoo() which returns true or false based on a couple of conditions, it makes sense to simply call isFoo() instead of repeating the conditions again.

Where it would be better to set the default properties' values: explicitly initialize properties with them, set them as default arguments values (as it's done for now) or specify them in both places?

This one is a little more complex. In my mind there are three possible scenarios when choosing how to initialize an object property.

The value MUST be passed to the constructor.

This is a case where a certain property must be specified when instantiating the object. If a value is not specified, the code should fail. For example, when creating an object of type User, then it is probably safe to assume it requires a firstName, lastName and email. If one or all of those variables are not passed to the constructor, the code should simply fail: the contract set by the constructor is not fulfilled.

class User {
    private $firstName;
    private $lastName;
    private $email;

    public function __construct(string $firstName, string $lastName, string $email) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->email = $email;
    }
}

$user = new User();

Exception: Argument 1 passed to User::__construct() must be of the type string, none given

The value MAY be passed to the constructor.

This is a case where you want to allow a value to be set in the constructor, but is not required to instatiate the object. Taking the User example from before, we could also have an middleName property that a user can have, and we want to be able to set it the constructor.

class User {
    private $firstName;
    private $lastName;
    private $middleName;
    private $email;

    public function __construct(string $firstName, string $lastName, string $email, $middleName = null) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->email = $email;
        $this->middleName = $middleName;
    }
}

$user = new User('John', 'Doe', 'johndoe@email.com'); // does not throw an Exception

in my opinion there are very little reasons to actually implement a constructor in this way. It adds unnecessary complexity to the constructor while not actually solving any real problem. Sure it may be a quick and dirty way to add a parameter to the constructor without breaking any existing code, however if you are modifying the rules for creating an instance of an object, then the existing code should probably be updated to reflect this change.

The value MUST be initialized to a default value.

This is a case where you want a certain property to be initialized to a specific default value as soon as the object is instantiated. This way there is no need to constantly check if the property has been initialized or not, or check for a null value when dealing with this property. If a specific use case requires that value to be overwritten right away, simply call the setter after instantiating the object.

class User {
    const USER_DEFAULT = 'default';

    private $firstName;
    private $email;
    private $propertyToInitialize = self::USER_DEFAULT;

    public function __construct(string $firstName, string $email) {
        $this->firstName = $firstName;
        $this->email = $email;
    }

    public function getInitializedProperty() {
        return $this->propertyToInitialize;
    }
}

$user = new User('John', 'johndoe@email.com');
echo $user->getInitializedProperty(); // outputs: 'default'

If you need a property's value to be part of a specific subset of values, I recommend checking out Enums


问:
Fibonacci Modified:How to fix this algorithm?
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

```<code>public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}
</code>```

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

答:
I can think of a way of doing this with the constraints in your comments but it's a total hack. You need one method to do two things: find the current value and add previous values. One option is to use negative numbers to flag one of those function:

```<code>int f(int n) {
    if (n > 0)
        return f(-n) + f(n-1);
    else if (n > -2)
        return 0;
    else if (n == -2)
        return 1;
    else
        return f(n+1)*f(n+1)+f(n+2)*f(n+2);
}
</code>```

The first 8 numbers output (before overflow) are:

```<code>0
1
2
4
9
38
904
751701
</code>```

I don't recommend this solution but it does meet your constraints of being a single recursive method with a single argument.

Body:
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

Body:
I can think of a way of doing this with the constraints in your comments but it's a total hack. You need one method to do two things: find the current value and add previous values. One option is to use negative numbers to flag one of those function:

int f(int n) {
    if (n > 0)
        return f(-n) + f(n-1);
    else if (n > -2)
        return 0;
    else if (n == -2)
        return 1;
    else
        return f(n+1)*f(n+1)+f(n+2)*f(n+2);
}

The first 8 numbers output (before overflow) are:

0
1
2
4
9
38
904
751701

I don't recommend this solution but it does meet your constraints of being a single recursive method with a single argument.


问:
Python login to website via twitter
A website use 'login via twitter'. Just like this site use facebook. How do I log in and get login cookies for the website (using python), if I know twitter username and password?</p>

答:
You don't; you use OAuth to authenticate.  Allowing third-party sites to authenticate with a user's username and password is a horrible security flaw, and Twitter no longer allows it.

See Twitter's OAuth Docs for how to authenticate.

EDIT:  Twitter does still maintain an 'xAuth' option that allows you to authenticate with a username and password.  You need to get special permission from Twitter to use it.

Title: Python login to website via twitter


答:
We want:

```<code>mod(1) = 0
mod(2) = 0+1
mod(3) = 0+1+1
mod(4) = 0+1+1+2
mod(5) = 0+1+1+2+5
mod(6) = 0+1+1+2+5+29
</code>```

and we know that each term is defined as something like:

```<code>   2^2+5^2=29
</code>```

So to work out mod(7) we need to add the next term in the sequence x to mod(6).

Now we can work out the term using mod:

```<code> x = term(5)^2 + term(6)^2
 term(5) = mod(5) - mod(4)
 term(6) = mod(6) - mod(5)
 x = (mod(5)-mod(4))^2 + (mod(6)-mod(5))^2
</code>```

So we can work out mod(7) by evaluating mod(4),mod(5),mod(6) and combining the results.

Of course, this is going to be incredibly inefficient unless you memoize the function!

Example Python code:

```<code>def f(n):
    if n<=0:
        return 0
    if n==1:
        return 1
    a=f(n-1)
    b=f(n-2)
    c=f(n-3)
    return a+(a-b)**2+(b-c)**2

for n in range(10):
    print f(n)
</code>```

prints:

```<code>0
1
2
4
9
38
904
751701
563697636866
317754178345850590849300
</code>```

Title: Fibonacci Modified:How to fix this algorithm?

Body:
We want:

mod(1) = 0
mod(2) = 0+1
mod(3) = 0+1+1
mod(4) = 0+1+1+2
mod(5) = 0+1+1+2+5
mod(6) = 0+1+1+2+5+29

and we know that each term is defined as something like:

   2^2+5^2=29

So to work out mod(7) we need to add the next term in the sequence x to mod(6).

Now we can work out the term using mod:

 x = term(5)^2 + term(6)^2
 term(5) = mod(5) - mod(4)
 term(6) = mod(6) - mod(5)
 x = (mod(5)-mod(4))^2 + (mod(6)-mod(5))^2

So we can work out mod(7) by evaluating mod(4),mod(5),mod(6) and combining the results.

Of course, this is going to be incredibly inefficient unless you memoize the function!

Example Python code:

def f(n):
    if n<=0:
        return 0
    if n==1:
        return 1
    a=f(n-1)
    b=f(n-2)
    c=f(n-3)
    return a+(a-b)**2+(b-c)**2

for n in range(10):
    print f(n)

prints:

0
1
2
4
9
38
904
751701
563697636866
317754178345850590849300


问:
Is it possible to recalculate the `srcset` image used if browser window is resized?
Is it possible to get srcset to recalculate the browser window size once the page has loaded, and thus update the image its using.

The reason you'd want to do this is because if on a desktop you have your browser window compressed, load a site, then make the browser window bigger, it will just scale the "small.jpg" (as set in the srcset) so the user will end up with a pixilated image.

I started make a jsfiddle to show the issue, but it dosnt work well, as i think srcset is calculated by the browser window, rather than the jsfiddle results grid.

If you are interested you can copy and paste below this into a blank html file and run it in a localserver (must be on a local http:// server  so you can view the network debugging tab to see which image the browser has loaded). Running it in the browser via the file url using file:/// wont allow you to see which image is loaded via the network debugging tab.

```<code>    <body>
        <div class="wrapper">

            <img
                 src="http://i.imgur.com/DoWeH0X.jpg?1"
                 srcset="http://i.imgur.com/QV9vace.jpg?1 1400w, http://i.imgur.com/ZqkR6Bk.jpg?1 800w, http://i.imgur.com/gltBZ06.jpg?1 300w"
                 alt="#"
            >

    </body>
</html>
</code>```

答:
i found this to force a re-render

var img = document.getElementById('my-element');

img.srcset = img.srcset;

ContentLicense: CC BY-SA 4.0


问:
How can I select for the latest row based on two different attributes?
I need to select the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745)   for my employees.  I need to know what my employee last transaction was (from the list) that had one of those activity codes.  There are 2 tables involved with a join on the employee ID.
Table 1:

```<code>|Emp_id  |  STUFF
|  1     |  stuff
|  2     |  stuff
|  3     |  stuff
</code>```

Table 2:

```<code>|Emp_id   |  date      | act_code   |  trans
|   1     |  1/1/17    |   A        |    109
|   1     |  3/4/12    |   X        |    203
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    110
|   2     |  6/6/13    |   V        |    109
|   3     |  12/13/16  |   J        |    982
|   3     |  11/23/14  |   W        |    745
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    745
</code>```

What I’d like to return is:

```<code>|Emp_id  |  STUFF  |  date      | act_code   |  trans
|  1     |  stuff  |  1/1/17    |   A        |    109
|  3     |  stuff  |  12/13/16  |   J        |    982
</code>```

Emp 2 would not be selected because the latest trans is not one of the correct values.  Emp 4 would not be selected because the latest act_code is not one of the correct values.  Anyone have an idea as to how to go about this?  Thanks in advance.

答:
Here is one way.

Use ROW_NUMBER() to partition the rows by emp_id and order the rows by date:

```<code>SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
       ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
FROM Table1 t1
JOIN Table2 t2 on t1.emp_id = t2.emp_id;
</code>```

Then filter this to only the most recent records (RN = 1) that have values in your lists with an outer select:

```<code>SELECT emp_id, stuff, date, act_code, trans
FROM (
    SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
           ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
    FROM Table1 t1
    JOIN Table2 t2 on t1.emp_id = t2.emp_id
     ) A
WHERE RN = 1
AND trans IN (109, 154, 982, 745)
AND act_code IN ('A', 'V', 'W', 'J');
</code>```

Body:
I need to select the latest activity code (A, V, W, J) for the following transactions (109, 154, 982, 745)   for my employees.  I need to know what my employee last transaction was (from the list) that had one of those activity codes.  There are 2 tables involved with a join on the employee ID.
Table 1:

|Emp_id  |  STUFF
|  1     |  stuff
|  2     |  stuff
|  3     |  stuff

Table 2:

|Emp_id   |  date      | act_code   |  trans
|   1     |  1/1/17    |   A        |    109
|   1     |  3/4/12    |   X        |    203
|   1     |  2/14/09   |   A        |    154
|   2     |  1/1/17    |   A        |    110
|   2     |  6/6/13    |   V        |    109
|   3     |  12/13/16  |   J        |    982
|   3     |  11/23/14  |   W        |    745
|   4     |  12/13/16  |   X        |    154
|   4     |  11/23/14  |   W        |    745

What I’d like to return is:

|Emp_id  |  STUFF  |  date      | act_code   |  trans
|  1     |  stuff  |  1/1/17    |   A        |    109
|  3     |  stuff  |  12/13/16  |   J        |    982

Emp 2 would not be selected because the latest trans is not one of the correct values.  Emp 4 would not be selected because the latest act_code is not one of the correct values.  Anyone have an idea as to how to go about this?  Thanks in advance.

Body:
Here is one way.

Use ROW_NUMBER() to partition the rows by emp_id and order the rows by date:

SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
       ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
FROM Table1 t1
JOIN Table2 t2 on t1.emp_id = t2.emp_id;

Then filter this to only the most recent records (RN = 1) that have values in your lists with an outer select:

SELECT emp_id, stuff, date, act_code, trans
FROM (
    SELECT t2.emp_id, t1.stuff, t2.date, t2.act_code, t2.trans,
           ROW_NUMBER() over (PARTITION BY t2.emp_id ORDER BY t2.date DESC) RN
    FROM Table1 t1
    JOIN Table2 t2 on t1.emp_id = t2.emp_id
     ) A
WHERE RN = 1
AND trans IN (109, 154, 982, 745)
AND act_code IN ('A', 'V', 'W', 'J');


问:
Adding key:value items to a dictionay in python with a for
Hi i have this function:

```<code>     def company_runtime(company_name):
        for well in all_wells:
            well_runtime = {}
            if well["groupName"].lower() == company_name.lower():
                well_runtime.update({well["name"]: well["efficiency"]})
            return well_runtime
</code>```

And i want to get a dictionary with "names" and "efficiency" from the loop, if i enter a compay name as a parameter.

I am getting only the last element of the all_wells list that meet that condition.

what i am doing wrong?

Thanks in advance

答: Each time you go through the loop you are resetting the Dictionary to {} or empty thus it clears it out until the last time on exit. Move well_runtime = {} outside of the loop.

Body:
Hi i have this function:

     def company_runtime(company_name):
        for well in all_wells:
            well_runtime = {}
            if well["groupName"].lower() == company_name.lower():
                well_runtime.update({well["name"]: well["efficiency"]})
            return well_runtime

And i want to get a dictionary with "names" and "efficiency" from the loop, if i enter a compay name as a parameter.

I am getting only the last element of the all_wells list that meet that condition.

what i am doing wrong?

Thanks in advance


问:
How to display average line in chart.js
I have been trying to display average line using chart.js, but I do not know how to do that.

This is my code:

```<code>var myChart = {
        type: 'line',
        data: {
          labels: MONTHS,  // array
          datasets: [{
            label: "Temperature",
            fill: false,
            backgroundColor: chartColors.red,
            borderColor: chartColors.red,
            data: tempInfo,  //array [1,2,3,4,5,6,7]
          }]
        },
        options: {
          responsive: true,
          title: {
            display: true,
            text: 'Farm Health Monitor'
          },
          tooltips: {
            mode: 'label',
          },
          hover: {
            mode: 'nearest',
            intersect: true
          },
          scales: {
            xAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Month'
              }
            }],
            yAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Value'
              }
            }]
          }
        }
      };
</code>```

答:
Just use Mathjs library site is http://mathjs.org.

And use the method : math.mean(yourArray) <-- put your Array in

I hope it will be helpful to you.

Title: How to display average line in chart.js

Body:
I have been trying to display average line using chart.js, but I do not know how to do that.

This is my code:

var myChart = {
        type: 'line',
        data: {
          labels: MONTHS,  // array
          datasets: [{
            label: "Temperature",
            fill: false,
            backgroundColor: chartColors.red,
            borderColor: chartColors.red,
            data: tempInfo,  //array [1,2,3,4,5,6,7]
          }]
        },
        options: {
          responsive: true,
          title: {
            display: true,
            text: 'Farm Health Monitor'
          },
          tooltips: {
            mode: 'label',
          },
          hover: {
            mode: 'nearest',
            intersect: true
          },
          scales: {
            xAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Month'
              }
            }],
            yAxes: [{
              display: true,
              scaleLabel: {
                display: true,
                labelString: 'Value'
              }
            }]
          }
        }
      };


问:
C++ - class issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

```<code>#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}
</code>```

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

答:
You need :</p>

```<code>#include <string>
#include <iostream>
#include <string.h>
</code>```

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

Body:
You need :

#include <string>
#include <iostream>
#include <string.h>


问:
Linq To SQL throws has no supported translation to SQL Exception when using generic Insert method
I have a method to insert entity to tables genericly using type T. But I want to add a feature to check if the entity to be added exists in the table based on a matcher property (e.g Name). When I execute the code it throws 'has no supported translation to SQL' on the check line. My code part is below. How can I fix this problem?</p>

```<code>    public static InsertStatus Add<T>(T ent, string matcherProp) where T : class
    {
        System.Data.Linq.Table<T> t = otdc.GetTable<T>();

        //Exception on this line
        if (t.Any(item => object.Equals(GetPropValue(item, matcherProp), GetPropValue(ent, matcherProp))))
            return InsertStatus.AlreadyExists;

        try
        {
            t.InsertOnSubmit(ent);
            otdc.SubmitChanges();
            return InsertStatus.Successfull;
        }
        catch
        {
            return InsertStatus.UnknownError;
        }
    }
    public static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName).GetValue(src, null);
    }
</code>```

答:
You will need to create an expresion tree at runtime. Fortunately this isn't very hard in your case; it will be something like:

```<code>var p = Expression.Parameter(typeof(T), "p");
var val = GetPropValue(ent, matcherProp);
var test = Expression.Lambda<Func<T, bool>>(
    Expression.Equal(
        Expression.PropertyOrField(p, matcherProp),
        Expression.Constant(val)
    ), p);

if (t.Any(test))
    return InsertStatus.AlreadyExists;
</code>```

What this does is construct the logical tree for:

```<code>p => p.{matcherProp} == {val}
</code>```

where matcherProp is the name of the member to test, and val is the existing value as a constant.

Note that you might get issues if val is null, unless you can also supply the type of the property (.PropertyType on the PropertyInfo) - and supply it to Expression.Constant.

Edit: another way to do this is to supply ent as the constant:

```<code>var p = Expression.Parameter(typeof(T), "p");
var test = Expression.Lambda<Func<T, bool>>(
    Expression.Equal(
        Expression.PropertyOrField(p, matcherProp),
        Expression.PropertyOrField(Expression.Constant(ent), matcherProp),
    ), p);
</code>```

This is then more akin to:

```<code>p => p.{matcherProp} == ent.{matcherProp}
</code>```

where ent in the lambda behaves much like a "captured variable".

Body:
I have a method to insert entity to tables genericly using type T. But I want to add a feature to check if the entity to be added exists in the table based on a matcher property (e.g Name). When I execute the code it throws 'has no supported translation to SQL' on the check line. My code part is below. How can I fix this problem?

    public static InsertStatus Add<T>(T ent, string matcherProp) where T : class
    {
        System.Data.Linq.Table<T> t = otdc.GetTable<T>();

        //Exception on this line
        if (t.Any(item => object.Equals(GetPropValue(item, matcherProp), GetPropValue(ent, matcherProp))))
            return InsertStatus.AlreadyExists;

        try
        {
            t.InsertOnSubmit(ent);
            otdc.SubmitChanges();
            return InsertStatus.Successfull;
        }
        catch
        {
            return InsertStatus.UnknownError;
        }
    }
    public static object GetPropValue(object src, string propName)
    {
        return src.GetType().GetProperty(propName).GetValue(src, null);
    }

Body:
You will need to create an expresion tree at runtime. Fortunately this isn't very hard in your case; it will be something like:

var p = Expression.Parameter(typeof(T), "p");
var val = GetPropValue(ent, matcherProp);
var test = Expression.Lambda<Func<T, bool>>(
    Expression.Equal(
        Expression.PropertyOrField(p, matcherProp),
        Expression.Constant(val)
    ), p);

if (t.Any(test))
    return InsertStatus.AlreadyExists;

What this does is construct the logical tree for:

p => p.{matcherProp} == {val}

where matcherProp is the name of the member to test, and val is the existing value as a constant.

Note that you might get issues if val is null, unless you can also supply the type of the property (.PropertyType on the PropertyInfo) - and supply it to Expression.Constant.

Edit: another way to do this is to supply ent as the constant:

var p = Expression.Parameter(typeof(T), "p");
var test = Expression.Lambda<Func<T, bool>>(
    Expression.Equal(
        Expression.PropertyOrField(p, matcherProp),
        Expression.PropertyOrField(Expression.Constant(ent), matcherProp),
    ), p);

This is then more akin to:

p => p.{matcherProp} == ent.{matcherProp}

where ent in the lambda behaves much like a "captured variable".


问:
C - declare and init array inside struct
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

```<code>struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};
</code>```

later, i want to access the values ...

```<code>int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}
</code>```

the only error is

```<code>./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~
</code>```

答:
The error you're getting is because ARRAY_SIZE expects an array, and structvariablepointer->section_A is not an array but a pointer.

Since your structs effectively have fixed size arrays, just declare them as arrays instead of pointers:

```<code>struct structname {
    int section_A[4];
    int section_B[0x35];
};
</code>```

Then initialize like this:

```<code>static const struct structname structvariable_a = {

    .section_A = {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = {
            [0x33] = 4,
            [0x34] = 5
        },
};
</code>```

Body:
language: C

i am trying to declare and initialize an array inside a struct and pass it to a pointer, which is itself declared in the struct xD

yes, i know my attempt is... let's say "not correct" :D
but it would be very useful if something similar would exist.

any ideas?

struct structname {
    int* section_A;
    int* section_B;
};

static const struct structname structvariable_a = {

    .section_A = (int[]) {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = (int[]) {
            [0x33] = 4,
            [0x34] = 5
        },

};

static const struct structname structvariable_b = {

    .section_A = (int[]) {
            [0x01] = 10,
            [0x02] = 20,
            [0x03] = 30
        },

    .section_B = (int[]) {
            [0x33] = 7,
            [0x34] = 8
        },

};

later, i want to access the values ...

int main()
{

    struct structname* structvariablepointer;

    if(foo == 1){
        structvariablepointer = &structvariable_a;
    } else {
        structvariablepointer = &structvariable_b;
    }

    printf("%i", ARRAY_SIZE(structvariablepointer->section_A));     // ARRAY_SIZE(arr) equals sizeof(arr) / sizeof(arr[0]));

    int b = 2;

    printf("%i", structvariablepointer->section_A[b]);
}

the only error is

./include/linux/build_bug.h:29:45: Fehler: Negative Breite in Bitfeld »<anonym>«
 #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:(-!!(e)); }))
                                             ^
./include/linux/compiler-gcc.h:64:28: Anmerkung: bei Substitution des Makros »BUILD_BUG_ON_ZERO«
 #define __must_be_array(a) BUILD_BUG_ON_ZERO(__same_type((a), &(a)[0]))
                            ^~~~~~~~~~~~~~~~~
./include/linux/kernel.h:60:59: Anmerkung: bei Substitution des Makros »__must_be_array«
 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
                                                           ^~~~~~~~~~~~~~~

Body:
The error you're getting is because ARRAY_SIZE expects an array, and structvariablepointer->section_A is not an array but a pointer.

Since your structs effectively have fixed size arrays, just declare them as arrays instead of pointers:

struct structname {
    int section_A[4];
    int section_B[0x35];
};

Then initialize like this:

static const struct structname structvariable_a = {

    .section_A = {
            [0x01] = 1,
            [0x02] = 2,
            [0x03] = 3
        },

    .section_B = {
            [0x33] = 4,
            [0x34] = 5
        },
};


问:
SQL Server geography result format
Using SQL Server Management Studio:

```<code>declare @g geography
set @g = geography::Point(-77.1851436,39.1065236,4326)
select @g
</code>```

returns

```<code>0xE6100000010C14C48A64D94B53C04820B990A28D4340
</code>```

What format is this result? I know that it is not STAsBinary() - that returns

```<code>0x01010000004820B990A28D434014C48A64D94B53C0
</code>```

Is there a way to create the 0xE61... value using C#?

答:
This is special binary format defined here (you may download PDF there if interested about details of that format). You can create such value in C# like this (reference Microsoft.SqlServer.Types assembly):

```<code>var pt = SqlGeography.Point(-77.1851436, 39.1065236, 4326);
var binary = pt.Serialize().Value;
var hexString = "0x" + BitConverter.ToString(binary).Replace("-", "");
</code>```

Title: SQL Server geography result format

Body:
Using SQL Server Management Studio:

declare @g geography
set @g = geography::Point(-77.1851436,39.1065236,4326)
select @g

returns

0xE6100000010C14C48A64D94B53C04820B990A28D4340

What format is this result? I know that it is not STAsBinary() - that returns

0x01010000004820B990A28D434014C48A64D94B53C0

Is there a way to create the 0xE61... value using C#?

Body:
This is special binary format defined here (you may download PDF there if interested about details of that format). You can create such value in C# like this (reference Microsoft.SqlServer.Types assembly):

var pt = SqlGeography.Point(-77.1851436, 39.1065236, 4326);
var binary = pt.Serialize().Value;
var hexString = "0x" + BitConverter.ToString(binary).Replace("-", "");


问:
How do I automatically change method/class access levels in IntelliJ?
A lot of the time, I start out with methods being public and then reducing them to the lowest levels needed after I finish, but that's kind of tedious. Is there a way to automatically change all the privacy modifiers (for both classes and methods) to the lowest ones possible all at once?

答: It is possible: Analyze | Run inspection by name, and enter Declaration access can be weaker name for the inspection. Then run the inspection for the project and fix all the occurrences in the project by one click in Inspection results tool window.


问:
Darken/Lighten ARKit camera feed behind objects
I'm currently working on an ARKit project where I would like to darken the actual camera feed so the objects in my 3D scene stand out more.

2 Solutions I found so far:

A) Manually applying CIFilter to the camera frames and setting those as background image to the SceneKit scene as answered in this SO post
The problem here is that fps tanks significantly.

B) Set a background color like so:

```<code>sceneView.scene.background.contents = UIColor(white: 0.0, alpha: 0.2)
</code>```

Sadly, colors with alpha <1 are still opaque, so no matter what alpha I set I can't see anything of the camera feed.

Can anyone think of a different trick to darken the camera feed?

答:
Your option B doesn't work for two reasons:

the scene view is opaque, so there's nothing behind it for a partially transparent background color to blend with.

sceneView.scene.background is what actually displays the camera image, so if you set it to a color you're not displaying the camera image at all anymore.

Some other options (mostly untested) you might look into:

As referenced from the answer you linked, use SCNTechnique to set up multipass rendering. On the first pass, render the whole scene with the excludeCategoryMask (and your scene contents) set up to render nothing but the background, using a shader that dims (or blurs or whatever) all pixels. On the second pass, render only the node(s) you want to appear without that shader (use a simple pass-through shader).

Keep your option B, but make the scene view non-opaque. Set the view's backgroundColor (not the scene's background) to a solid color, and set the transparency of the scene background to fade out the camera feed against that color.

Use geometry to create a "physical" backdrop for your scene — e.g. an SCNPlane of large size, placed as a child of the camera at some fixed distance that's much farther than any other scene content. Set the plane's background color and transparency.

Use multiple views — the ARSCNView, made non-opaque and with a clear background, and another (not necessarily an SceneKit view) that just shows the camera feed. Mess with the other view (or drop in other fun things like UIVisualEffectView) to obscure the camera feed.

File a bug with Apple about sceneView.background not getting the full set of shading customization options that nodes and materials get (filters, shader modifiers, full shader programs) etc, without which customizing the background is much more difficult than customizing other aspects of the scene.

Body:
I'm currently working on an ARKit project where I would like to darken the actual camera feed so the objects in my 3D scene stand out more.

2 Solutions I found so far:

A) Manually applying CIFilter to the camera frames and setting those as background image to the SceneKit scene as answered in this SO post
The problem here is that fps tanks significantly.

B) Set a background color like so:

sceneView.scene.background.contents = UIColor(white: 0.0, alpha: 0.2)

Sadly, colors with alpha <1 are still opaque, so no matter what alpha I set I can't see anything of the camera feed.

Can anyone think of a different trick to darken the camera feed?


问:
Azure Functions - Set MediaTypeFormatter for response message?
I am trying to set a media type formatter for the response of an Azure Function to return an Excel file. I do not want an External File Binding since I want to stream the output to the browser for download, not write the file to a blob or a google sheet or something. I have used the EPPlus library and WebApiContrib.Formatting.Xlsx for this purpose before in other contexts (e.g. WebApi). I was able to import the packages and reference them in my function, but I have not been able to successfully add the formatter and apply it to the response.

Is it possible to get a reference to the HttpConfiguration object for a function to add the formatter? I have tried adding the XlsxMediaTypeFormatter to the CreateResponse call but for some reason it cannot be cast to a MediaTypeFormatter. If I just try to set the MIME type, it says there is no formatter available.

Here's my test function:

```<code>using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using WebApiContrib.Formatting.Xlsx;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{

    var testData = new List<TestItemDto>
    {
        new TestItemDto
        {
            Id = System.Guid.NewGuid().ToString(),
            Name = "Test Item 1"
        },
        new TestItemDto
        {
            Id = System.Guid.NewGuid().ToString(),
            Name = "Test Item 2"
        }
    };

    //var excelMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var formatter = new XlsxMediaTypeFormatter(headerHeight: 25f, freezeHeader: true);

    var response = req.CreateResponse<List<TestItemDto>>(HttpStatusCode.OK, testData, (MediaTypeFormatter)formatter);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "TestData.xlsx"
    };
    return response;
}

public class TestItemDto
{
    public string Id { get; set; }
    public string Name { get; set; }
}
</code>```

And I get the error:

```<code>error CS0030: Cannot convert type 'WebApiContrib.Formatting.Xlsx.XlsxMediaTypeFormatter' to 'System.Net.Http.Formatting.MediaTypeFormatter'
</code>```

My project.json file:

```<code>{
  "frameworks": {
    "net46":{
      "dependencies": {
        "EPPlus": "3.1.3.3",
        "WebApiContrib.Formatting.Xlsx" : "1.0.1"
      }
    }
   }
}
</code>```

答:
This isn't the best answer, since it bypasses the MediaTypeFormatter and just creates the response content directly. However, I was able to get it to work by ditching the XlsxMediaTypeFormatter, creating the excel workbook directly with the EPPlus library, and streaming it to the browser (using the same DTO and test collection as above):

```<code>// try to create an excel file by hand with EPPlus
ExcelPackage pck = new ExcelPackage();
var wsTest = pck.Workbook.Worksheets.Add("TestSheet");
//Load the collection starting from cell A1...
wsTest.Cells["A1"].LoadFromCollection(testData, true);
wsTest.Cells[wsTest.Dimension.Address].AutoFitColumns();

var excelMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

var response = req.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(pck.GetAsByteArray()));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(excelMediaType);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
      FileName = "TestData.xlsx"
};
return response;
</code>```

I will leave the question open in case someone can answer the actual question (e.g. how to use a MediaTypeFormatter).

Body:
I am trying to set a media type formatter for the response of an Azure Function to return an Excel file. I do not want an External File Binding since I want to stream the output to the browser for download, not write the file to a blob or a google sheet or something. I have used the EPPlus library and WebApiContrib.Formatting.Xlsx for this purpose before in other contexts (e.g. WebApi). I was able to import the packages and reference them in my function, but I have not been able to successfully add the formatter and apply it to the response.

Is it possible to get a reference to the HttpConfiguration object for a function to add the formatter? I have tried adding the XlsxMediaTypeFormatter to the CreateResponse call but for some reason it cannot be cast to a MediaTypeFormatter. If I just try to set the MIME type, it says there is no formatter available.

Here's my test function:

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using WebApiContrib.Formatting.Xlsx;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{

    var testData = new List<TestItemDto>
    {
        new TestItemDto
        {
            Id = System.Guid.NewGuid().ToString(),
            Name = "Test Item 1"
        },
        new TestItemDto
        {
            Id = System.Guid.NewGuid().ToString(),
            Name = "Test Item 2"
        }
    };

    //var excelMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var formatter = new XlsxMediaTypeFormatter(headerHeight: 25f, freezeHeader: true);

    var response = req.CreateResponse<List<TestItemDto>>(HttpStatusCode.OK, testData, (MediaTypeFormatter)formatter);
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "TestData.xlsx"
    };
    return response;
}

public class TestItemDto
{
    public string Id { get; set; }
    public string Name { get; set; }
}

And I get the error:

error CS0030: Cannot convert type 'WebApiContrib.Formatting.Xlsx.XlsxMediaTypeFormatter' to 'System.Net.Http.Formatting.MediaTypeFormatter'

My project.json file:

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "EPPlus": "3.1.3.3",
        "WebApiContrib.Formatting.Xlsx" : "1.0.1"
      }
    }
   }
}

Body:
This isn't the best answer, since it bypasses the MediaTypeFormatter and just creates the response content directly. However, I was able to get it to work by ditching the XlsxMediaTypeFormatter, creating the excel workbook directly with the EPPlus library, and streaming it to the browser (using the same DTO and test collection as above):

// try to create an excel file by hand with EPPlus
ExcelPackage pck = new ExcelPackage();
var wsTest = pck.Workbook.Worksheets.Add("TestSheet");
//Load the collection starting from cell A1...
wsTest.Cells["A1"].LoadFromCollection(testData, true);
wsTest.Cells[wsTest.Dimension.Address].AutoFitColumns();

var excelMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

var response = req.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(new MemoryStream(pck.GetAsByteArray()));
response.Content.Headers.ContentType = new MediaTypeHeaderValue(excelMediaType);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
      FileName = "TestData.xlsx"
};
return response;

I will leave the question open in case someone can answer the actual question (e.g. how to use a MediaTypeFormatter).


问:
Which action(s) can I use to create a folder in SharePoint Online via Azure Logic App?
As question title states, I am looking for a proper action in Logic Apps to create a folder. This action will be executed several times -- once per directory as per business rule. There will be no files created in these folders because the intent of the Logic App is to prepare a template folder structure for the users' needs.

In the official documentation I see that there are create file, create item, and list folder actions. They suggest that there might be an action to create a folder too (which I can't find).

If such action does not exist, I may need to use some SharePoint Online API, but that will be a last resort solution.

答:
I was able to create a directory by means of SharePoint - CreateFile action. Creating a directory via a side effect of the file creation action is definitely a dirty hack (btw, inspired by a comment on MS suggestion site). This bug/feature is not documented, so relying on it in production environment is probably not a good idea.

More that that, if my problem requires creating a directory in SharePoint without any files in it whatsoever, an extra step in App Logic needs to be used. Make sure to delete the file using the Id provided by Create File action.

Here's what your JSON might look like, if you were trying to create a directory called folderCreatedAsSideEffect under preexisting TestTarget document library.

```<code>"actions": {
    "Create_file": {
        "inputs": {
            "body": "@triggerBody()?['Name']",
            "host": { "connection": { "name": "@parameters('$connections')['sharepointonline']['connectionId']" } },
            "method": "post",
            "path": "/datasets/@{encodeURIComponent(encodeURIComponent('https://MY.sharepoint.com/LogicApps/'))}/files",
            "queries": {
                "folderPath": "/TestTarget/folderCreatedAsSideEffect",
                "name": "placeholder"
            }
        },
        "runAfter": {},
        "type": "ApiConnection"
    },
    "Delete_file": {
        "inputs": {
            "host": { "connection": { "name": "@parameters('$connections')['sharepointonline']['connectionId']" } },
            "method": "delete",
            "path": "/datasets/@{encodeURIComponent(encodeURIComponent('https://MY.sharepoint/LogicApps/'))}/files/@{encodeURIComponent(body('Create_file')?['Id'])}"
        },
        "runAfter": {
            "Create_file": [
                "Succeeded"
            ]
        },
        "type": "ApiConnection"
    }
},
</code>```

Body:
I was able to create a directory by means of SharePoint - CreateFile action. Creating a directory via a side effect of the file creation action is definitely a dirty hack (btw, inspired by a comment on MS suggestion site). This bug/feature is not documented, so relying on it in production environment is probably not a good idea.

More that that, if my problem requires creating a directory in SharePoint without any files in it whatsoever, an extra step in App Logic needs to be used. Make sure to delete the file using the Id provided by Create File action.

Here's what your JSON might look like, if you were trying to create a directory called folderCreatedAsSideEffect under preexisting TestTarget document library.

"actions": {
    "Create_file": {
        "inputs": {
            "body": "@triggerBody()?['Name']",
            "host": { "connection": { "name": "@parameters('$connections')['sharepointonline']['connectionId']" } },
            "method": "post",
            "path": "/datasets/@{encodeURIComponent(encodeURIComponent('https://MY.sharepoint.com/LogicApps/'))}/files",
            "queries": {
                "folderPath": "/TestTarget/folderCreatedAsSideEffect",
                "name": "placeholder"
            }
        },
        "runAfter": {},
        "type": "ApiConnection"
    },
    "Delete_file": {
        "inputs": {
            "host": { "connection": { "name": "@parameters('$connections')['sharepointonline']['connectionId']" } },
            "method": "delete",
            "path": "/datasets/@{encodeURIComponent(encodeURIComponent('https://MY.sharepoint/LogicApps/'))}/files/@{encodeURIComponent(body('Create_file')?['Id'])}"
        },
        "runAfter": {
            "Create_file": [
                "Succeeded"
            ]
        },
        "type": "ApiConnection"
    }
},


答:
How about this? :)

```<code>class Main {

  public static void main(String[] args) {
    final int N = 6; // Your number here.
    System.out.println(result(N));
  }

  private static long result(final int n) {
    if (n == 0) {
      return 0;
    } else {
      return element(n) + result(n - 1);
    }
  }

  private static long element(final int n) {
    if (n == 1) {
      return 0L;
    } else if (n == 2) {
      return 1L;
    } else {
      return sqr(element(n - 2)) + sqr(element(n - 1));
    }
  }

  private static long sqr(final long x) {
    return x * x;
  }
}
</code>```

Here is the idea that separate function (element) is responsible for finding n-th element in the sequence, and result is responsible for summing them up. Most probably there is a more efficient solution though. However, there is only one parameter.

Body:
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

Body:
How about this? :)

class Main {

  public static void main(String[] args) {
    final int N = 6; // Your number here.
    System.out.println(result(N));
  }

  private static long result(final int n) {
    if (n == 0) {
      return 0;
    } else {
      return element(n) + result(n - 1);
    }
  }

  private static long element(final int n) {
    if (n == 1) {
      return 0L;
    } else if (n == 2) {
      return 1L;
    } else {
      return sqr(element(n - 2)) + sqr(element(n - 1));
    }
  }

  private static long sqr(final long x) {
    return x * x;
  }
}

Here is the idea that separate function (element) is responsible for finding n-th element in the sequence, and result is responsible for summing them up. Most probably there is a more efficient solution though. However, there is only one parameter.


问:
MongoDB No converter found capable of converting from type org.bson.types.ObjectId to type java.lang.Long
I have the following Model for a Customer that is used by Postgres and MongoDB. It works fine with Postgres but I get this error when I want to list all Customers from MongoDB:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  org.bson.types.ObjectId to type java.lang.Long

Here is my model class:

```<code>package com.example.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@XmlRootElement(name = "customer")
@Table(name = "customer")
public class Customer implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String firstName;
    private String lastName;

    public Customer() {
    }

    public Customer(String fn, String ln) {
        this.firstName = fn;
        this.lastName = ln;
    }

    public Customer(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @XmlAttribute(name = "id", required = false)
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @XmlAttribute(name = "first-name", required = false)
    @Column(name = "first_name", nullable = false)
    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlAttribute(name = "last-name", required = false)
    @Column(name = "last_name", nullable = false)
    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
</code>```

Here is my CustomerService to retrieve all Customers:

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.example.model.Customer;
import com.example.service.CustomerService;

@Service
@Import({ MongoConfiguration.class })
public class MongoCustomerService implements CustomerService{

    @Inject MongoTemplate mongoTemplate;

    Class<Customer> entityClass = Customer.class;

    @Override
    public Collection<Customer> getAllCustomers() {
        try {
             List<Customer> allCustomers = mongoTemplate.findAll(entityClass);
             return allCustomers;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

My pom.xml:

```<code>          </dependency>
            <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>
</code>```

答: Make field _id and annotate with @Id . Make type as Big Integer</p>

Body:
I have the following Model for a Customer that is used by Postgres and MongoDB. It works fine with Postgres but I get this error when I want to list all Customers from MongoDB:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  org.bson.types.ObjectId to type java.lang.Long

Here is my model class:

package com.example.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.lang.builder.ToStringBuilder;

@Entity
@XmlRootElement(name = "customer")
@Table(name = "customer")
public class Customer implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String firstName;
    private String lastName;

    public Customer() {
    }

    public Customer(String fn, String ln) {
        this.firstName = fn;
        this.lastName = ln;
    }

    public Customer(Long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @XmlAttribute(name = "id", required = false)
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @XmlAttribute(name = "first-name", required = false)
    @Column(name = "first_name", nullable = false)
    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @XmlAttribute(name = "last-name", required = false)
    @Column(name = "last_name", nullable = false)
    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

Here is my CustomerService to retrieve all Customers:

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.context.annotation.Import;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.example.model.Customer;
import com.example.service.CustomerService;

@Service
@Import({ MongoConfiguration.class })
public class MongoCustomerService implements CustomerService{

    @Inject MongoTemplate mongoTemplate;

    Class<Customer> entityClass = Customer.class;

    @Override
    public Collection<Customer> getAllCustomers() {
        try {
             List<Customer> allCustomers = mongoTemplate.findAll(entityClass);
             return allCustomers;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

My pom.xml:

          </dependency>
            <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.3.3.RELEASE</version>
        </dependency>


问:
Django - Cannot update model with model form gives str error
Im trying to let the user update some of the settings on their team but it doesn't seem to work correctly I want to update the name and if they accept users.

Views.py

```<code>@login_required
def teamsettings_general(request, team_pk):
    logged_in_user = get_object_or_404(User, pk=request.user.pk)
    requested_team = get_object_or_404(Team, pk=team_pk)
    if request.method == 'POST':
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
                if form.is_valid():
                    form.save()
                    messages.success(request, "The team has been updated!")
                    return redirect('teamsettings_general', team_pk=team_pk)
    for member in requested_team.teammembership_set.all().order_by('-leader'):
        if member.user.pk == request.user.pk and member.leader:
            feedback = FeedbackSupportForm()
            form = TeamSettings_GeneralForm(instance=team_pk)
            context = {
                'requested_team': requested_team,
                'feedback': feedback,
                'form' : form,
                'logged_in_user': logged_in_user,
            }
            return render(request, 'team/settings.html', context)
            break
        else: return redirect('team', team_pk)
</code>```

and my form.py

```<code>class TeamSettings_GeneralForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ('name', 'accepts_applications',)
</code>```

Now I just want it to update name and accepts_applications

```<code>'str' object has no attribute '_meta'

    form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
    if form.is_valid():
        form.save()
        messages.success(request, "The team has been updated!")
        return redirect('teamsettings_general', team_pk=team_pk)
logged_in_user = get_object_or_404(User, pk=request.user.pk)
requested_team = get_object_or_404(Team, pk=team_pk)
form = TeamSettings_GeneralForm(instance=team_pk) ...
for member in requested_team.teammembership_set.all().order_by('-leader'):
    if member.user.pk == request.user.pk and member.leader:
        feedback = FeedbackSupportForm()
        context = {
            'requested_team': requested_team,
            'feedback': feedback,
</code>```

Thanks in adbanvce

答:
You got the Team instance, but then ignored it and passed the PK to the form instead. It should be:</p>

```<code>form = TeamSettings_GeneralForm(instance=requested_team)
</code>```

Body:
Im trying to let the user update some of the settings on their team but it doesn't seem to work correctly I want to update the name and if they accept users.

Views.py

@login_required
def teamsettings_general(request, team_pk):
    logged_in_user = get_object_or_404(User, pk=request.user.pk)
    requested_team = get_object_or_404(Team, pk=team_pk)
    if request.method == 'POST':
        for member in requested_team.teammembership_set.all().order_by('-leader'):
            if member.user.pk == request.user.pk and member.leader:
                form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
                if form.is_valid():
                    form.save()
                    messages.success(request, "The team has been updated!")
                    return redirect('teamsettings_general', team_pk=team_pk)
    for member in requested_team.teammembership_set.all().order_by('-leader'):
        if member.user.pk == request.user.pk and member.leader:
            feedback = FeedbackSupportForm()
            form = TeamSettings_GeneralForm(instance=team_pk)
            context = {
                'requested_team': requested_team,
                'feedback': feedback,
                'form' : form,
                'logged_in_user': logged_in_user,
            }
            return render(request, 'team/settings.html', context)
            break
        else: return redirect('team', team_pk)

and my form.py

class TeamSettings_GeneralForm(forms.ModelForm):
    class Meta:
        model = Team
        fields = ('name', 'accepts_applications',)

Now I just want it to update name and accepts_applications

'str' object has no attribute '_meta'

    form = TeamSettings_GeneralForm(request.POST, instance=team_pk)
    if form.is_valid():
        form.save()
        messages.success(request, "The team has been updated!")
        return redirect('teamsettings_general', team_pk=team_pk)
logged_in_user = get_object_or_404(User, pk=request.user.pk)
requested_team = get_object_or_404(Team, pk=team_pk)
form = TeamSettings_GeneralForm(instance=team_pk) ...
for member in requested_team.teammembership_set.all().order_by('-leader'):
    if member.user.pk == request.user.pk and member.leader:
        feedback = FeedbackSupportForm()
        context = {
            'requested_team': requested_team,
            'feedback': feedback,

Thanks in adbanvce

Body:
You got the Team instance, but then ignored it and passed the PK to the form instead. It should be:

form = TeamSettings_GeneralForm(instance=requested_team)