text:
Q: Ошибка при парсинге JSON на JS Есть вот такой JSON (это, если важно, формула из экселя):
{"value":"=IF(C23=1,IF(C21=0,IF(C38=E38,CONCATENATE(TEXT(AB15,\"# ##0\"),\" - \u043f\u0435\u0440\u0432\u044b\u0435 \",W13,\" \u043c\u0435\u0441. \",\" \",),0),0),IF(C21=0,IF(C38=E38,CONCATENATE(TEXT(Z15,\"# ##0\"),\" - \u043f\u0435\u0440\u0432\u044b\u0435 \",W13,\" \u043c\u0435\u0441. \",\" \",),0),0))"}

При вызове JSON.parse к этому JSON возникает ошибка:
Uncaught SyntaxError: Unexpected token # in JSON at position 63

С чем это может быть связано?

A: В данном случае можно не использовать функцию JSON.parse.
Объект приходит от json_encode ($array) в PHP, а console.log вызывается из тега script, который выводится в документ через echo:
$json = json_encode ($array, JSON_HEX_TAG | JSON_HEX_AMP);
echo "<script>console.log ({$json})</script>";

Поэтому JSON.parse нет необходимости использовать, ведь JSON - это уже объект JS.


text:
Q: Trouble with django templating looping over a dict created from an xml response I am trying to display data in the html page from an xml request. I have converted the xml content to a dict using xmltodict. The xml data is like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<countriesRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.hotelbeds.com/schemas/messages">
    <from>1</from>
    <to>207</to>
    <total>207</total>
    <auditData processTime="30" timestamp="2020-10-01 18:10:02.666" requestHost="10.185.89.196" serverId="ip-10-185-88-253.eu-west-1.compute.internal.node.int-hbg-aws-eu-west-1.discovery" environment="[awseuwest1, awseuwest1a, ip_10_185_88_253]" release="cbd9f69ac1e7076b6ae86a8358f1e1bf26e00f44" internal="94d38b94f628408a9a0e41d7673d93a8"/>
    <countries>
        <country code="AD" isoCode="AD">
            <description>Andorra</description>
            <states>
                <state code="CA">
                    <name>CANILLO</name>
                </state>
                <state code="EN">
                    <name>ENCAMP</name>
                </state>
                <state code="ES">
                    <name>ESCALDES - ENGORDANY</name>
                </state>
                <state code="AN">
                    <name>ANDORRA</name>
                </state>
                <state code="AD">
                    <name>ANDORRA LA VELLA</name>
                </state>
                <state code="07">
                    <name>ANDORRA</name>
                </state>
                <state code="XX">
                    <name>NOT ASSIGNED</name>
                </state>
                <state code="OR">
                    <name>ORDINO</name>
                </state>
                <state code="SJ">
                    <name>SANT JULIA DE LORIA</name>
                </state>
                <state code="MS">
                    <name>LA MASSANA</name>
                </state>
            </states>
        </country>
        <country code="AE" isoCode="AE">
            <description>United Arab Emirates</description>
            <states>
                <state code="DU">
                    <name>UNITED ARAB EMIRATES</name>
                </state>
                <state code="FU">
                    <name>Fujairah</name>
                </state>
                <state code="AZ">
                    <name>Abu Dhabi</name>
                </state>
                <state code="AJ">
                    <name>Ajman</name>
                </state>
                <state code="07">
                    <name>UNITED ARAB EMIRATES</name>
                </state>
                <state code="XX">
                    <name>NOT ASSIGNED</name>
                </state>
                <state code="UQ">
                    <name>Umm Al Quwain</name>
                </state>
                <state code="RK">
                    <name>Ras Al Khaimah</name>
                </state>
                <state code="SH">
                    <name>Sharjah</name>
                </state>
            </states>
        </country>

however, when i use a for loop to display the countries with {% for country in response.CountriesRS.countries %}, I can only see 'country' being displayed. How can I properly loop through this dict?
This is how the variable 'response' shows up in html:
OrderedDict([('countriesRS', OrderedDict([('@xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'), ('@xmlns', 'http://www.hotelbeds.com/schemas/messages'), ('from', '1'), ('to', '203'), ('total', '207'), ('auditData', OrderedDict([('@processTime', '28'), ('@timestamp', '2020-10-01 21:09:13.151'), ('@requestHost', '10.185.89.196'), ('@serverId', 'ip-10-185-88-253.eu-west-1.compute.internal.node.int-hbg-aws-eu-west-1.discovery'), ('@environment', '[awseuwest1, awseuwest1a, ip_10_185_88_253]'), ('@release', 'cbd9f69ac1e7076b6ae86a8358f1e1bf26e00f44'), ('@internal', '23cbd9bfc8a64401824599cc99028cc0')])), ('countries', OrderedDict([('country', [OrderedDict([('@code', 'AD'), ('@isoCode', 'AD'), ('description', 'Andorra'), ('states', OrderedDict([('state', [OrderedDict([('@code', 'CA'), ('name', 'CANILLO')]), OrderedDict([('@code', 'EN'), ('name', 'ENCAMP')]), OrderedDict([('@code', 'ES'), ('name', 'ESCALDES - ENGORDANY')]), OrderedDict([('@code', 'AN'), ('name', 'ANDORRA')]), OrderedDict([('@code', 'AD'), ('name', 'ANDORRA LA VELLA')]), OrderedDict([('@code', '07'), ('name', 'ANDORRA')]), OrderedDict([('@code', 'XX'), ('name', 'NOT ASSIGNED')]), OrderedDict([('@code', 'OR'), ('name', 'ORDINO')]), OrderedDict([('@code', 'SJ'), ('name', 'SANT JULIA DE LORIA')]), OrderedDict([('@code', 'MS'), ('name', 'LA MASSANA')])])]))]), OrderedDict([('@code', 'AE'), ('@isoCode', 'AE'), ('description', 'United Arab Emirates'), ('states', OrderedDict([('state', [OrderedDict([('@code', 'DU'), ('name', 'UNITED ARAB EMIRATES')]), OrderedDict([('@code', 'FU'), ('name', 'Fujairah')]), OrderedDict([('@code', 'AZ'), ('name', 'Abu Dhabi')]), OrderedDict([('@code', 'AJ'), ('name', 'Ajman')]), OrderedDict([('@code', '07'), ('name', 'UNITED ARAB EMIRATES')])

A: Try to add .country to your chain:
{% for country in response.CountriesRS.countries.country %}
  <li>{{ country.description }}</li>
{% endfor %}

A: Problem solved. even though country is the list of countries in the xml string, when converted to dict, the term 'country' isnt repeated, hence isnt looping. using for country in response.CountriesRS.countries.country fixed the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maven 3 regression: Profile dependencies lost? I observed a change behavior between Maven 2 and Maven 3. Is this a bug or a feature? I couldn't find anything in the Maven 3.x Compatibility Notes
I use two different profiles to add dependencies for different environment in a multi-module project.
parent-pom:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>group</groupId>
    <artifactId>main</artifactId>
    <packaging>pom</packaging>
    <version>1.0.0-SNAPSHOT</version>

    <modules>
        <module>common</module>
        <module>portal</module>
    </modules>
</project>

The common-pom has the profile in it:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>group</groupId>
    <artifactId>common</artifactId>
    <packaging>jar</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <parent>
        <groupId>group</groupId>
        <artifactId>main</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <profiles>
        <profile>
            <id>development</id>
            <dependencies>
                <dependency>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                    <version>1.2.14</version>
                </dependency>
            </dependencies>
        </profile>
        <profile>
            <id>production</id>
            <dependencies>
                <dependency>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                    <version>1.1.1</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
</project>

The portal-pom has only the common dependency and should include the transitive dependency from the common module:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>group</groupId>
    <artifactId>portal</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <parent>
        <groupId>group</groupId>
        <artifactId>main</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <dependencies>
        <dependency>
            <groupId>group</groupId>
            <artifactId>common</artifactId>
            <version>1.0.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

Building this project (from the parent) via Maven2 mvn -P production package results in a WAR which includes the transitive dependency. (I used those simple dependencies for easy reproduction)
Executing via Maven3, I get only the common.jar in the WAR, but not the transitive dependency.
Is this a desired behavior?
To make things even "interesting": If one of the profiles is activated by default (explicit in the common-pom as the activation is not derived from the parent to the child modules) these transitive dependencies are always add to the portal.
But filtering or property-setting via profiles works as expected.

A: This comment solves it the one way:

the situation described above does work when profile activation using properties is used

With property activation (and not via -P) it works in Maven2 and 3
But the real solution was "caused" by the release plugin:
The profile must be submitted to release-plugin via
-Darguments=-Pproduction

A: Not a solution, but your use case looks similar to this open maven bug.  Interestingly, according to the bug details, it happens on earlier maven versions as well.


text:
Q: Modify Dynamic value within EventHandler I'm trying to build a tic tac toe program using a 3x3 board list running inside of a DynamicModule with a separate window displaying the current value and accepting clicks from the user. For now I'm just trying to use EventHandler to set any empty boxes to X's when clicked.
When I click on a box, I get the error

Part::pkspec1: The expression x cannot be used as a part specification.

Is this an issue with assigning a new value for board inside of the EventHandler?
How else should I structure this?
createBox[elem_] := Show[
  Graphics[{White, Rectangle[]}, Frame -> True,
   FrameStyle -> Thickness[.02], FrameTicks -> None],
  Graphics@Text[Style[elem, FontSize -> 100], {.5, .5}],
  ImageSize -> 150
  ]

DynamicModule[{board = Table[Table[" ", 3], 3]},
  CreateWindow[
   DocumentNotebook[
    (*Displaying grid*)
    Dynamic@Grid[
      Table[Table[
        EventHandler[
         createBox[board[[y]][[x]]]
         , {"MouseClicked" :> (
            If[board[[y]][[x]] == " ", board[[y]][[x]] = "X";];
            )}]
        , {x, 3}], {y, 3}],
      Spacings -> {0, 0}]
    ],
   WindowElements -> {}, WindowTitle -> "Tic Tac Toe",
   WindowSize -> All, Editable -> False, Selectable -> False,
   ShowCellBracket -> False, WindowFrameElements -> {"CloseBox"}];
  ];

A: Main issues:

*

*set part
board[[y]][[x]] = val will not work, you need board[[y, x]] = "X"
See: Part not behaving the way I expect it to

*x and y can't get inside :>
RuleDelayed holds and so after Table is done you will have board[[y, x]] in each item, instead of expected e.g. board[[2,1]] etc.
The way to go is to use With[{i=i},... idiom, see: Function in Table

*DynamicModule is 'a scoped rectangle in your screen'
So instead of DynamicModule[.. CreateWindow.. it should rather be CreateWindow[.. DynamicModule..
See e.g. IntroductionToDynamic
Secondary issues

*

*you don't need Dynamic around Grid, only content of board changes so you can put it inside createBox[Dynamic[...]]

*it is better to use === instead of == to compare non numerical values

*Show[Graphics...] can be combined in one Graphics[...]

*Unless you need it we can replace CreateWindow[NotebookDocument with CreateDocument (omg, I just realized the origin of this function name, thanks)

*but your notebook's options suggest it may be enough to use CreateDialog

*you can combine nested Table into one
Summing up:
createBox[elem_] := Graphics[
  { { White, Rectangle[] }
  , Text[Style[elem, FontSize -> 100], {.5, .5}]
  }
, ImageSize -> 150
, Frame -> True
, FrameStyle -> Thickness[.02]
, FrameTicks -> None
];

CreateDialog[
  DynamicModule[
    {board = ConstantArray[" ", {3, 3}]}
  , Grid[
      Table[ With[{x = x, y = y}
      , EventHandler[
          createBox[ Dynamic @ board[[y, x]]]
        , {"MouseClicked" :> If[board[[y, x]] === " ", board[[y, x]] = "X"]
          }
        ]]
      , {x, 3}, {y, 3}
      ]
    , Spacings -> {0, 0}
    ]
  ]
, WindowTitle -> "Tic Tac Toe"
, WindowSize -> All
];


text:
Q: Can't get into Ubuntu I've just upgraded to Ubuntu 20.04 from 18.04 and now I can't log in. It's giving me the lock screen with my name and password. I put my password in and it just stays the same.
I notice that there's another user logged in. That's me, because there is only 1 user on each of my machines and I'm set to automatic login.
What can I do, please?

A: Well, I found the fault myself. Because I noticed that I was already logged in, I re-booted and tried CTRL-ALT-BACKSPACE. That got me to another menu which had emergency things on it. I tried it and got in. Then I opened SETTINGS and changed the USER to log in. Then I re-booted and got the same screen, but I logged in and was taken to the desktop.
Chris


text:
Q: DIY Powered USB Hub PCB For my home project I need to connect multiple Arduino's to a Raspberry Pi. My raspberry pi controls everything in my house and the arduino's are going to be used to get sensor data.
I want to connect multiple Arduino's (up to maybe 20 or more) and I think it will be best to use a powered usb hub to do that (connected to the raspberry pi and use serial communication to get the data at the Raspberry Pi). To make it as best for my case I would like to build a PCB so I can make it exactly as I want, the only question is... how.
I have made multiple PCB's but I don't have a degree in it, I just want to make it for my hobby, can someone help me to start with it, or is it too difficult or can't it be done?

A: I would also advise against doing a USB hub if you're not familiar with PCB design. As mentioned in the comments already, you're much better off getting a commercially made USB hub.
PCB design involving high speed busses like USB usually need special consideration when laying out the board (like impedance matching, trace length matching, reducing cross-talk , etc). If you're not careful, you might end up with a hub that only works with USB 1.1, one that's unreliable, or not functional at all.
If you really want to give it a go, find a USB hub chip that fits your requirements using the parametric parts selector of your favourite electronic parts distributor. The datasheet for the chip usually contains a schematic of a reference design that you can use in your design.


text:
Q: org.springframework.aop.framework.AopConfigException Error in WebLogic 12c I am in the process of upgrading WebLogic Server 11g (10.3.6.0) to 12c (12.2.1.3.0).
I installed the war file without a problem onto the 12c server. Then, I tried to start the module. I was getting weblogic.application.ModuleException: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.springframework.aop.framework.AopConfigException error due to missing a particular class file. It seems like the class file belongs to "spring-aop-2.5.2.jar."
When I deployed the same war file onto the WebLogic Server 11g environment, I did not observe any problem. I ensured that "spring-aop-2.5.2.jar" exists in the war file. I am using the version 2.5.2 for the SpringFramework. I suspect it may also be a problem.
Based on my research, some people suggested to append <package-name>net.sf.cglib.*</package-name> into the to <prefer-application-packages> in your weblogic-application.xml. I do not have the weblogic-application.xml in my project or in the war file. I only see the file on the server. Although I appended the tag into weblogic-application.xml, I am still geting the same error.
Should I configure anything else based on my description? Any idea?

A: Having the same issue, I got it to work by putting both spring and cglib jars in the ear APP-INF/lib folder and using the following META-INF/weblogic-application.xml
<?xml version='1.0' encoding='UTF-8'?>
<weblogic-application xmlns="http://xmlns.oracle.com/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-application http://xmlns.oracle.com/weblogic/weblogic-application/1.3/weblogic-application.xsd">
    <prefer-application-packages>
        <package-name>net.sf.cglib.*</package-name>
        <package-name>org.springframework.*</package-name>
    </prefer-application-packages>
</weblogic-application>

From my understanding, it's important that:

*

*Both cglib and spring jars are in the same classpath folder

*Both are present in "prefer-application-packages"

Using "prefer-application-packages" in weblogic.xml inside my .war file did not seem to work for some reason.

A: You should modify your weblogic.xml file to use the proper libraries with prefer-application-packages. However, do not forget to include this.
<prefer-web-inf-classes>false</prefer-web-inf-classes>

Oracle states here

Note that in order to use prefer-application-packages or prefer-application-resources, prefer-web-inf-classes must be set to false.


text:
Q: What are all of the points around a circle? Is there a formula provided degree rotation to find a given point? I have a camera in 3-space which I want to spin around the y-axis. The distance remains the same, but the x- and z-positions change.

The above is the direction I need to rotate. It's a top-down view (looking at xz-plane). The y-position never changes, but the x- and z-positions do. The distance between the camera and origin should also not change.
Say the initial point (as seen in the image) is $(0,0,-10)$, a half-rotation will leave me at $(0,0,10)$, a quarter at $(10,0,0)$, and so on. My problem is finding the inbetween points as I don't know of any formula.
Say I rotate only $15°$, what would the co-ordinates of the camera be?

A: The path of your camera can be parametrised by
$$ [10\cos t, 0, 10\sin t]
$$
where $t$ represents the angle. To set the initial point, just offset $t$.


text:
Q: The maximum eigenvalue of the sum of two matrix Suppose there are two matrix $A$ and $B$. The components of each matrix is non-negative.
And
$$Ax_1=\lambda_1 x_1  $$ where $\lambda_1$ is the maximum eigenvalue of $A$.
Similarly
$$Bx_2=\lambda_2 x_2  $$ where $\lambda_2$ is the maximum eigenvalue of $B$.
Let $C = A+B$
And
$$Cx=\lambda x  $$ where $\lambda$ is the maximum eigenvalue of $C$.
From wiki(https://en.wikipedia.org/wiki/Matrix_norm), it shows that $$\left\| A+B \right\|\le \left\| A \right\|+\left\| B \right\|$$
The maximum eigenvalue is 2 norm. So no matter the components are negative or not, $$\lambda\le \lambda_1+\lambda_2$$

A: Yes. By Gelfand's formula, if $\|\cdot\|$ is any matrix norm, then $\rho(A)=\lim_{n\to\infty}\|A^n\|^{1/n}$. Now, simply take $\|\cdot\|$ as the maximum row sum norm, i.e. $\|A\|=\max\limits_i\sum_j|a_{ij}|$. Since both $A$ and $B$ are nonnegative, we have $0\le A^n\le(A+B)^n$ entrywise. Hence the result follows.


text:
Q: Circular reference for Repository in Symfony 5 I try to follow this tutorial : https://www.thinktocode.com/2018/03/05/repository-pattern-symfony/.
It's suppose to help structure your Repository.
But when i get to this point :
final class ProductRepository
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * @var ObjectRepository
     */
    private $objectRepository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
        $this->objectRepository = $this->entityManager->getRepository(Product::class);
    }

    public function find(int $productId): Product
    {
        $product = $this->objectRepository->find($productId);
        return $product;
    }

    public function findOneByTitle(string $title): Product
    {
        $product = $this->objectRepository
            ->findOneBy(['title' => $title]);
        return $product;
    }

    public function save(Product $product): void
    {
        $this->entityManager->persist($product);
        $this->entityManager->flush();
    }
}

And testing my Repository with this test case :
<?php

namespace App\Tests\Repository;

use App\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class ProductRepository_KernelTest extends KernelTestCase
{

    private ?ProductRepository $_productRepository;

    protected function setUp(): void
    {
        $kernel = self::bootKernel();
        $this->_productRepository = self::$container->get(ProductRepository::class);
    }

    public function test_findAllProductNatByLabelForLabelEmptyReturnTenProduct()
    {
        dump($this->_productRepository->findAllProductsByLabel('AACIFEMINE'));
        die();
    }
}

It loop endlessly.
I think it's due to this code :
public function __construct(EntityManagerInterface $entityManager)
{
    $this->entityManager = $entityManager;
    $this->objectRepository = $this->entityManager->getRepository(Product::class); // <-----
}

As it call the ProductRepository constructor inside of this same constructor... So i guess it's why that loop
So I don't know. Is this tutorial just wrong or not up to date ?

A: https://www.thinktocode.com/2018/03/05/repository-pattern-symfony/#comment-4155200782

Maciej,
You are correct that in these example we are using 2 repositories. The
object repository from doctrine inside our own custom repository. This
allows use to be decoupled from doctrine's repository and still change
this in the future. This means to not set your custom repository as
the default repository in your entity.
You can get rid of inject the object repository, and in so only be
using 1 repository by implementing a BaseRepository class in which you
create the basic findBy, findOneBy, createQueryBuilder yourself. Take
a look at the EntityRepository in Doctrine/ORM. This might be a good
follow up topic to go over in a future article to create a better
solution then I suggested in here.


text:
Q: Using condition variable to trigger threads one at a time Given this example code taken and modified from cplusplus.com
#include "stdafx.h"
// condition_variable example
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id(int id) {
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready)
    {
        std::cout << "waiting for unlock";
        cv.wait(lck);
    }

    std::cout << "thread " << id << '\n';
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    cv.notify_one();
}

void go() {
    std::unique_lock<std::mutex> lck(mtx);
    ready = true;
    cv.notify_one();
}

int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i<10; ++i)
        threads[i] = std::thread(print_id, i);

    std::cout << "10 threads ready to race...\n";
    go();                       // go!

    for (auto& th : threads) th.join();

    return 0;
}

Does this properly block each thread until one is woken up by the notify_one() call? or is this essentially unlocking all threads?
I am attempting to start all the threads up at the same time, then block until the previous one finishes. The order is not important, but i can't have them executing the meat of the code all at the same time.

A: Your code works in the sense that no two worker threads can execute this code:
  std::cout << "thread " << id << '\n';
  std::this_thread::sleep_for(std::chrono::milliseconds(2000));
  cv.notify_one();

concurrently, but this is not entirely because your use of std::condition_variable unblocks the worker threads one at a time. In fact, you haven't really changed the behavior from the original cplusplus.com example. In both programs the critical section of code is protected by a locked mutex, which guarantees that only one thread can hold the lock at any time.
Your use of std::condition_variable to "serialize" the execution of the threads does not by itself prevent concurrent execution because calling notify_one() doesn't guarantee that only one thread is released from wait(). The reason is that threads are allowed to spuriously return from wait() without any notification:

The function will unblock when signaled by a call to notify_one() or a
  call to notify_all(), or spuriously.

In a sense you are being saved by the mutex. If you wrote your worker function like this:
void print_id(int id) {
    {
        std::unique_lock<std::mutex> lck(mtx);
        while (!ready)
        {
            std::cout << "waiting for unlock";
            cv.wait(lck);
        }
    }

    std::cout << "thread " << id << '\n';
    std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    cv.notify_one();
}

This code unlocks the mutex as soon as the thread is unblocked. This would not be safe because multiple threads can reach your critical section without the protection of the locked mutex.
So I think your program does what you want - runs a section of code in many threads without concurrency - but perhaps not for the reason you expect.

The idiomatic way of blocking on a condition is to define a predicate test that passes when the thread is ready to proceed but fails otherwise, and check it in a loop:
std::unique_lock<std::mutex> lock(mutex);
while (!predicate)
    condition.wait(lock);

This idiom handles spurious wake-ups properly because the predicate test will fail and the thread will call wait() again.
Although your program looks very similar to this, it doesn't quite do this because your predicate allows all the threads to proceed, not just one, and that isn't what you stated that you want. It turns out to work anyway because of the locked mutex.
You could unblock your threads one at a time in order by changing your predicate test so that it passes only for the next thread, and by using notify_all():
#include <atomic>
...
std::atomic<int> ready(-1);

void print_id(int id) {
   {
      std::unique_lock<std::mutex> lck(mtx);
      while (ready != id)
         cv.wait(lck);
   }

   std::cout << "thread " << id << '\n';
   std::this_thread::sleep_for(std::chrono::milliseconds(2000));
   ++ready;
   cv.notify_all();
}

void go() {
   ready = 0;
   cv.notify_all();
}

int main()
{
   std::thread threads[10];
   // spawn 10 threads:
   for (int i = 0; i<10; ++i)
      threads[i] = std::thread(print_id, i);

   std::cout << "10 threads ready to race...\n";
   go();                       // go!

   for (auto& th : threads) th.join();

   return 0;
}

Note how this predicate test ready != id only passes when the thread should proceed. I also used a std::atomic<int> for ready so that notification does not require locking the mutex.
This revised predicate code is correct, but one drawback is that we have to change notify_one() to notify_all() to make sure that we wake up the next thread. This wakes up all the threads only to put all but one of them back to waiting, which costs a little bit of performance. One way to optimize this would be to create N condition_variable instances (e.g. in an array) and have each thread wait on its own condition_variable instance.

A: After cppreference:
void notify_one();

If any threads are waiting on *this, calling notify_one unblocks one of the waiting threads.

So it's unlocking just one thread and you cannot say, which one. In order to unblock all threads you need to use void notify_all();
If you're attempting to run all threads at once you should use notify_all() in go() and then notify_one() for sequential run in print_id(int)
Remember that even when using notify_all() all threads will try to lock lck, but only one will succeed.


text:
Q: I am using MUI timePicker, but I am not able to select the minutes in that. It's getting closed down as soon as I select the hour. How to fix this? Sharing my code snippet below:
<DesktopTimePicker
      orientation="portrait"
      value={value ?? null}
      onChange={handleDateChange}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="standard"
          onBlur={onBlur}
          fullWidth
          sx={{ m: 1.5 }}
        />
      )}
    />

This is my function for handling timeChange,
const handleDateChange = (date) => {
    onValueChange(date);
  };

How to fix this issue ?


text:
Q: How to handle full width with StencilJS Let's assume we have a very simple component as below
@Component({
  tag: 'custom-button',
})
export class CustomButton {
  render() {
    return <button class={{ 'button--blue': true }}>Press Me</button>
  }
}

The component above will render as below on the DOM tree
<custom-button class="hydrated">
  <button class="button--blue">Press Me</button>
</custom-button>

Now everything is working fine. The problem comes only if we define width: 100% in button--blue class. It will not work because width: 100% of custom-button is essentially pointless.
I know we can solve the problem by using Host element and applying css on it
@Component({
  tag: 'custom-button',
})
export class CustomButton {
  render() {
    return (
      <Host class={{ 'full-width': true }}><button class={{ 'button--blue': true }}>Press Me</button></Host>
    )
  }
}

I am looking for alternative solution, reason being we need to purposely create another generic utility css class just because we are using stencil which I feel its not optimal.
Ultimately it will be great if my CSS is not polluted and I only have button--blue class.
Wondering if there is any alternatives available? Maybe somehow we can omit custom-button element when we render to the DOM tree?


text:
Q: Include "space" check in email adress flutter Can someone please tell me how to
add "space" check in email address? I
have tried email.contains("") bt it didnt
worked.
I don't get a error when i type invalid email
 import 'dart:async';

class Validators{
  final validEmail = StreamTransformer<String, String>.fromHandlers(
    handleData: (email, sink){
      if(email.contains('@')){
        sink.add(email);
      }else if(email.contains(" ")){
          sink.addError('Enter a valid email');
      }else{
          sink.addError('Enter a valid email');

      }
    }
  );

  final validPassword  = StreamTransformer<String, String>.fromHandlers(
    handleData: (password, sink){
      if(password.length > 4){
        sink.add(password);
      }else{
        sink.addError('Enter a valid password');
      }
    }
  );
}

I want "invalid email" error to be displayed as this

A: Contains works perfectly for me.
void main() {
  bool check;
  String email = 'tes t@test.com';

  check = email.contains(' ');

  print(check); // true
}

I have tried it on DartPad
Perhaps you forgot to put whitespace between quotes.

A: Please don't use hand-rolled regex to validate email addresses.  For one, spaces are in fact permitted in email addresses, as long as they are properly quoted, so the original question is already at fault.  Also, these regex all reject many perfectly valid email addresses, such as my autoresponder at fred&barney@stonehenge.com.  (Go ahead... send it email!)
If you're going to validate email, use https://pub.dev/packages/email_validator, which I have confirmed follows the proper rules.

A: The error you are having is the order in which you validate the email. You should first check for spaces and then for the @ character.
handleData: (email, sink){
      if(email.contains(" ")){
          sink.addError('Enter a valid email');
      } else if(email.contains('@')){
        sink.add(email);
      } else{
          sink.addError('Enter a valid email');

      }
    }

A: You can also use a Regular Expression to validate an email address. Although, regular expressions are a bit complex to understand, they are very good for validating strings and checking patterns. Here's an example of  a RegEx to validate an email address in Flutter/Dart
// String p to define pattern
String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" +
            "\\@" +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
            "(" +
            "\\." +
            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
            ")+";
            //Convert string p to a RegEx
            RegExp regExp = new RegExp(p);
            //If email address matches pattern
            if (regExp.hasMatch(emailAddress)) {
              return 'Email is Valid';
            }else{ //If it doesn't match
              return 'Email is not valid';
            }

A: The simplest solution to this is to call trim() on your email value before passing it. Something like this:
new AuthenticationService()
                  .signIn(_emailTextController.value.text.trim(),
                      _passwordTextController.value.text.trim())


text:
Q: Capturing UIScrollView off screen content I'm working with a UIScrollView which can be used in either orientation and contains a number of subviews:
// in viewDidLoad

mainScrollView = (UIScrollView *)self.view;

mainScrollView.contentSize = CGSizeMake(1024, 1432);

I'm trying to capture a screen shot of the entire scroll view with all its subviews, including what is not currently visible on screen. The following captures only what is visible on screen at the time of capture:
// make screenshot

 UIGraphicsBeginImageContext(mainScrollView.bounds.size);

 [mainScrollView.layer renderInContext:UIGraphicsGetCurrentContext()];

 UIImage *screenImg = UIGraphicsGetImageFromCurrentImageContext();

 UIGraphicsEndImageContext();

 // save screenshot in docs dir

 NSData *pngData = UIImagePNGRepresentation(screenImg);

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 NSString *documentsDir = [paths objectAtIndex:0];

 [pngData writeToFile:[documentsDir stringByAppendingPathComponent:@"screen1.png"]

                 options:NSDataWritingAtomic error:nil];

Adding the following before making the screen shot was the only way I could fine that enabled me to capture the entire scroll view:
 // capture off-screen content

 mainScrollView.frame = CGRectMake(0, 0, 1024, 1432);

This capture is fine and includes all subviews. The problem is that once I have made the screen shot, my scroll view becomes unresponsive so I can no longer scroll (or pan sideways if in portrait mode). If I rotate the device, the problem seems to rectify itself and I can scroll and pan normally.
I'm sure I'm missing something very simple that is needed to get my scroll view working normally straight after the screen shot is taken.
Any suggestions much appreciated!

A: The problem is that you are setting the frame size equals to the content size. When the frame size is equals or greater to the content size you can't scroll.
You have to find a way to identify when the screen shot have finished and change the frame size back to the previous size. So:
CGRect oldFrame = mainScrollView.frame;

// do your logic to screenshot

mainScrollView.frame = oldFrame;


text:
Q: How to show that the polynomilal $\sum_{k=0}^n \dfrac 1{3^{k^2}}x^k$ has $n$ distinct real roots for any positive integer $n$ ? From this Rational roots of polynomials ; How might we show that the polynomilal $\sum_{k=0}^n \dfrac 1{3^{k^2}}x^k$ has $n$ distinct real roots $\forall n \in \mathbb N$ ?

A: Evaluating the polynomial at $x=-3^{2m}$ for $0\le m\le n$ yields
$$
\sum_{k=0}^n \frac1{3^{k^2}} (-3^{2m})^k = (-1)^m 3^{m^2} \sum_{k=0}^n (-1)^{m-k} 3^{-(m-k)^2}.
$$
In the sum on the right-hand side, the $k=m$ term equals $1$, while the sum of all the other terms is less than $1$ in absolute value (one can show). Therefore the sign of the polynomial at $-3^{2m}$ is equal to $(-1)^m$. Since this is true for the $n+1$ points $m=0,1,\dots,n$, the polynomial must vanish at least $n$ times.


text:
Q: How to pass a function only after an entire array has been read and not for each element? I'm trying to run a function when reading an array, but instead of running the function to each element, which I'm currently using forEach for, I want to make the script to read the entire array and then pass a function.
What I'm trying to say is this:
data.forEach(movie => {
    // Log each movie's title
    //console.log(movie.title);

    // Check if the userWord matches
    if (movie.title.toUpperCase().includes(userWord.toUpperCase())) {
        alert("YES");
    } else {
        alert("NO").
    }
});

Let's say my array is: array = ["Aa", "Ba", "Ca", "Da"];
If the user enters: a, then the script would alert("YES") four times, and I want to make it alert just once, at the end of the iteration.
For the same example, if the users enters: B, then the script would first alert("NO") once, then alert("YES"), then alert("YES") 2 times, and I want to make it just alert("YES")once, in the end.
Finally, if the users enters: Ferrari, then the script would alert("NO") four times, and I just want it to alert("NO") at the end.
I tried to make it very clear here, that's why the three "cases" of what is happening.
In the end, I want to know if there is a method that is kinda the opposite of the forEach or the common for. Something that just executes the function after reading the entire array.

A: I think closest what you can get is some. Here is example

let data = ["test","hello", "hello1"];
let userWord = "el";
let res =  data.some(movie => movie.toUpperCase().includes(userWord.toUpperCase()));
console.log(res) // prints true- means there was at least one "match", so you can alert

A: You could use the filter array function to filter array elements that match your criteria and then finally alert only if a match is found. Using this method you could get all the elements that have matched to your userWord. That is, the match array will contain all the possible matches.

var data = ['Aa', 'Bb', 'Cc', 'Dd'];
var flag = false;
var userWord = 'F'
var match = data.filter(movie => movie.indexOf(userWord) !== -1);
if(match.length)
console.log('YES');
else
console.log('NO');

A: *

*Change the alert to a bool variable

*Remove else (it would only overwrite any match)

*if bool statement outside the loop to perform actions

if you want a list of the results, you should store the names in an array and outside of the loop - print.
see below:
Non-loop method:
data = ["test","hello", "hello1"];
search = "lo";
const matches = data.filter(movie => movie.includes(search));

alert(matches) //array of only matches - only has hello and hello 1

I don't know if there are performance gains against a loop... I suppose you could do a side by side comparison on a large dataset
Loop method:
var matches = "";
data.forEach(movie => {
    // Check if the userWord matches
    if (movie.title.toUpperCase().includes(userWord.toUpperCase())) {
        matches += movie.title + "<br> ";
    }
});

if (matches.length > 0)
{
    document.getElementById("results").innerHTML = matches;
} else {
    alert("No match found");
}

You'll see more customization on the first loop, but I think filtering data first is the way to go.

A: If I understand the question correctly, I believe you want to execute something if a predicate matches at least one of the items in the array (correct me if I'm wrong). For that you can use the some method like so:
if (movies.some((movie) => movie.toUpperCase().includes(userWord.toUpperCase()))) {
  alert('YES');
} else {
  alert('NO');
}


text:
Q: Add footer to master page O365 How can I add a footer to a master page in Office 365 SharePoint Online site, Microsoft has recommended not to create our own master pages, so what's the solution for it now? it is urget for me, please any suggestion

A: The "best practice" is "JS injection". This is JavaScript that runs in the page.
There is lots more detail here in this excellent MVA course here:
http://www.microsoftvirtualacademy.com/training-courses/transform-sharepoint-customizations-to-sharepoint-app-model

A: *

*create css style sheet and add styles.

*Open the master page you are using in sharepoint designer 2013 by going to All files>catalogues>masterpage> select the masterpage you are using.html and then register it in the master.

*I followed this and it worked for me Add footer

A: 1) Open Olso.master in Edit mode
2) Select Save as action to save it as a custom master page, let's name it, lets say, helsinki.master (helsinki.master is not associated with html page, it means it could be edited directly )
3) Open helsinki.master and find DeltaPlaceHolderFooter
4) To specify custom footer, replace the block
<SharePoint:AjaxDelta id="DeltaPlaceHolderFooter" BlockElement="true" runat="server">
   <SharePoint:DelegateControl runat="server" ControlId="PageFooter" AllowMultipleControls="false" />
</SharePoint:AjaxDelta>

with
<SharePoint:AjaxDelta id="DeltaPlaceHolderFooter" BlockElement="true" runat="server">
  <%--SharePoint:DelegateControl runat="server" ControlId="PageFooter" AllowMultipleControls="false" /--%>

Some fancy footer is displayed here.

</SharePoint:AjaxDelta>

Result


text:
Q: How to align equation more to the left?
How I can do the numeration and equation format like shown in the picture above?
I tried this code:
\documentclass[12pt,a4paper,fleqn, twocolumn]{article}
\usepackage[margin=1.5cm]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T2A]{fontenc}
\usepackage[russian]{babel}
\usepackage{titlesec}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{esint}
    \begin{align}
    \begin{array}{l}
    P^{TE}_q = Re\frac{j|E_0|^2}{2\eta}\\
    \times \oiint\limits_S(A^i_qA^{i*}_q\bar{M}^{(1)}_q \times \bar{N}^{(1)*}_q + A^i_qA^{s*}_q\bar{M}^{(1)}_q \times \bar{N}^{(4)*}_q\\
    + A^s_qA^{i*}_q\bar{M}^{(4)}_q \times \bar{N}^{(1)*}_q + A^s_qA^{s*}_q\bar{M}^{(4)}_q \times \bar{N}^{(4)*}_q)\\
    \cdot \hat{r}ds
    \end{array}\\
    \begin{array}{l}
    P^{TM}_q = Re\frac{j|E_0|^2}{2\eta}\\
    \times \oiint\limits_S(B^i_qB^{i*}_q\bar{N}^{(1)}_q \times \bar{M}^{(1)*}_q + B^i_qB^{s*}_q\bar{N}^{(1)}_q \times \bar{M}^{(4)*}_q\\
    + B^s_qB^{i*}_q\bar{N}^{(4)}_q \times \bar{M}^{(1)*}_q + B^s_qB^{s*}_q\bar{M}^{(4)}_q \times \bar{M}^{(4)*}_q)\\
    \cdot \hat{r}ds
    \end{array}
    \end{align}

but only get this

A: Something like this? Observe that I would recommend not specifying the option fleqn. I recommend using a single align environment and no array environments.

\documentclass[12pt,a4paper,twocolumn]{article} % no 'fleqn' option
\usepackage[margin=1.5cm]{geometry}
\usepackage{mathtools,esint}
\usepackage[utf8]{inputenc}
\usepackage[T2A]{fontenc}
\usepackage[russian]{babel}

\let\Re\relax
\DeclareMathOperator{\Re}{Re} % redefine '\Re'
\DeclarePairedDelimiter{\abs}{\lvert}{\rvert}

\begin{document}
\hrule % just to illustrate width of column
\setcounter{equation}{24} % just for this example
\begingroup
\thickmuskip=0mu
\medmuskip=0mu
\thinmuskip=0mu
\small
\begin{subequations}
\begin{align}
P^{\mathrm{TE}}_q &= \Re \frac{j\abs{E_0}^2}{2\eta} \notag\\
&\quad\times \oiint\limits_S \Bigl(
     A^i_qA^{i*}_q\bar{M}^{(1)}_q \times \bar{N}^{(1)*}_q
   + A^i_qA^{s*}_q\bar{M}^{(1)}_q \times \bar{N}^{(4)*}_q \notag\\
&\qquad
   + A^s_qA^{i*}_q\bar{M}^{(4)}_q \times \bar{N}^{(1)*}_q
   + A^s_qA^{s*}_q\bar{M}^{(4)}_q \times \bar{N}^{(4)*}_q \Bigr) \notag\\
&\qquad \cdot \hat{r}\mkern3mu ds \\[1ex]
P^{\mathrm{TM}}_q &= \Re\frac{j\abs{E_0}^2}{2\eta} \notag\\
&\quad\times \oiint\limits_S \Bigl(
    B^i_qB^{i*}_q\bar{N}^{(1)}_q \times \bar{M}^{(1)*}_q
  + B^i_qB^{s*}_q\bar{N}^{(1)}_q \times \bar{M}^{(4)*}_q \notag\\
&\qquad
  + B^s_qB^{i*}_q\bar{N}^{(4)}_q \times \bar{M}^{(1)*}_q
  + B^s_qB^{s*}_q\bar{M}^{(4)}_q \times \bar{M}^{(4)*}_q\Bigr) \notag\\
&\qquad\cdot \hat{r}\mkern3mu ds
\end{align}
\end{subequations}
\endgroup
\hrule % just to illustrate width of column
\end{document}

Addendum: If you happened to be pressed for space in your document, it's actually possible to typeset each equation in 3 rows instead of the 4 used both in your initial screenshot and in the answer above.
The following solution also uses \widebar (a macro provided by the mathabx package) instead of \bar as in the answer above. Using \widebar provides a "look" that replicates more closely the look of the screenshot you posted.

\documentclass[12pt,a4paper,twocolumn]{article} % no 'fleqn' option
\usepackage[margin=1.5cm]{geometry}
\usepackage{mathtools,mathabx,esint}
\usepackage[utf8]{inputenc}
\usepackage[T2A]{fontenc}
\usepackage[russian]{babel}

\let\Re\relax
\DeclareMathOperator{\Re}{Re} % redefine '\Re'

\DeclarePairedDelimiter{\abs}{\lvert}{\rvert}

\begin{document}
\setcounter{equation}{24} % just for this example

\begin{subequations}
\begin{align}
&P^{\mathrm{TE}}_q = \Re \frac{j\abs{E_0}^2}{2\eta}
\times \oiint\limits_{S} \Bigl\{
     A^i_qA^{i*}_q\widebar{M}^{(1)}_q \times \widebar{N}^{(1)*}_q \notag\\
&\quad+ A^i_qA^{s*}_q\widebar{M}^{(1)}_q \times \widebar{N}^{(4)*}_q
   + A^s_qA^{i*}_q\widebar{M}^{(4)}_q \times \widebar{N}^{(1)*}_q  \notag\\
&\qquad+ A^s_qA^{s*}_q\widebar{M}^{(4)}_q \times \widebar{N}^{(4)*}_q \Bigr\}  \hat{r}\, ds \\[1ex]
&P^{\mathrm{TM}}_q = \Re\frac{j\abs{E_0}^2}{2\eta}
\times \oiint\limits_{S} \Bigl\{
    B^i_qB^{i*}_q\widebar{N}^{(1)}_q \times \widebar{M}^{(1)*}_q \notag \\
&\quad+ B^i_qB^{s*}_q\widebar{N}^{(1)}_q \times \widebar{M}^{(4)*}_q
  + B^s_qB^{i*}_q\widebar{N}^{(4)}_q \times \widebar{M}^{(1)*}_q \notag\\
&\qquad+ B^s_qB^{s*}_q\widebar{M}^{(4)}_q \times \widebar{M}^{(4)*}_q\Bigr\}  \hat{r}\, ds
\end{align}
\end{subequations}

\end{document}

A: A different proposal, with more lines but shorter; typesetting math in two column format is always a pain.
\documentclass[12pt,a4paper,fleqn,twocolumn]{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\usepackage[margin=1.5cm]{geometry}
\usepackage{titlesec}
\usepackage{graphicx}
\usepackage{amsmath,mathtools}
\usepackage{esint}

\let\Re\relax
\DeclareMathOperator{\Re}{Re}

\begin{document}

\begin{align}
\begin{split}
P^{TE}_q ={}& \Re\frac{j|E_0|^2}{2\eta} \\
{} \times \mathop{\smash[b]{\oiint\limits_S}}\Bigl(
  &  A^i_qA^{i*}_q\bar{M}^{(1)}_q \times \bar{N}^{(1)*}_q \\
  &+ A^i_qA^{s*}_q\bar{M}^{(1)}_q \times \bar{N}^{(4)*}_q \\
  &+ A^s_qA^{i*}_q\bar{M}^{(4)}_q \times \bar{N}^{(1)*}_q \\
  &+ A^s_qA^{s*}_q\bar{M}^{(4)}_q \times \bar{N}^{(4)*}_q \Bigr) \cdot \hat{r}\,ds
  \end{split}
\\
\begin{split}
P^{TM}_q ={}& \Re\frac{j|E_0|^2}{2\eta} \\
{} \times \mathop{\smash[b]{\oiint\limits_S}}\Bigl(
 & B^i_qB^{i*}_q\bar{N}^{(1)}_q \times \bar{M}^{(1)*}_q \\
 &+ B^i_qB^{s*}_q\bar{N}^{(1)}_q \times \bar{M}^{(4)*}_q \\
 &+ B^s_qB^{i*}_q\bar{N}^{(4)}_q \times \bar{M}^{(1)*}_q \\
 &+ B^s_qB^{s*}_q\bar{M}^{(4)}_q \times \bar{M}^{(4)*}_q \Bigr) \cdot \hat{r}\,ds
\end{split}
\end{align}

\end{document}

The \smash[b] construction is to avoid the big integral pushes the line below it too much down. Wrapping it in \mathop ensures correct horizontal spacing.


text:
Q: Import-Module PoshRSJob with Executionpolicy RemoteSigned I downloaded the PoshRSJob module. When I try to import the module it always throws the following error (translated from German):
PS C:\WINDOWS\system32> ipmo "C:\Program Files\WindowsPowerShell\Modules\PoshRSJob"
ipmo : The File "C:\Program Files\WindowsPowerShell\Modules\PoshRSJob\Scripts\TabExpansion.ps1" could not be loaded. The File "C:\Program
Files\WindowsPowerShell\Modules\PoshRSJob\Scripts\TabExpansion.ps1" is not signed digitally. You can't execute this script on your system. More information: "about_Execution_Policies" unter
"http://go.microsoft.com/fwlink/?LinkID=135170"..
In Zeile:1 Zeichen:1
+ ipmo "C:\Program Files\WindowsPowerShell\Modules\PoshRSJob"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : Sicherheitsfehler: (:) [Import-Module], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand

Our ExecutionPolicy is RemoteSigned
Is there a way to get this module working in a RemoteSigned environment, without Bypassing the Executionpolicy everytime I use the Module in a Script, and without setting the ExecutionPolicy to Unrestricted?

A: It might be that Windows is treating the files as remote files despite being on your machine locally. Sometimes Windows will know when files have come from the internet (for example if you download through IE or Edge instead of say, Firefox). Behind the scenes, this is storing zone information in an alternate data stream associated with the file, but that can be modified or stripped off.
Right click the PSD1, PS1, PSM1 files inside the module and choose "Properties" and if there's an unblock option, make sure it's unticked.
Alternatively you could run the cmdlet Unblock-File if you have PowerShell 5.1 or greater.


text:
Q: how to navigate from GamePage.xaml.cs to Game1.cs in vs2012(monogame library) actually i'm trying to develop a small windows store game.so in order to create game,game libraries are required.so i want to use xna framework.so i downloaded monogame library which supports xna.it has two pages(GamePage.xaml.cs,Game1.cs) and one designer page(GamePage.xaml).when i set the color of the Game.cs to Blue it is not getting reflected in the xaml page.
  Game1.cs page:

  using Microsoft.Xna.Framework;
 using Microsoft.Xna.Framework.Graphics;

 namespace GameName1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
    GraphicsDeviceManager _graphics;
    SpriteBatch _spriteBatch;

    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        _spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.Blue);

        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }
}
}

  GamePage.xaml.cs:
 using Windows.UI.Xaml;
 using Windows.UI.Xaml.Controls;
 using MonoGame.Framework;
 using Microsoft.Xna.Framework.Graphics;
 using Microsoft.Xna.Framework;
 using MonoGame.Framework;
 using Windows.ApplicationModel.Activation;

namespace GameName1
{
  /// <summary>
  /// The root page used to display the game.
  /// </summary>
public sealed partial class GamePage : SwapChainBackgroundPanel
{
    readonly Game1 _game;

    public GamePage(string launchArguments)
    {
        this.InitializeComponent();

        // Create the game.
        _game = XamlGame<Game1>.Create(launchArguments, Window.Current.CoreWindow, this);
    }
}

}

A: actually it was some project creation error.try creating a new project it will work.sometimes clean and rebulid the solution might work.


text:
Q: Microsoft T-SQL: Can I CONVERT smallint to varchar It may just be me, but... Despite the fact that most sql developers may consider cast & convert to be very basic stuff, and that may be true, I find Microsoft's documentation page on CAST & CONVERT to be one of the most hideous, not-intuitively-laid-out, hard to understand things I have ever seen. Much of their documentation is great. Like constantly trying to blend the entire page into a mix of both cast and convert, jumping back and forth in each sentence... rather than dealing with them separately. And who puts the target_type as the first argument? Putting the expression as the first argument would be more intuitive - and follow the other 99% of numerous programming languages' syntax.  UH
MS says that I can only convert to 3 data types: (well actually I'm not really sure if this applies to both CAST and CONVERT, since they ARE, in fact, different... But according to the layout of that webpage, it apparently applies equally to both - even though I already know for a fact that it is not true for CAST, which I use much more frequently).
It says:  "Is the target data type. This includes xml, bigint, and sql_variant"
Putting aside for the moment the fact that I CAST things as many other datatypes all the time (date, varchar),
My immediate question is:  if I can only CONVERT to those data types, then why does this work?
select CONVERT(varchar(200), cast(50 as smallint))

And finally, I'd like to run an INSERT that will be getting a smallint and putting it into a varchar(200) column.
All I'm trying to do is avoid any failures, so maybe I don't really "need" to convert or cast over to varchar, but any commments on

*

*answer on what is my apparent misunderstanding about the CONVERT documentation

or

*how to safely convert it to insert to varchar
are welcome. As long as you're not just overly unpleasant, since there are always those MS fans who get hot under the collar at all critiques of MS .. :|

A: Yes, you can convert from smallint to varchar.

1) answer on what is my apparent misunderstanding about the CONVERT
  documentation

This may be product of general lack of understanding on what data types are, how can they be converted from one type to another and equally important; what styles are when it comes to the aesthetic representation of a data type.
CAST is an explicit cast operation with no style options.
CONVERT is also an explicit cast that gives you the ability to specify a style for the output.
The documentation clearly states:

Implicit Conversions
Implicit conversions are those conversions that occur without
  specifying either the CAST or CONVERT function. Explicit conversions
  are those conversions that require the CAST or CONVERT function to be
  specified. The following illustration shows all explicit and implicit
  data type conversions that are allowed for SQL Server system-supplied
  data types. These include xml, bigint, and sql_variant. There is no
  implicit conversion on assignment from the sql_variant data type, but
  there is implicit conversion to sql_variant.

For your second question

2) how to safely convert it to insert to varchar

Depending of what you mean by safe. Converting to varchar is the convertion that most likely succeed. But whenever to cast to any toher datatype you are intrinsically changing the very nature of the data and will lose precision when casting to smaller types (or applying styles).
The documentation clearly states:

Truncating and Rounding Results
When you convert character or binary expressions (char, nchar,
  nvarchar, varchar, binary, or varbinary) to an expression of a
  different data type, data can be truncated, only partially displayed,
  or an error is returned because the result is too short to display.
  Conversions to char, varchar, nchar, nvarchar, binary, and varbinary
  are truncated, except for the conversions shown in the following
  table.

in other words, casting is never safe.

A: Numbers always get silently truncated for me. I would propose:
Option 1
Compare the converted value with the original value.
DECLARE @ORIGINAL DECIMAL(13,2) = -99999999999.99 --
DECLARE @EXPECTED VARCHAR(15) = ''
SELECT @EXPECTED = CONVERT(VARCHAR(15),@ORIGINAL)
IF CONVERT(DECIMAL(13,2),@EXPECTED) != @ORIGINAL SELECT 'Ooops'

Option 2
Make sure that all possible values will fit in target varchar.
Decimal(13,2). Widest number possible will be "-99999999999.99" needs varchar(15):

*

*13 chars for digits

*1 char for decimal separator

*1 char for minus sign

Smallint stores 2 bytes, from "-32768" to "32767", needs varchar(6):
 - 5 chars for digits
 - 1 char for minus sign
Not sure if you need chars for thousands separators, or if you can change it via settings.


text:
Q: double free or corruption when implement binary tree update:
add more code as asked.pasted to the end of question. Thanks everyone who stops.
current code is fine to delete a leaf, but come to Root, it can not delete.
====
update:
I revise the code, change removeRootMatch to
tmp = Root;
Root = tmp->Right;
tmp->Right = NULL;
delete tmp;

and no error but it does not delete the Node.
=====
The program is simple do the following step:

*

*find min value of a binary tree;

*record the min value in a vector;

*delete the node with min value in the tree;

*repeat 1-3 till the tree is empty.

I have removeNode()function, which will call removeRoot function(check code below),if the one needed to be removed is Root. But I have trouble with this function. I am doing some debug and found it is something wrong with removeRootMatch function. It give an error when run. the error I got is The error I got is *** glibc detected *** ./bintree: double free or corruption (fasttop): 0x0000000000727060 ***, any one can help me?
The tree is defined as following, language is c++
typedef struct myNode* LPNode;
typedef struct myNode Node;
struct myNode
{
  double key;

  LPNode Left; //left subtree
  LPNode Right; //right subtree
};

Main part of program is as following:

*

*nmax is initialed as 0,

*sortedvector is alloacted a vector with space as large as the total nodes in the tree,

*min is initialed as 99999.

*minValue will return the min value of tree.

*compareDouble(a,b) will return 1 if a < b,return 2 if a > b,return 3 if equal

code as following
    void removeRootMatch(LPNode Root)
{
    LPNode tmp = MakeNewNode(Root->key);
    tmp->Left = Root->Left;
    tmp->Right = Root->Right;
    //no child
    if(Root->Left==NULL && Root->Right == NULL) {

        Root=NULL;
    delete Root;
    } else if(Root->Left==NULL && Root->Right!=NULL){ //one right child
        //delete Root;
            Root = tmp->Right;
        tmp->Right = NULL;
        delete tmp;
    } else {
        printf("Remove root bug!\n");
    }
}

This is the function call removeNode function.
//compare double
int compareDouble(double a,double b)
{
    if(a-b<-EPSILON) //a<b
        return 1;
    else if(a-b>EPSILON)//a>b
        return 2;
    else
        return 3;
}

//find the min key in a tree
double minValue(LPNode Root,double min)
{
    if(Root == NULL)
        return min;
    if(compareDouble(Root->key,min)==1)
        min = Root->key;
    min = minValue(Root->Left, min);
    min = minValue(Root->Right, min);
    return min;
}

//remove root
void removeRootMatch(LPNode& Root)
{
    LPNode tmp = MakeNewNode(Root->key);
    tmp->Left = Root->Left;
    tmp->Right = Root->Right;
    //no child
    if(Root->Left==NULL && Root->Right == NULL) {
        Root=NULL;
        delete Root;
    } else if(Root->Left==NULL && Root->Right!=NULL){ //one right child

        double k = Root->key;

        Root = tmp->Right;
        tmp->Right = NULL;
        delete tmp;
        //tmp=tmp->Right;
        //Root->Right = NULL;
        //delete Root;
        //Root = tmp;

    } else {
        printf("Remove root bug!\n");
    }
}

//remove a node
void removeMatch(LPNode& Root,LPNode match,bool left)
{
    //no child
    if(match->Left==NULL && match->Right == NULL){
        double k = match->key;
        left==true?
        Root->Left=NULL:
        Root->Right=NULL;
        delete match;
        if(!Root->Left)printf("%f  ",k);
    }
    else if(match->Left==NULL && match->Right!=NULL){//one right child
                double k = match->key;

        left==true?
        Root->Left=match->Right:
        Root->Right=match->Right;
        delete match;
        if(!Root->Left)printf("%f  ",k);
    } else {
        printf("Remove root bug!\n");
    }
}

//delete a node
void removeNode(LPNode Root,double min)
{
    if(compareDouble(min,Root->key)==3){
        removeRootMatch(Root);
    }else if(compareDouble(min,Root->key)==1 && Root->Left != NULL) {

        compareDouble(min,Root->Left->key)==3 ?
        removeMatch(Root,Root->Left,true):
        removeNode(Root->Left,min);
    }else if(compareDouble(min,Root->key)==2 && Root->Right != NULL){

        compareDouble(min,Root->Right->key)==3 ?
        removeMatch(Root,Root->Right,false):
        removeNode(Root->Right,min);
    }else{
        printf("Remove bug1!\n");
    }
}

//call minValue to find the min key
//record the min key in a vector
//call removeNode to delete the Node
//repeat till the tree is empty
void problem1(LPNode Root,double* sortedvector,int& nmax)
{
    double min;
    //while(Root!=NULL)
    for(int i=0;i<3;i++)
    {
        min = MAX;
        sortedvector[nmax] = minValue(Root,min) ;
        printf("inv%f\n",sortedvector[nmax]);
        removeNode(Root,sortedvector[nmax]);
        nmax++;
    }
    printf("The tree is empty");
}

A: If your function removeNode may adjust the Root, then your function is not declared properly.
 void removeRootMatch(LPNode Root)

You are passing a pointer to Root.  Inside the removeRootMatch function, you are working on a copy of the pointer.  So code like this inside of the removeRootMatch function:
Root = tmp->Right;
    tmp->Right = NULL;
    delete tmp;

does not change the Root node when the function returns.
To address this issue, you should pass the Root pointer by reference:
 void removeRootMatch(LPNode& Root)


text:
Q: How to turn off bluetooth? I want to turn off bluetooth. It seems to be turned off already, but every boot it appears at the panel again.
Here is how it looks at Settings.

A: This might be useful:
How to boot with bluetooth turned off
Specifically the answer by Stepbaer:

I found a how-to with a clean "workaround":
http://catlingmindswipe.blogspot.com/2012/05/how-to-disable-bluetooth-on-startup.html
Actually changing /etc/bluetooth/main.conf was enough for me.
InitiallyPowered = true


text:
Q: Is memory fragmentation possible when malloc and free functions are called in order? I am doing an embedded system app in C and I was wondering of the following.
If one uses malloc and free functions in order, do you still have to worry about memory fragmentation?
Example:
malloc(a)
malloc(b)
malloc(c)
free(c)
free(b)
free(a)
Thanks for the help.

A: It is almost certain that the memory allocator will perform free block aggregation, so that adjacent free blocks will be aggregated into a single block.  There is no guarantee of that, but that would be conventional if not required behaviour.
There is of course no guarantee that the blocks a, b and c in your example are adjacent, but either way, on deallocation of all three, the heap will be in the same state as it was before allocation, in that sense it actually makes no difference what the order of deallocation is.
It is only the intermediate state that will be fragmented.  For example if the blocks are adjacent as follows:
aaaaaaaaaaabbbbbbbbbbbbbbcccccccccccccc

and you deallocate b before a or c, you will have two non-adjacent free blocks until either a or c are deallocated.
aaaaaaaaaaa--------------cccccccccccccc

However it is academic since as I said there is no guarantee of allocation of adjacent blocks in the first instance.  If you want to be sure of the behaviour, you would allocate one large block (statically or from the heap using malloc) and then allocate from that using your own allocator with an implementation that meets your application requirements.

A: In your case you should not see memory fragmentation occurring.  You can verify that it is not occurring by doing your malloc/free sequence several times, say 1000.  If malloc returns the same values for a, b, and c, then I think you can conclude that no fragmentation is occurring.


text:
Q: How to attach each sheet as attachment from a excel file (workbook) to send mail How to send an email by attaching the each sheet as individual attachment.
I have a workbook it contains 3 or 4 sheets, i want attach these sheets as individual attachment to send a mail.
Any help in this regards is highly solicited.
Thanks in advance

A: You need to open the Workbook from VBA and then process each of the sheets. Even not using VBA in Excel you need to have Excel running for getting the sheet information. The examples mentioned by @siddharth-rout give code on how to create the email for Sendmail and several Mail program.
Go for Sendmail as you can dispense with user interaction and when you can provide the target in the program (or from some cell in the workbook). Go with the mailer routines for the mailer your users have installed if they need to provide comments in addition to the sheets or the email target addresses.


text:
Q: Nested query in sql server Hello then the query below performs a select on a sql server database, the problem is that the total field is calculated as the total of all the tables, not of each , how can I run the account individually?Each table has a construction field and I want to calculate the  Totale field based on that field
Query:
SELECT *
FROM ((SELECT Cantiere.IdCantiere,
              Cliente.RagioneSociale,
              'Preventivo' AS Tipo,
              Cantiere.NomeCantiere,
              Cantiere.StatoCantiere,
              (SELECT (SELECT COALESCE(SUM(Prezzo * Quantita), 0)FROM ArticoloCantiere ) + (SELECT COALESCE(SUM((Kilometri.Kilometri * CostoKilometrico) + DirittoChiamata), 0)
                                                                                FROM Kilometri ) + (SELECT COALESCE(SUM(CostoNoleggio + Trasporto), 0)FROM Noleggio) + (SELECT COALESCE(SUM(Utente.CostoInterno * ((REPLACE((LEFT(CAST(REPLACE((CONVERT(varchar(5), CAST(CONVERT(varchar(5), (RisorseUmane.OreFine - RisorseUmane.OreInizio), 108) AS datetime) - CAST(REPLACE(RisorseUmane.Pausa, '.', ':') AS datetime), 108)), ':', ',') AS money) / 100, 2)), '.', '')) + (((CAST('0,' + (RIGHT(CAST(REPLACE((CONVERT(varchar(5), CAST(CONVERT(varchar(5), (RisorseUmane.OreFine - RisorseUmane.OreInizio), 108) AS datetime) - CAST(REPLACE(RisorseUmane.Pausa, '.', ':') AS datetime), 108)), ':', ',') AS money) / 100, 2)) AS money) / 100) * 100) / 60))), 0)
                                                                                FROM RisorseUmane
                                                                                INNER JOIN Utente ON RisorseUmane.IdUtente = Utente.IdUtente where IdCantiere=@IdCantiere) + (SELECT COALESCE(SUM(Costo), 0)FROM SpeseSostenute where IdCantiere=@IdCantiere) + (SELECT COALESCE(SUM(Costo), 0)FROM Ristorante )) AS Totale
       FROM Cantiere
            INNER JOIN Cliente ON Cantiere.IdCliente = Cliente.IdCliente
            INNER JOIN CantierePreventivo ON CantierePreventivo.IdCantierePreventivo = Cantiere.IdCantiere)
      UNION
      (SELECT Cantiere.IdCantiere,
              Cliente.RagioneSociale,
              'Consuntivo' AS Tipo,
              Cantiere.NomeCantiere,
              Cantiere.StatoCantiere,
              (SELECT (SELECT COALESCE(SUM(Prezzo * Quantita), 0)FROM ArticoloCantiere ) + (SELECT COALESCE(SUM((Kilometri.Kilometri * CostoKilometrico ) + DirittoChiamata), 0)
                                                                                FROM Kilometri ) + (SELECT COALESCE(SUM(CostoNoleggio + Trasporto), 0)FROM Noleggio ) + (SELECT COALESCE(SUM(Utente.CostoInterno * ((REPLACE((LEFT(CAST(REPLACE((CONVERT(varchar(5), CAST(CONVERT(varchar(5), (RisorseUmane.OreFine - RisorseUmane.OreInizio), 108) AS datetime) - CAST(REPLACE(RisorseUmane.Pausa, '.', ':') AS datetime), 108)), ':', ',') AS money) / 100, 2)), '.', '')) + (((CAST('0,' + (RIGHT(CAST(REPLACE((CONVERT(varchar(5), CAST(CONVERT(varchar(5), (RisorseUmane.OreFine - RisorseUmane.OreInizio), 108) AS datetime) - CAST(REPLACE(RisorseUmane.Pausa, '.', ':') AS datetime), 108)), ':', ',') AS money) / 100, 2)) AS money) / 100) * 100) / 60))), 0)
                                                                                FROM RisorseUmane
                                                                                INNER JOIN Utente ON RisorseUmane.IdUtente = Utente.IdUtente ) + (SELECT COALESCE(SUM(Costo), 0)FROM SpeseSostenute ) + (SELECT COALESCE(SUM(Costo), 0)FROM Ristorante )) AS Totale
       FROM Cantiere
            INNER JOIN Cliente ON Cantiere.IdCliente = Cliente.IdCliente
            INNER JOIN CantiereConsuntivo ON CantiereConsuntivo.IdCantiereConsuntivo = Cantiere.IdCantiere)) q
ORDER BY q.Totale DESC;

A: your totale column in all of tables is same. you must calculate total in each section by joining total result of those section with associated Cantiere  row. for more help please give your tables structure and sample data.


text:
Q: Duplicates in a repeater are not allowed angular.js I have a view controller with the following code that fetches data from api server:
$scope.recent_news_posts = localStorageService.get('recent_news_posts') || [];

        $http({method: 'GET', url: 'http://myapi.com/posts'}).success(function(data) {
            if ($scope.$$destroyed) {
                return
            }

            $scope.recent_news_posts = data || [];
            localStorageService.set("recent_news_posts", $scope.recent_news_posts);
        });

In template:
<md-card class="news-item" ng-repeat="post in recent_news_posts track by post.link" ng-click="openExternalLink(post.link);">
                    <md-card-title>
                        <md-card-title-text>
                            {{ post.title }}

                        </md-card-title-text>
                        <md-card-title-media>

                        </md-card-title-media>
                    </md-card-title>
                </md-card>

And sometimes I getting reports from sentry like:

[ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track
  by' expression to specify unique keys. Repeater: post in
  recent_news_posts track by post.link, Duplicate key: function link(),
  Duplicate value:

http://errors.angularjs.org/1.5.9/ngRepeat/dupes?p0=post%20in%20recent_news_posts%20track%20by%20post.link&p1=function%20link()&p2=%0A
I read article and added track by, but this didn't help.
I suppose this is maybe because ng-repeat function not finished in time new data from server came. But don't know how to fix this.

A: Check your data which comes from API. Probably there are some items which have exactly the same post.link inside. If you use track by then the item which is used for tracking needs to be unique!


text:
Q: FileNotFoundException when getting facebook friend bitmap - Android I'm getting an error fetching a bitmap of friends facebook profile pictures. These friends have all logged into the app. I have used examples found on StackOverFlow to create an AsyncTask and to load the bitmap, however I haven't really found another error similar/relevant to the one I have. I Have been stuck for a while now, so thanks for your time!
Calling the AysncTask:
        new DownloadImage().execute(new MyTaskParams(friendList.get(pos).getId(), viewHolder.friendPic));

MyAsyncTask:
private class DownloadImage extends AsyncTask<MyTaskParams, Void, Void> {

    @Override
    protected Void doInBackground(MyTaskParams... params) {
        MyTaskParams im = params[0];
        int id = im.id;
        ImageView imageView = im.imageView;

        try {
            URL imageURL = new URL("https://graph.facebook.com/" + id + "/picture?type=small");
            InputStream inputStream = (InputStream) imageURL.getContent(); //line with error
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            imageView.setImageBitmap(bitmap);

        } catch(MalformedURLException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}

Logcat error:
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕     java.io.FileNotFoundException: https://graph.facebook.com/2147483647/picture?type=small
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:197)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at java.net.URLConnection$DefaultContentHandler.getContent(URLConnection.java:1017)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at java.net.URLConnection.getContent(URLConnection.java:199)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getContent(DelegatingHttpsURLConnection.java:133)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getContent(HttpsURLConnectionImpl.java:25)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at com.dtfapp.FriendListArrayAdapter$DownloadImage.doInBackground(FriendListArrayAdapter.java:101)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at com.dtfapp.FriendListArrayAdapter$DownloadImage.doInBackground(FriendListArrayAdapter.java:93)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
07-05 13:14:57.312  15485-15529/com.dtfapp W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
07-05 13:14:57.322  15625-15625/? W/ResourceType﹕ ResTable_typeSpec entry count inconsistent: given 1, previously 1632

I have also tried using the facebook ProfilePictureView. It works using the id of the person that is logged in, but not when using the id of friends.
((ProfilePictureView) rowView.findViewById(R.id.profilePicture)).setProfileId(friendList.get(pos).getIdStr());

A: try using facebook android sdk sdk:
/* make the API call */
new GraphRequest(
   AccessToken.getCurrentAccessToken(),
   "/{user-id}/picture",
   null,
   HttpMethod.GET,
   new GraphRequest.Callback() {
      public void onCompleted(GraphResponse response) {
          /* handle the result */
      }
   }
).executeAsync();

In addition, when I access in the browser http://graph.facebook.com/2147483647/picture I get this message:
"message": "(#803) Some of the aliases you requested do not exist: 2147483647",


text:
Q: using one element from one datafram to find all the information in the other datafram? Python I have 2 dataframe in python by running 2 sql queries.
Table A:

Name
Email
Code

A
E
E1,E2,E3

B
F
F1,F2

C
G
G1

...
...
...

Table B:

Info1
Code
Info2

...
E1
...

...
F1
...

...
E2
...

...
E3
...

...
G1
...

...
F2
...

Because they are dataframe in Python, I would like to read the email one by one, and find its Code list/Array in TableA.
And use every elements in the list/array to find all the data in Table B, create excels and send to information's host.
For example,
I would to get the result excel like below and send it to E.

Info1
Code
Info2

...
E1
...

...
E2
...

...
E3
...

For example,
I would to get the result excel like below and send it to F.

Info1
Code
Info2

...
F1
...

...
F2
...

For example,
I would to get the result excel like below and send it to G.

Info1
Code
Info2

...
G1
...

Please use dataframe in Python.
THANK YOU SO MUCH

A: You could try something like this:
new_df = df1.assign(Code=df['Code'].str.split(',')).explode('Code').merge(df2)
for email, sub_df in new_df.groupby(['Email']):
    print(f'Sending df to {email}...')
    print(sub_df.to_csv())

Output:
Sending df to E...
,Name,Email,Code,Info1,Info2
0,A,E,E1,...,...
1,A,E,E2,...,...
2,A,E,E3,...,...

Sending df to F...
,Name,Email,Code,Info1,Info2
3,B,F,F1,...,...
4,B,F,F2,...,...

Sending df to G...
,Name,Email,Code,Info1,Info2
5,C,G,G1,...,...


text:
Q: Action of momentum operator on position eigenstate i.e., $\hat{P}|x\rangle$ I was trying to calculate commutator $\left[\hat{P}, \hat{T}(\vec{dx})\right]$ where $\hat{P}$ is momentum operator and $ \hat{T}(\vec{dx})$ is Translation operator
My approach:
I tried calculating the terms
\begin{eqnarray}
\hat{P} \hat{T}(\vec{dx}) |x\rangle \text{ and }  \hat{T}(\vec{dx})\hat{P}|x\rangle
\end{eqnarray}
Now I know that $\hat{T}(\vec{dx})|x\rangle = |x + dx\rangle$ but I dont know how will $\hat{P}$ operate on state $|x\rangle$ or $|x + dx\rangle$

A: You know that $\langle p|x\rangle = e^{-ixp/\hbar}/\sqrt{2\pi/\hbar}$, so
$$
\langle p|\hat T (dx)|x\rangle = \langle p|x+dx\rangle= \frac{e^{-ip(x+dx)/\hbar}}{\sqrt{2\pi\hbar}}\\ =\langle p|x\rangle e^{-ipdx/\hbar}= \langle p|e^{-i\hat Pdx/\hbar}|x\rangle \\ \leadsto
\hat T (dx)= e^{-i\hat P dx /\hbar}, ~~\implies~~ [\hat P, \hat T]=0.
$$
Heed the counterintuitive minus sign in the exponent: kets translate oppositely to functions and bras!

Geeky : If you enjoy integrating delta functions by parts,  you might well consider two handy representations of this unitary operator,
$$
\hat T(a) =\int \!\! dp~|p\rangle e^{-ipa/\hbar}\langle p| = \int \!\! dx~|x\rangle e^{-a \partial_x}\langle x|.
$$


text:
Q: Horisontal spacing CSS menu LI I'm trying to get the boxes for each
 tag to position next to each other without spaces, but as they are now, they have a big space between each box. How do I remove that?
HTML code:

        Menu

Option1

Option1

Option1

Option1

Option1

Option1

CSS code:
ul {
margin: 0px;
padding: 0;
}

#menu li {
display: inline;
list-style: none;
}
#menu li a {
margin: 0px;
padding: 5px 30px 5px 30px;
text-align: center;
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif;
font-size: 15px;
color: rgba(66,48,1,1);
border: 1px solid rgba(105,181,50,1);
background: rgba(122,199,67,1);
}
#menu li a:hover {
cursor: pointer;
background: rgba(178,232,139,1);
color: rgba(0,0,0,1);
}
#menu a:link, #menu a:visited {
color: rgba(255,255,255,1);
text-decoration: none;
}
#menu a:active {
color: rgba(250,191,12,1);
}
#menu a#current {
background: rgba(85,137,48,1);
}

A: Those gaps are white-space characters. You can see them when you go with your cursor over one of those gaps - it changes to a text-cursor.
You can avoid this by

*

*write your list items in one line, thus avoiding white space

*float your list items like so:

CSS:
#menu li {
    display: inline;
    list-style: none;
    float: left;
}


text:
Q: What does the console's output means after defining a module? Defining a module in console produces some collection of numbers with the module's function and number of arguments it takes:
defmodule HotelRoom do
  def book(%{name: name, age: age}) when age < 25, do: IO.puts "#{name}, you are too young"
  def book(%{name: name, age: age}) when age >= 30, do: IO.puts "#{name},you are 30 years old"
  def book(person), do: IO.puts "Your name is #{person.name}"
end

#=> {:module, HotelRoom,
 <<70, 79, 82, 49, 0, 0, 8, 120, 66, 69, 65, 77, 69, 120, 68,99, 0, 0, 0,
   150, 131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100,
   111, 99, 115, 95, 118, 49, 108, 0, 0, 0, 4, 104, 2, ...>>, {:book, 1}}

What does it mean and should I care about it?

A: That is the binary contents for the module. Normally you don't need to worry about it.

This macro defines a module with the given alias as its name and with
  the given contents. It returns a tuple with four elements:

*

*:module

*the module name

*the binary contents of the module

*the result of evaluating the contents block

http://elixir-lang.org/docs/v1.1/elixir/Kernel.html#defmodule/2


text:
Q: Random variable $Z = |X-Y|$ Let's take two independent, random variables $X$ and $Y$ from set $\{1,\ldots,n\}$
probability, that $X =i$ AND $Y = j$ is $\frac{1}{n^2}$.
I want to determine the expected value, so I started:
$$E[Z] = E[|X-Y|] = \sum_i (a_i) \cdot P(|X-Y|=a_i),$$ (sum is to $n$) but I don't now how to count $P(|X-Y|=a_i)$, cause some values values are repeated. Can anybody give a prompt?

A: Draw the  $n\times n$ grid of points with coordinates $(i,j)$, where $i$ and $j$ range from $1$ to $n$.  The points $(x,y)$
such that $x-y=k$ are the points on the line $x-y=k$. For $k=0$ there are $n$ such points, the points on the diagonal. For $x-y=1$, there are $n-1$ points, for $x-y=2$ there are $n-2$ points, and so on. For positive $k$, we are dealing with the points of the grid which are below the diagonal line $y=x$.
Similarly, there are $n-1$ points such that $x-y=-1$, $n-2$ points such that $x-y=-2$, and so on. These are the points of our grid above the diagonal $y=x$.
So for $2(n-1)$ points, the absolute value of the difference is $1$, for $2(n-2)$ points the absolute value of the difference is $2$, and so on. Finally, there are $2$ points where the absolute value of the difference is $n-1$. In all cases, each point has probability $\frac{1}{n^2}$. It follows that
$$E(|X-Y|)=\frac{2}{n^2}\left[(1)(n-1)+(2)(n-2)+(3)(n-3)+\cdots +(n-1)(n-(n-1))                 \right].$$
We next obtain a closed form for the above expression. By expanding, we can  see that our sum is equal to
$$\frac{2}{n^2}n\left[1+2+3+\cdots+n-1\right] -2\left[1^2+2^2+3^2+\cdots+(n-1)^2\right].$$
By the usual formula for the sum of the consecutive integers, and the sum of consecutive integers, we get, after some algebra,
$$\frac{(n-1)(n+1)}{3n}.$$
Remark: The standard formulas that were used for the closed form are $1+2+\cdots+k=\frac{k(k+1)}{2}$ and $1^2+2^2+\cdots +k^2=\frac{k(k+1)(2k+1)}{6}$.

A: $$E[Z] = E[|X - Y|] = \sum_{i = 1}^n \sum_{j = 1}^n |i - j|P(X = i, Y = j) = \frac{1}{n^2}\sum_{i = 1}^n \sum_{j = 1}^n |i - j| = \frac{2}{n^2}\sum_{i = 1}^{n} \sum_{j = 1}^{i - 1} (i - j) = \frac{2}{n^2}\sum_{i = 1}^{n} i(i - 1) - \frac{i(i - 1)}{2} = \frac{2}{n^2}\sum_{i = 1}^{n}\frac{i(i - 1)}{2} = \frac{1}{n^2}\sum_{i = 1}^{n}i(i - 1) = \frac{1}{n^2}\sum_{i = 1}^{n}i^2 - i = \frac{1}{n^2} \left( \frac{n(n + 1)(2n + 1)}{6} - \frac{n(n + 1)}{2} \right) = \frac{(n + 1)}{2n} \left( \frac{2n + 1}{3} - 1 \right) = \frac{(n - 1)(n + 1)}{3n}$$


text:
Q: Use 'MutableClass' methods in 'Class' methods

Hi all,
Consider the following :
// Things.h
@interface Things : NSObject
@property (strong, nonatomic) NSSomething * listOfThings;
@end

// Things.m
@implementation Things
// Some methods
@end

// MutableThings.h
@interface MutableThings : Things
- (instancetype) thingsPassingTest;
@end

// MutableThings.m
@implementation MutableThings
- (instancetype)thingsPassingTest
{
    // Do some stuff in order to return a subset of Things
    return newThings;
}
@end

I would like to be able to call thingsPassingTest for a Things object, and not a MutableThings.
Is there a way to call a subclass method ?
Or maybe am I going in the wrong direction ?

A: In your design your MutableThings inherits from Thinks so every public property and methods implemented in Things will be available in MutableThings object.
You can override thingsPassingTest in MutableThings class and return nil, maybe this is what you want.
But the best way is to create root class with all of the common methods for Things and MutableThings classes. And implement thingsPassingTest just in Things not in the MutableThings and not in the root class.
Is it something you asking for?

A: You can not call "thingsPassingTest" on "Things" object because "Things" is superclass for "MutableThings". It is against the rules of object Oriented Programing paradigm.


text:
Q: Norm of $L^2$ functional Consider the functional $T: L^2((0,1)) \rightarrow \mathbb{R}$
$$
T(f) = \int_0^1 f(x) (1-x) dx.
$$
Calculate $\lVert T \rVert$.

I can show that
$$
|T(f)| \leq \int_0^1 |f(x) (1-x)| dx \leq \left( \int_0^1 |f(x)|^2 dx \right)^{1/2}
\left( \int_0^1 (1-x)^2 dx \right)^{1/2}= \lVert f \rVert_2 \sqrt{\frac{1}{3}}
$$
using Hölder inequality. Which means $\lVert T \rVert \leq \sqrt{\frac{1}{3}}$.
Now I need to find $f \in L^2(0,1)$, $\lVert f \rVert \leq 1$ (or a sequence) such that
$\lVert T(f) \rVert = \sqrt{\frac{1}{3}}$. How can I do that?
Thanks.

A: In both inequalities in the question we have inequality if $f(x)=\alpha(1-x)$ for $\alpha\in\mathbb{R}$. In particular, if $\alpha=\pm\sqrt{3}$, then $\|f\|_2=1$ and $\|Tf\|_2=\frac1{\sqrt{3}}$.


text:
Q: How to send structure array to function in C? Hi I'm having trouble sending an array of structures to a function.
The structure is set up as below:
struct Leader
{
   char surname[15], party[15];
   int months_in_power;
};

I then read the data from a file and assign it:
if ((INFILE=(fopen("PM.txt","r"))) == NULL)
{
    printf("ERROR: The file could not be opened.");
    system("pause");
    return 1;
}

while(fscanf(INFILE, "%s %d %d %d %d %s", name,
&start_month, &start_year, &end_month, &end_year, party)>0)
{
    struct Leader PM[i];
    strcpy(PM[i].surname, name);
    strcpy(PM[i].party, party);
    months = tenure(start_month, start_year, end_month, end_year);
    PM[i].months_in_power = months;
    party_time(&PM[i], &Con_months, &Lab_months );
    printf("%s: %s, %d months\n", PM[i].surname, PM[i].party, PM[i].months_in_power); //This line all works
    i++;
}

Then I try and call my function 'bubble'.
imax=i;
bubble(PM, imax);

and the function bubble is supposed to sort them in order.
void bubble(struct Leader arr[],int max)
{
    int j=0, i=0, temp=0;

    for (j=1; j<(max);j++)
    {
        for (i=0; i<(max-1); i++)
        {
        if (arr[i].months_in_power < arr[i+1].months_in_power)
        {
            temp = arr[i].months_in_power;
            arr[i].months_in_power=arr[i+1].months_in_power;
            arr[i+1].months_in_power = temp;
        }
            else continue;
        }
    }

    for( i=0; i<max; i++)
    {printf("%d\n", arr[i].months_in_power);}

    return ;
}

If I try and print arr[i].months_in_power during the sorting loops it just prints rubbish and crashes. Whats wrong?
EDIT: The PM.txt file contains information like:
Attlee         7   1945  10  1951 Labour
Churchill     11   1951   5  1955 Conservative
Eden           6   1955  12  1956 Conservative
etc etc...
Thanks

A: I don't think that the following code is correct
struct Leader PM[i];
strcpy(PM[i].surname, name);
strcpy(PM[i].party, party);

You first declare an array of Leader structures of size i, which can be correct, but then you try to access it with PM[i]. PM[i] will fetch data beyond the array and strcpy will write into memory which doesn't belong to the array.
Later on, when you try to access data it might be garbage.

A: In your code, you did not create an instance of the PM array or structs. Other than a few other nits, and your sort being in descending order (check the bubble sort logic), the code was not in bad shape. Note: when you are creating an array of some size, it is general practice to #define a maximum size of the array. Below, I just defined MAXS (max structures) to 256 in the line #define MAXS 256. You then check your count as you read from your data file against MAXS-1 (zero based array count). If you exceed MAXS - 1 you will need to increase the size (or if you allocated dynamically, you have the option to reallocate at that point) The example below ran fine.
Remember to initialize all variables! This is one of the easiest things you can do to prevent wandering off into undefined behavior.
Note: I created a tenure to return the number of months served -- make sure that is what you want. Also, I did not recreate a party_time function. That's up to you.
Let me know if you need any additional help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXS 256

struct Leader
{
    char surname[15];
    char party[15];
    int months_in_power;
};

void bubble (struct Leader arr[],int max);
int tenure (int start_month, int start_year, int end_month, int end_year);

int main () {

    char name[64] = {0};
    char party[64] = {0};
    int start_month=0, start_year=0, end_month=0, end_year=0;
    int months = 0;
    int i = 0;
    int imax = 0;
    FILE *INFILE;

    struct Leader PM[MAXS] = {{ {0}, {0}, 0 }};

    if ((INFILE = (fopen ("PM.txt","r"))) == NULL)
    {
        fprintf (stderr, "ERROR: The file could not be opened.");
        return 1;
    }

    while(fscanf(INFILE, "%s %d %d %d %d %s", name,
    &start_month, &start_year, &end_month, &end_year, party)>0)
    {
        strcpy(PM[i].surname, name);
        strcpy(PM[i].party, party);
        months = tenure(start_month, start_year, end_month, end_year);
        PM[i].months_in_power = months;
        // party_time(&PM[i], &Con_months, &Lab_months );
        printf("%-12s: %-12s, %d months\n", PM[i].surname, PM[i].party, PM[i].months_in_power); //This line all works

        i++;

        if (i > MAXS - 1) {
            fprintf (stderr, "Error: lines read from file exceed MAXS, reallocate or increase size.\n");
            return 1;
        }
    }

    imax=i;
    bubble(PM, imax);

    return 0;
}

void bubble(struct Leader arr[],int max)
{
    int j=0, i=0, temp=0;

    for (j=1; j<(max);j++)
    {
        for (i=0; i<(max-1); i++)
        {
        if (arr[i].months_in_power < arr[i+1].months_in_power)
        {
            temp = arr[i].months_in_power;
            arr[i].months_in_power=arr[i+1].months_in_power;
            arr[i+1].months_in_power = temp;
        }
            else continue;
        }
    }

    for( i=0; i<max; i++)
    {printf("%d\n", arr[i].months_in_power);}

    return ;
}

int tenure (int start_month, int start_year, int end_month, int end_year)
{
    int no_months = (end_year - start_year) * 12 - start_month + end_month;
    return (start_year <= end_year) ? no_months : -(no_months);
}

input:
$ cat PM.txt
Attlee 7 1945 10 1951 Labour
Churchill 11 1951 5 1955 Conservative
Eden 6 1955 12 1956 Conservative

output:
$ ./bin/structleader
Attlee      : Labour      , 75 months
Churchill   : Conservative, 42 months
Eden        : Conservative, 18 months
75
42
18


text:
Q: Select2 4 custom data adapter I am trying to create a custom data adapter according to an example here: http://select2.github.io/announcements-4.0.html#query-to-data-adapter.
How can I move the line that creates the select2 control outside the function with definition of DataAdapter (see the code below)?
<!DOCTYPE html>
<head>
    <title></title>
    <link href="select2.css" rel="stylesheet" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script>
    <script type="text/javascript" src="select2.full.js"></script>
    <script type="text/javascript">
        $.fn.select2.amd.require(
            ['select2/data/array', 'select2/utils'],
            function (ArrayData, Utils) {
                function CustomData ($element, options) {
                    CustomData.__super__.constructor.call(this, $element, options);
                }

                Utils.Extend(CustomData, ArrayData);

                CustomData.prototype.query = function (params, callback) {
                    var data = {results: []};
                    data.results.push({id: params.term, text: params.term});
                    data.results.push({id: 11, text: 'aa'});
                    data.results.push({id: 22, text: 'bb'});
                    callback(data);
                };

// Works if uncommented, but this line needs to be elsewhere (in $(document).ready()).
                //$("#my").select2({tags: true, dataAdapter: CustomData});
            });

        $(document).ready(function() {
// This line does not work here.
            $("#my").select2({tags: true, dataAdapter: CustomData});
        });
    </script>
</head>
<body>
    <select id="my"></select>
</body>
</html>

A: you define it via AMD-Pattern:
$.fn.select2.amd.define('select2/data/customAdapter',[
        'select2/data/array',
        'select2/utils'
    ],
    function (ArrayAdapter, Utils) {

        function CustomDataAdapter ($element, options) {
            CustomDataAdapter.__super__.constructor.call(this, $element, options);
        }
        Utils.Extend(CustomDataAdapter, ArrayAdapter);

        CustomDataAdapter.prototype.current = function (callback) {

            callback(...);

        };

        return CustomDataAdapter;
    }
);

var customAdapter=$.fn.select2.amd.require('select2/data/customAdapter');

$("#my").select2({
    tags: true,
    dataAdapter: customAdapter
});

A: For anyone trying to extend select2, here is an example :
// Require the adapter you want to override
$.fn.select2.amd.require(["select2/data/select"], function (Select) {
    let CustomDataAdapter = Select;

    // Simple example, just override the function
    CustomDataAdapter.prototype.current = function (callback) {
        // Your own code
    };

    // Example modifying data then calling the original function (which we need to keep)
    let originalSelect = CustomDataAdapter.prototype.select;
    CustomDataAdapter.prototype.select = function (data) {
        // Your own code
        // Call the original function while keeping 'this' context
        originalSelect.bind(this)(data);
    };

    // Finally, use the custom data adapter
    $('#my-select').select2({
        dataAdapter: CustomDataAdapter
    });

});

A: Example of select2 to handle big array. I am fetching data from server using ajax. Handling searching and pagination locally with more than 20000 data json.
<select id="widget_project"></select>

<script>
    $(function () {
        allProjects;// having all project json data

        pageSize = 50
        jQuery.fn.select2.amd.require(["select2/data/array", "select2/utils"],

        function (ArrayData, Utils) {
            function CustomData($element, options) {
                CustomData.__super__.constructor.call(this, $element, options);
            }
            Utils.Extend(CustomData, ArrayData);

            CustomData.prototype.query = function (params, callback) {

                var results = [];
                if(p_term !== "" &&  typeof params.term === "undefined"){
                    params.term = p_term;
                    console.log(params.term);
                }
                if (params.term && params.term !== '') {
                    p_term = params.term;
                  results = findItem(params.term);
                } else {
                  results = allProjects;
                }

                if (!("page" in params)) {
                    params.page = 1;
                }
                var data = {};
                data.results = results.slice((params.page - 1) * pageSize, params.page * pageSize);
                data.pagination = {};
                data.pagination.more = params.page * pageSize < results.length;
                callback(data);
            };

            $(document).ready(function () {
                $("#widget_project").select2({
                    minimumInputLength: 3,
                    placeholder:"Select a project",
                    ajax: {},
                    dataAdapter: CustomData
                });
            });
        })
    });

</script>


text:
Q: Copy file from one server path to another showing access denied Copy file from one server path to another showing access denied though I have given full access.

Error:System.UnauthorizedAccessException: Access to the path is
  denied. at System.IO.__Error.WinIOError(Int32 errorCode, String
  maybeFullPath) at System.IO.File.InternalMove(String sourceFileName,
  String destFileName, Boolean checkHost)

I have tried give security access to the required folder
string sourceFile = "C:/inetpub/wwwroot/MATS_History_Load_App/Python_Scripts/MATSUpgrade.xlsx";

string destinationFile = "//192.xxx.47/Mats/mats_test/MATSUpgrade.xlsx";

// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);

Important: The application is hosted on IIS

A: given there is no access problem with the identity of your code's process:
this works perfectly well out of the box, try to replace slash with Backslashs and use the @ before the path string:
string sourceFile = @"C:\temp\test.txt";
string destinationFile = @"\\fileshare\users\xy\prime.txt";
System.IO.File.Move(sourceFile, destinationFile);

otherwise in service or web hosting scenarios, you need to consider the access rights of your executing identity:
https://support.microsoft.com/en-us/help/207671/how-to-access-network-files-from-iis-applications

A: As far as I know, if you want to modify or access the network share folder. You should make sure you have choose the right application pool identity permission firslty. If you use the Network Service account as the identity, you still need to add enough permission on the shared folder, Since Network service and local system both appear on the network as the computer account (DOMAIN\computer$).
Normally, we will select the network servcie.
Details, you could refer to below steps:
1.Open the IIS management console, select the right application pool and click the advanced settings.

2.Select the identity and modify the account to networkserivce

3.Right cick the computer and click the property, you will find your computer name as below:

4.Go to your shared folder server, right click the folder and click property. Then you could add your server's account to it like this (Domain\Servername$)