text:
Q: Get data from nested JSON in PHP I have created a custom API, That gets JSON via PHP. Now my problem is I want to decode the JSON
so that I can edit it from my PHP file but get errors/ blank screen with no content on it only ID is, Name is est. but no values
I used the following code
    <?php
$string = file_get_contents("api/read.php");
//echo string;
$json_a = json_decode($string, true);
echo 'ID is: ' . $json_a['id'];
echo 'Name is: ' . $json_a['name'];
echo 'Email is: ' . $json_a['email'];
echo 'Age is: ' . $json_a['age'];
echo 'Destignation is: ' . $json_a['designation'];
echo 'Created on: ' . $json_a['created'];
?>

this is the read.php file
<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-Type: application/json; charset=UTF-8");

    include_once '../config/database.php';
    include_once '../class/employees.php';

    $database = new Database();
    $db = $database->getConnection();

    $items = new Employee($db);

    $stmt = $items->getEmployees();
    $itemCount = $stmt->rowCount();

    //echo json_encode($itemCount);

    if($itemCount > 0){

        $employeeArr = array();
        $employeeArr["body"] = array();
        $employeeArr["itemCount"] = $itemCount;

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            extract($row);
            $e = array(
                "id" => $id,
                "name" => $name,
                "email" => $email,
                "age" => $age,
                "designation" => $designation,
                "created" => $created
            );

            array_push($employeeArr["body"], $e);
        }
        echo json_encode($employeeArr, JSON_PRETTY_PRINT);
    }

    else{
        http_response_code(404);
        echo json_encode(
            array("message" => "No record found.")
        );
    }
?>

its output is the following
{
    "body": [
        {
            "id": "1",
            "name": "John Doe",
            "email": "johndoe@gmail.com",
            "age": "32",
            "designation": "Data Scientist",
            "created": "2012-06-01 02:12:30"
        },
        {
            "id": "2",
            "name": "David Costa",
            "email": "sam.mraz1996@yahoo.com",
            "age": "29",
            "designation": "Apparel Patternmaker",
            "created": "2013-03-03 01:20:10"
        },
        {
            "id": "3",
            "name": "Todd Martell",
            "email": "liliane_hirt@gmail.com",
            "age": "36",
            "designation": "Accountant",
            "created": "2014-09-20 03:10:25"
        },
        {
            "id": "4",
            "name": "Adela Marion",
            "email": "michael2004@yahoo.com",
            "age": "42",
            "designation": "Shipping Manager",
            "created": "2015-04-11 04:11:12"
        },
        {
            "id": "5",
            "name": "Matthew Popp",
            "email": "krystel_wol7@gmail.com",
            "age": "48",
            "designation": "Chief Sustainability Officer",
            "created": "2016-01-04 05:20:30"
        },
        {
            "id": "6",
            "name": "Alan Wallin",
            "email": "neva_gutman10@hotmail.com",
            "age": "37",
            "designation": "Chemical Technician",
            "created": "2017-01-10 06:40:10"
        },
        {
            "id": "7",
            "name": "Joyce Hinze",
            "email": "davonte.maye@yahoo.com",
            "age": "44",
            "designation": "Transportation Planner",
            "created": "2017-05-02 02:20:30"
        },
        {
            "id": "8",
            "name": "Donna Andrews",
            "email": "joesph.quitz@yahoo.com",
            "age": "49",
            "designation": "Wind Energy Engineer",
            "created": "2018-01-04 05:15:35"
        },
        {
            "id": "9",
            "name": "Andrew Best",
            "email": "jeramie_roh@hotmail.com",
            "age": "51",
            "designation": "Geneticist",
            "created": "2019-01-02 02:20:30"
        },
        {
            "id": "10",
            "name": "Joel Ogle",
            "email": "summer_shanah@hotmail.com",
            "age": "45",
            "designation": "Space Sciences Teacher",
            "created": "2020-02-01 06:22:50"
        }
    ],
    "itemCount": 10
}


text:
Q: counting occurrences in an SSRS table Working on SSRS. Have the following data set.
ID       City      Country
1       London     England
2       Glasgow    Scotland
3       Aberdeen   Scotland
4       Swansea    Wales
5       London     England
6       Glasgow    Scotland
7       Glasgow    Scotland
8       Manchester England

Would like to have a table, grouped by the city and showing how many occurrences there have been for each city, see below?
   City         Country      Total
  Glasgow       Scotland       3
  London        England        2
  Manchester    England        1
  Swansea       Wales          1
  Aberdeen      Scotland       1

How would i go about doing this please?

A: After creating a group of City use the following expression:
=COUNT(Fields!City.Value,"City")

Let me know if this helps.

A: It seems from your question that you don't want the detail in the report, only the summary data.  If you do want detail, Alejandro Zuleta's answer will work.  If you don't need the detail, you can do the grouping in your dataset:
select city, country, count(*) as total
  from <yourtable>
 group by city, country;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Opera - your browser does not currently recognize any of the video formats available I'm using opera browser version 56.0.3051.43 on Ubuntu 16.04 with I3wm and I get

your browser does not currently recognize any of the video formats available

when trying to play some videos on youtube on respect to HTML5. I've seen a couple forums about this, but only about very outdated versions and none are very clear steps. How can I fix this problem?

A: I had installed opera with the deb package downloadable from Opera's site and it did not load HTML 5 videos from youtube. The only solution that worked for me was to uninstall the version I had with:
sudo apt-get remove --purge opera-stable

and then installed the version from the PPA package following this other AskUbuntu post.
Adding a pointer to the opera stable sources:
sudo sh -c 'echo "deb http://deb.opera.com/opera/ stable non-free" >> /etc/apt/sources.list.d/opera.list'

Install the key:
sudo sh -c 'wget -O - http://deb.opera.com/archive.key | apt-key add -'

Fetch the new repository:
sudo apt-get update

Install latest Opera with:
sudo apt-get install opera-stable

Now Opera is able to handle HTML5 videos.

A: From a web search for opera linux enable h.264 I found this answer over on the Unix & Linux SE H.264 support for Opera and openSUSE that suggests trying a few different ideas, but it lead to a more promising looking Opera forum from 4 months ago that might/should work:

burnout426 4 months ago
@drpostman A little bit better directions.
Start Opera, goto, https://github.com/iteufel/nwjs-ffmpeg-prebuilt/releases/ and download the 0.31.4-linux-x64.zip file. In Opera's download dialog, click the folder icon to show the file in the file manager. Right-click it and choose "Extract here". This will give you libffmpeg.so.
Right-click in a blank spot in the file manager and choose "open as root" and type in your password. Then, right-click on libffmpeg.so and choose cut.
Then, in the file manager, browser to "/usr/lib/x86_64-linux-gnu/opera/". Right-click in a blank spot and choose to create a new folder named lib_extra. Once the folder is created, go into it, right-click on a blank spot and choose paste. You should then see libffmpeg.so there. Then, restart Opera and goto https://youtube.com/html5 to see if h.264 support is enabled for example. Then, test out some videos. On youtube, you can right-click on a video and choose "stats for nerds" to see if it's using vp9 or h.264. Or, you can try these h.264 videos to make sure they work.
You can then close the file manager.
(Tested on Linux Mint 19 Cinnamon x64)

Others answers that might be worth trying (from the earlier question) include:

*

*Copy a libffmpeg.so file from https://github.com/iteufel/nwjs-ffmpeg-prebuilt/releases or http://ppa.launchpad.net/saiarcot895/chromium-beta/ubuntu/pool/main/c/chromium-browser/

*Use the snap version of opera

A: The instructions by Sergey Podobry did not work for me on Ubuntu 19.10. Further digging into the issue, it seems that chromium-codecs-ffmpeg-extra does not have the necessary codec anymore. This can be notices if you look at the package list of files here.
Instead, this is what I did:

*

*Download the codec from an earlier Ubuntu release, Like 18.04, from here.

*Extract the package, and then extract data.tar.xz file.

*Within the extracted folder, navigation to data/usr/lib/chromium-browser. You will find the codec named libffmpeg.so.

*Move this file to /usr/lib/x86_64-linux-gnu/opera/lib_extra.

*Restart Opera.

A: Due to legal restrictions Opera is unable to distribute H264 codec. You can use the following workaround:
Install chromium-codecs-ffmpeg-extra package and create a link to libffmpeg.so:
sudo ln -sf /usr/lib/chromium-browser/libffmpeg.so /usr/lib/x86_64-linux-gnu/opera/libffmpeg.so

You can check your opera installation directory in the About dialog.

A: The problem is not so much with Opera and in all fairness the issue here is with libffmpeg.so which is in fact proprietary codec support. I have a little script that adds the support you need after an Opera update or install. Get the script here. Once you have it, make it executable and run it as follows.
chmod 755 opera_codec.sh
./opera_codec.sh

Hope this helps you out as it has always worked for me. You can then go test your html5 support at https://html5test.com

A: My FIX: I went to https://www.youtube.com/html5 (Thx Grandpa Dave!),

*

*Scrolled to the BOTTOM YOUTUBE LOGO on left

*and just to the RIGHT of the bottom-left logo "LANGUAGE" and

*CORRECTED my location/LANGUAGE.

Everything played fine after that. Pls share if this worked for you. It's a weird auto-location selection. I thought there might be a prob when the comp auto-filled my date/time with another country time, sure enough, youtube matched the incorrect auto location.

A: If anyone is looking for a one-line Opera install script you can use the following:
curl -sSL https://raw.githubusercontent.com/icolwell/install_scripts/master/opera_install.bash | bash

I've updated the install script according to Sergey Podobry's answer so it will link the correct video codecs. The script is hosted here.


text:
Q: How to change isEnabled and alpha properties of UIButton base on validation using RXSwift? This is what I simply try to achieve using:
let observable = Observable.combineLatest(loginProperty.asObservable(), passwordProperty.asObservable()) { _,_ in
    self.viewModel.isValid
}
observable.bind(to: mainView.loginButton.rx.isEnabled).disposed(by: disposeBag)
//observable.bind(to: mainView.loginButton.rx.alpha).disposed(by: disposeBag)

But this can be bound only to isEnabled property. I would like to also change alpha of my loginButton. How can I do that?

A: You have to write Reactive extension to bind the property.
extension Reactive where Base : UIButton {
    public var valid : Binder<Bool> {
        return Binder(self.base) { button, valid in
            button.isEnabled = valid
            button.alpha = 0.5 // You Value as per valid or not
        }
    }
}

Then write like this to check the Observable value
observable.bind(to: mainView.loginButton.rx.valid).disposed(by: disposeBag)


text:
Q: Size/Length and Type of a SQL table How do I find the length and type of a column in a SQL Table Column?
i.e. While creating a table if someone used Varchar(20), I want to identify this information whether it is Numeric or Varchar and the length/size.
Also, can I reduce the size of the table without losing data.
For example, if all the data in the column is of size 15 and my column length is of size 20, can I just alter the table column length to 15, without losing data?

A: The following query should work:
select DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tableName' and COLUMN_NAME = 'ColumnName'

Per your second question, yes, theoretically you could alter the column length without truncating any of the data in that column. You should consider that any future data (which may be require greater length/precision) will be affected as well.

A: Only select that table and press alt+f1 then you will get the complete structure of the table.


text:
Q: Diferenças entre OnKeyUp, OnKeyDown e OnKeyPress? Quando exatamente são disparados? E quais os contextos de uso pra cada um?
Pergunto isso porque de todas vezes que precisei usar sempre resolvia só com onkeyup. Apesar da dúvida ser em javascript ela reflete em outras linguagens também.

A: Eles cumprem funções diferentes.
onkeydown é o primeiro a disparar e podêmos pará-lo. Se tiveres um input podes evitar que a tecla premida escreva no input se tiveres um event handler associado.
onkeypress é o segundo a disparar. De notar que este evento não é disparado em teclas que não geram caracteres, como os F1 ~ F12, tab, esc, etc. De notar que o keypress gera resultados diferentes para letra grande e pequena.
onkeyup é disparado quando a tecla é largada e o seu input adicionado/registado no DOM. No caso de um input o novo caracter é inserido e não dá para cancelar, ou seja um input receberá o caractere.
Exemplos:
keydown
Um input que ignora vogais: http://jsfiddle.net/4t4ta4q5/
var input = document.querySelector('input');
var ignorar = ['a', 'e', 'i', 'o', 'u'];
input.addEventListener('keydown', function (e) {
    var char = e.keyCode || e.which;
    var letra = String.fromCharCode(char).toLowerCase();
    if (ignorar.indexOf(letra) != -1) e.preventDefault();
});

keypress
Distinguir letra grande de letra pequena: http://jsfiddle.net/awrjLphp/
function log(e) {
    var char = e.code || e.keyCode || e.which;
    var res = [e.type, char, String.fromCharCode(char), '<br />'].join(' | ');
    document.getElementById('res').innerHTML += res;
};

input.addEventListener('keydown', log);
input.addEventListener('keypress', log);

Este código vai dar
keydown | 77 | M |
keypress | 109 | m |

quando premir-mos o m pequeno e
keydown | 77 | M |
keypress | 77 | M |

no M grande.
keyup
Somar campos: http://jsfiddle.net/gz2ttyt1/
var inputs = $$('body > input').addEvent('keyup', function (e) {
    var numerico = this.value.replace(/[^0-9\.]/g, '');
    if (!numerico) this.value = this.value.slice(0, -1);
    var soma = inputs.map(function (input) {
        return parseFloat(input.value) || 0;
    }).reduce(function (a, b) {
        return a + b;
    }, 0);
    $$('body div > input').set('value', soma);
});

Isso é código MooTools, mas no fundo corre um script a cada keyup e soma os valores dos inputs todos num campo com o total.

A: KeyPress, KeyDown e KeyUp são eventos acionados pelo teclado.
O KeyDown  acontece primeiro (quando a tecla esta abaixando). O KeyPress acontece segundo (quando o texto for digitado). O KeyUp  acontece depois da tecla digitada (quando a tecla estiver subindo e quando a entrada de texto está completo).

A: De acordo com este link:

keydown
Fires when the user depresses a key. It repeats while the user keeps the key depressed.
keypress
Fires when an actual character is being inserted in, for instance, a text input. It repeats while the user keeps the key depressed.
keyup
Fires when the user releases a key, after the default action of that key has been performed

Ou, em miúdos: A diferença entre eles é a ordem que ocorrem, no momento que o usuário pressiona uma tecla. Na teoria, eventos keydown e keyup representam a tecla sendo apertada ou solta, respectivamente, enquanto o evento keypress representa um caractér sendo digitado (e se repete caso o usuário continue segurando a tecla). A questão é que esta teoria não é implementada da mesma maneira por todos os browsers.


text:
Q: is it possible to run R as a daemon I have a script in R that is frequently called during the day (by other scripts). I call R in a terminal using
Rscript code.R

I notice it takes a lot of time to load packages and set up R.
Is it possible to run R as a background service which I hit using a port or something?

A: Yes, look into RServe which has been available for over a dozen years for this reason.  There are a couple of fairly high profile applications too.

A: You can check out this add-in for Rstudio, it is not a port like solution but maybe it can help you https://github.com/bnosac/taskscheduleR


text:
Q: Sorting an array to get the maximum combined sum of the differences between every two adjacent elements This is related to this question: Stack Overflow
Problem description
We are given a sequence of n positive integers. How to sort the elements to get the maximum combined sum of the differences between every two adjacent elements.
For example, for a sequence {8, 4, 1, 2, 3} the starting difference is (8-4) + (4-1) + (2-1) + (3-2) = 9, but 14 can be reached for {4, 8, 1, 3, 2}.
The best arrangement is {4, 1, 8, 2, 3}, sum 17.
Claim
Optimal solution can always be reached by either starting with the smallest or largest element and then alternately putting currently largest/smallest elements on both sides of the sequence.
That's not all yet: for the starting sequence {1, 2, 3, 4} we would start with 4 $\longrightarrow$ 1 4 2 $\longrightarrow$ 3 1 4 2 or 1 4 2 3. So this approach is not strict enough yet.
However, if we always first put to the left and then to the right (or otherwise), we are guaranteed that the number on the left side will be smaller/bigger than the corresponding number on the right side.
I tested the solution above so I am quite sure it works.
I am interested how would you prove it.

A: You are correct:

*

*When $n$ is even, the best arrangement has the highest and lowest in the middle, sandwiched between the second lowest and second highest, sandwiched between the third highest and third lowest, etc.

*When $n$ is odd, the optimal arrangement either has the highest in the middle, sandwiched between the two lowest, then two remaining highest, etc, or it is the similar sequence where you start with the lowest in the middle.
The proof is easier when $n$ is even, so let's start there. Let the sequence of positive integers, sorted in increasing order, be $x_1\le x_2\le \dots\le x_n$. Then, for $i=1,\dots,n-1$, let $s_i=x_{i+1}-x_i$ be the sequence of gaps between the numbers. Finally, given a permutation $y_1,y_2,\dots,y_n$ of the given sequence, for $i=1,\dots,n-1$, let
$$
m_i=\#\{j:y_{j}\le x_{i}\text{ and } y_{j+1}\ge x_{i+1}\}+\#\{j:y_j\ge x_{i+1}\text{ and } y_{j+1}\le x_i \}
$$
In words, $m_i$ is the number of times the sequence $(y_1,\dots,y_n)$ crosses the "gap" between $x_i$ and $x_{i+1}$. Each time the sequence does this, it adds $s_i$ to the total of the absolute differences of the consecutive elements. Therefore, it follows that
$$
|y_2-y_1|+|y_3-y_2|+\dots+|y_n-y_{n-1}|=\sum_{i=1}^{n-1}m_is_i
$$
If this is unclear, I encourage you to look at some examples. You can then show two things:

*

*For the proposed optimal sequence, we have$$
\begin{cases}
m_i=2i & \text{when $i<n/2$}\\
m_{n/2}=n-1\\
m_{n-i}=2i & \text{when $i<n/2$}\\
\end{cases}
$$

*For any permutation, it is true that $$
\begin{cases}
m_i\le 2i & \text{when $i<n/2$}\\
m_{n/2}\le n-1\\
m_{n-i}\le 2i & \text{when $i<n/2$}\\
\end{cases}
$$
These two points imply that the proposed sequence is optimal.
The first bullet can be verified easily. For the second bullet, note that when $i<n/2$, that a crossing between $x_i$ and $x_{i+1}$ can only occur when one of the $i$ smallest values $x_1,\dots,x_i$ is next to one of the largest $n-i$ values. But this can obviously occur at most $2i$ times, to the left and right of each of the $i$ values $x_1,\dots,x_i$.  The same logic applies to $m_{n-i}$. Finally, $m_{n/2}\le n-1$ since there are only $n-1$ adjacent pairs.
I leave the case when $n$ is odd to you. In this case, you will find three things:

*

*When $i<n/2$, $m_i<2i$ and $m_{n-i}<2i$ (same as before).

*Furthermore, letting $k=\lfloor n/2\rfloor$, it is impossible to have both $m_k=2k$ and $m_{k+1}=2k$. At least of these must be smaller than their maximal value in any permutation.

*The two proposed optimal arrangements achieve the maximal values implied by the two previous bullet points.

A: Let the given integers be $a_1,\dots,a_n$.  You can formulate the problem as a traveling salesman problem on a complete graph with $n+1$ nodes.  Besides one node for each array element, introduce a dummy node with $0$ cost to the other nodes.  Otherwise, the cost of edge $\{i,j\}$ is $-|a_i-a_j|$, and you want to find a tour of minimum cost.
If there is a counterexample to your conjectured optimal algorithm, this formulation could help you find one by solving the corresponding TSP to check optimality.


text:
Q: Packing Points into Region In a $64\times 200$ region, the distance between any two points must be at least $25$.

What is the maximum number of points that can be placed inside the region? The most I could fit was 30.
What if they were placed in the most space-inefficient way? (Least number of points present such that no more can be placed)

This has to do with random obstacle generation in a game I'm working on.

A: I can fit 26 of them if some of them are allowed to be on the edge, using hexagonal packing which is optimal for large regions (three columns lengthwise, two of 9 points each that touch the ends, interleaves with one columns of 8 points each).  If you make this one unit wider, I could fit another column, and get 34.  I suspect that if you take a 64x200 rectangle and slide it around a hexagonal pattern with the points 25 apart you will find an oblique angle where more than 26 dots are covered.  But if you can change the region to 65x200, life will be much easier.

A: Since any two points cannot be closer than 25 units, picture each point as the center of a circle with a radius of 25 units, which is the same as a circle with a diameter of 50 units. 4 such circles could be placed one on top of each other in a 64-unit wide by 200-unit high area.
It might look something like this (You have to assume they're touching):
O
O
O
O
Along the top of the uppermost circle, you could have 3 points (upper left corner of the region, 25 units to the right of that point, and then another 25 units to the right).
Similarly, you could have another set of 3 points going through the center of the uppermost circle, and along the bottom of the uppermost circle. Each of these would be exactly 25 from its nearest neighbor. So, the first circle has given us 9 such points.
Each of the other circles is going to add another 6 such points (not 9, because the last set of 3 from the previous circle is the same as the first set of 3 from the new circle). So, that's 3 more circles with 6 points each, or 18 more points.
Adding this result to the previous 9, we get 27 points. I am unfortunately unable to prove this is a maximum, but it does seem like a good starting point.

A: If the size of the rectangular region is $w = 64$ by $h = 200$, and $R = 25$ is the minimum distance between any pair of points, and points are allowed to reside on the perimeter of the region, then the number of points you can put within the rectangular region cannot exceed $N$,
$$N \le \left \lfloor \frac{4 (w + R)(h + R)}{\pi R^2} \right \rfloor$$
because each point excludes a circular region whose area is $\pi\left(\frac{R}{2}\right)^2 = \frac{\pi R^2}{4}$.
In this case, $N \le \lfloor 40.794595 \rfloor$ i.e. $N \le 40$.
From circle packing, we know that not all "area" is used in this way; that you cannot cover all of a surface with non-overlapping circles. In practice, it means that the true, absolute number is somewhat less. (Even the shape, or aspect ratio of the rectangle, matters.)
I am not aware of any methods of finding the actual absolute number of circles/disks/points, because there is an infinite number of positions for each point within the area. Since this is for a game, I'd expect the above known absolute upper limit to suffice, and the actual number of obstacles to vary.


text:
Q: How to get a list of children in a self-referencing table (Parent-Child) using EF Core? I use the following Model to create a self-referencing table:
public class Part
{
    [Key]
    public long PartId { get; set; }
    [Required]
    public string PartName { get; set; }
    public long? ParentPartId { get; set; }
    public Part Parentpart { get; set; }

    //Navigation properties
    public ICollection<Part> ChildParts { get; set; } //For self-referencing
}

The Fluent API is:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//For parts self-referencing
    modelBuilder.Entity<Part>(entity =>
    {
        entity.HasKey(x => x.PartId);
        entity.Property(x => x.PartName);
        entity.HasOne(e => e.Parentpart)
              .WithMany(e => e.ChildParts)
              .HasForeignKey(e => e.ParentPartId)
              .IsRequired(false)
              .OnDelete(DeleteBehavior.Restrict);
    });
}

I can use the following code to get all the parents of a given part:
[HttpGet]
public async Task<IActionResult> GetParentPartsList(string partName)
{
    var q = _sqlServerContext.Parts.Where(x => x.PartName == partName).Include(x => x.Parentpart);

    while (q.Select(x => x.ParentPartId) == null)
    {
        q = q.ThenInclude(x => x.Parentpart);
    }
    q = q.ThenInclude(x => x.Parentpart);

    return Ok(await q.ToListAsync());
}

I want to get a list of all children for a given part. I searched some threads such as this link, but they have a one-one relationship between child and parent while I need a one-many relationship. How can I achieve this?


text:
Q: Spring security OAuth2 "clientDetailsService" circular reference? I have below security config class (at the bottom), recently upgraded to;

*

*Spring Security (3.2.6.RELEASE)

*Spring Security OAuth2 (2.0.6.RELEASE from 2.0.3.RELEASE)

and I started seeing this error messages, now all my integration tests fail with the same error;

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'securityConfig': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
org.springframework.security.oauth2.provider.ClientDetailsService
com.xyz.package.config.SecurityConfig.clientDetailsService; nested
exception is
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'clientDetailsService': Requested bean
is currently in creation: Is there an unresolvable circular reference?
..............
..............
Caused by:
org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'clientDetailsService': Requested bean
is currently in creation: Is there an unresolvable circular reference?

This is definitely caused by upgrading to Spring Security OAuth2 (2.0.6.RELEASE), I didn't have this on 2.0.3.RELEASE.
I appreciate if anyone can give me an insight on this one.
Thanks in advance.
@Configuration
public class SecurityConfig {

@Autowired
private DataSource dataSource;

@Autowired
private ClientDetailsService clientDetailsService;

@Autowired
private RedisConnectionFactory redisConnectionFactory;

@Bean
public TokenStore tokenStore() {
    return new PipelinedRedisTokenStore(redisConnectionFactory);
}

@Bean
public DefaultTokenServices tokenServices() throws Exception {
    DefaultTokenServices tokenServices = new DefaultTokenServices();
    tokenServices.setAccessTokenValiditySeconds(6000);
    tokenServices.setClientDetailsService(clientDetailsService);
    tokenServices.setTokenEnhancer(new MyTokenEnhancer());
    tokenServices.setSupportRefreshToken(true);
    tokenServices.setTokenStore(tokenStore());
    return tokenServices;
}

@Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
    UserApprovalHandler handler = new MyUserApprovalHandler();
    handler.setApprovalStore(approvalStore());
    handler.setClientDetailsService(clientDetailsService);
    handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
    handler.setUseApprovalStore(true);
    return handler;
}

@Bean
public ApprovalStore approvalStore() {
    TokenApprovalStore store = new TokenApprovalStore();
    store.setTokenStore(tokenStore());
    return store;
}

@Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
    return new OAuth2AccessDeniedHandler();
}

@Configuration
@Priority(2000)
@EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${baseUrl}")
    private String baseUrl;

    @Autowired
    private DataSource dataSource;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Autowired
    private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;

    @Bean
    public ClientDetailsService clientDetailsService() throws Exception {
        ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();

        serviceConfig.clientDetailsServiceConfigurer().inMemory()
            .withClient("xxxx")
            .secret("some-secret")
            .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("play", "trust");

        return serviceConfig.clientDetailsService();
    }

    @Bean
    UserDetailsService clientDetailsUserDetailsService() throws Exception {
        return new ClientDetailsUserDetailsService(clientDetailsService());
    }

    @Bean
    public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
        ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
        filter.setAuthenticationManager(authenticationManagerBean());
        filter.afterPropertiesSet();
        return filter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
        jdbcUserDetail.dataSource(dataSource);
        jdbcUserDetail.passwordEncoder(passwordEncoder);
        jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
        jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
        auth.apply(jdbcUserDetail);

        auth.userDetailsService(clientDetailsUserDetailsService());

    }

    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    protected AuthenticationEntryPoint authenticationEntryPoint() {
        OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
        entryPoint.setTypeName("Basic");
        entryPoint.setRealmName("realm/client");
        return entryPoint;
    }

    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity
            .ignoring()
            .antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
            .antMatchers(HttpMethod.POST, "/api/**/account")
        .and()
            .debug(false);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // @formatter:off
        http
            .anonymous().disable()
            .requiresChannel().anyRequest().requiresSecure();

        http
            .antMatcher("/oauth/token")
            .authorizeRequests().anyRequest().authenticated()
        .and()
            .httpBasic().authenticationEntryPoint(authenticationEntryPoint())
        .and()
            .csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
            .exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler)
        .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http
            .addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class);
        // @formatter:on

    }

}

@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerTokenServices tokenServices;

    @Autowired
    private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;

    @Autowired
    ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //resources.tokenServices(tokenServices);
        resources.resourceId("resource");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        // @formatter:off
        http
            .requiresChannel().anyRequest().requiresSecure();

        // API calls
        http
            .anonymous().disable()
            .authorizeRequests()
            .antMatchers("/api/**")
            .access("#oauth2.hasScope('trust') and #oauth2.hasScope('play') and (hasRole('ROLE_USER'))")
        .and()
            .addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER)
        .and()
            .exceptionHandling()
            .accessDeniedHandler(oAuth2AccessDeniedHandler);

        // @formatter:on
    }

}

@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AuthorizationServerTokenServices tokenServices;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
        .tokenServices(tokenServices)
        .userApprovalHandler(userApprovalHandler)
        .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        clients.withClientDetails(clientDetailsService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception {
        oauthServer.authenticationEntryPoint(authenticationEntryPoint)
                .realm("realm/clients");
    }

}

}

** Update (3/17) **
Created https://github.com/aug70/security-sample for this question.
Without changing the configuration seems like things that worked in previous release (2.0.3) is not working anymore. See project readme.

A: Solution posted here. Using Spring Security Oauth 2.0.9 release.


text:
Q: Tricky Chain Rule/Differentation/Derivative/Ellipse problem
When I found the derivative I got:
$$\frac{1}{2}x+ 2y\frac{dy}{dx}=0$$
$$\frac{dy}{dx}=\frac{\frac{-1}{2}x}{2y}$$
$$\frac{dy}{dx}=\frac{-1x}{4y}$$
But I cannot plug in $(4, 0)$ and since point $Q$ is NOT in the circle equation.
By the way the "solution" is $$y = \frac{-x}{2\sqrt{3}} + \frac{2}{\sqrt{3}}$$
But I don't know how that is the solution? Since its from the answer key without steps shown
I mean I could guess and check the slope and plug in any value in the circle equation:
$$y = \pm \sqrt{1 - \frac{1}{4}x^{2}}$$
since the domain of $x$ is $(-2, 2)$.
But this is obviously not how you solve it.emphasized text

A: Notice, let point of tangency $P(h, k)$ on the ellipse hence it will satisfy the equation of the ellipse $\frac{x^2}{4}+y=1$ as follows $$\frac{h^2}{4}+k^2=1\tag 1$$
Now, the slope of the tangent at the point $(h, k)$ is $$\left(\frac{dy}{dx}\right)_{(h, k)}=\text{slope of line PQ joining the points}\ (h, k) \ \text{&}\ (4, 0) $$ $$\frac{-h}{4k}=\frac{k-0}{h-4}$$
$$-h^2+4h=4k^2\iff \frac{h^2}{4}+k^2=h\tag 2$$
Now, comparing (1) & (2), we get
$$h=1$$
Hence, setting this value of $h$ in (1), we get $$\frac{(1)^2}{4}+k^2=1$$ $$k^2=\frac{3}{4}\iff k=\pm\frac{\sqrt 3}{2}$$
Since, the point $P$ is in the first quadrant its y-coordinate $k$ will be positive i.e. $k=\frac{\sqrt 3}{2}$ so we have $P\left(1, \frac{\sqrt3}{2}\right)$
Hence, the equation of the tangent PQ joining the points $P\left(1, \frac{\sqrt3}{2}\right)$ & $Q(4, 0)$ is given as $$y-0=\frac{\frac{\sqrt3}{2}-0}{1-4}(x-4)$$
$$\color{red}{x+2y\sqrt 3-4=0}$$

A: Differentiate using Chain Rule getting equation of tangent ( some steps omitted )
$$ \frac{x x_P}{4} + \frac{y y_P}{1} =1  \tag{1} $$
You are given
$$ x=x_Q=4,y=y_Q=0, \rightarrow x_P= 1 \tag{2}$$
Substitute into equation  of ellipse, you get $ y_P= \frac{\sqrt3}{2} \tag{3}$
Tangent line has equation:
$$\frac{x\cdot 1}{4} + \frac {y \sqrt 3}{2} =1. \tag{4}$$


text:
Q: Running Ubuntu Desktop 20.10 headless on Raspberry Pi 4 8Gb I want to be able to use a Ubuntu desktop on my Raspberry Pi 4 8Gb.  I also want to be able to access that desktop remotely using a tool like VNCViewer.
I have installed Ubuntu Desktop 20.10. I am unable to access the desktop remotely. I have setup SSH so I can access via text (PUTTY).  I can find no vnc capability for example.
Is it possible to do what I want?
When will vnc be available on Ubuntu 20.10 on ARM64 hardware of Raspberry Pi?

A: Install x11vnc to access the default desktop.  However, if there is no physical monitor connected to the Pi the desktop won't start.  A work around is to connect an HDMI dummy adapter to make the Pi think there is a monitor connected.


text:
Q: ASP.NET exception gives irrelevant stack trace on YSOD, very challenging! Here is the YSOD:
Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.]
   System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +428
   System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +65
   System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
   System.Data.SqlClient.SqlConnection.Open() +122
   ECommerce.PMethod.Sql.SqlConns.Open() +78
   ECommerce.PMethod.Sql.SqlConns..ctor() +120
   ECommerce.login.DatasInfo.Proc.UserCenter.IsLogin(String UserGUID, Int32 UserID) +49
   ECommerce.login.Rules.Users.UserLogin.isLogin() +44
   Config.isUserLogined() +5
   Shopping_Shopping.Page_Load(Object sender, EventArgs e) +10
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
[TypeInitializationException: The type initializer for 'ECommerce.ERP.DAL.DBConn' threw an exception.]
   ECommerce.ERP.DAL.DBConn.get_ConnString() +0
[ObjectDefinitionStoreException: Factory method 'System.String get_ConnString()' threw an Exception.]
   Spring.Objects.Factory.Support.SimpleInstantiationStrategy.Instantiate(RootObjectDefinition definition, String name, IObjectFactory factory, MethodInfo factoryMethod, Object[] arguments) +257
   Spring.Objects.Factory.Support.ConstructorResolver.InstantiateUsingFactoryMethod(String name, RootObjectDefinition definition, Object[] arguments) +624
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateUsingFactoryMethod(String name, RootObjectDefinition definition, Object[] arguments) +60
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +56
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +436
[ObjectCreationException: Error thrown by a dependency of object 'styleService' defined in 'assembly [ECommerce.Services.Impl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Services.Impl.AppContext.xml] line 56' : Initialization of object failed : Factory method 'System.String get_ConnString()' threw an Exception.
while resolving 'constructor argument with name promotionservice' to 'promotionService' defined in 'assembly [ECommerce.Services.Impl, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Services.Impl.AppContext.xml] line 31'
while resolving 'constructor argument with name domainservice' to 'promotionDomainService' defined in 'assembly [ECommerce.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Domain.AppContext.xml] line 20'
while resolving 'constructor argument with name promotionrepos' to 'promotionRepos' defined in 'assembly [ECommerce.Data.AdoNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Data.AdoNet.AppContext.xml] line 34'
while resolving 'constructor argument with name connstr' to 'ECommerce.ERP.DAL.DBConn#389F399' defined in 'assembly [ECommerce.Data.AdoNet, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [ECommerce.Data.AdoNet.AppContext.xml] line 34']
   Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveReference(IObjectDefinition definition, String name, String argumentName, RuntimeObjectReference reference) +394
   Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +312
   Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +17
   Spring.Objects.Factory.Support.ConstructorResolver.ResolveConstructorArguments(String objectName, RootObjectDefinition definition, ObjectWrapper wrapper, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) +993
   Spring.Objects.Factory.Support.ConstructorResolver.AutowireConstructor(String objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, Object[] explicitArgs) +171
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.AutowireConstructor(String name, RootObjectDefinition definition, ConstructorInfo[] ctors, Object[] explicitArgs) +65
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +161
   Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +636
   Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +174
   Spring.Objects.Factory.Support.WebObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +150
   Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +990
   Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) +10
   Spring.Context.Support.AbstractApplicationContext.GetObject(String name) +20
   ECommerce.Common.ServiceLocator.GetService() +334
   ECommerce.Mvc.Controllers.StylesController..ctor() +72
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
   System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
[InvalidOperationException: An error occurred when trying to create a controller of type 'ECommerce.Mvc.Controllers.StylesController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677954
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082
Question is: the first stack trace is irrelevant to others, what happened? Any ideas?
Let me make this more clear:
a MVC page uses the spring part trying to load a lazy-init service which constructor wants a connection string through a static property like this:
<object id="promotionRepos" type="ECommerce.Data.AdoNet.Promotions.PromotionRepos, ECommerce.Data.AdoNet" lazy-init="true">
    <constructor-arg name="provider">
        <null />
    </constructor-arg>
    <constructor-arg name="connStr">
        <object type="ECommerce.ERP.DAL.DBConn, ECommerce.ERP.DAL" factory-method="get_ConnString" />
    </constructor-arg>
    <property name="RefreshInterval" value="00:00:10" />
</object>

the timeout part is some what irrelevent to all others. see this in the first exception: Shopping_Shopping.Page_Load(Object sender, EventArgs e) +10
it's another page at all. And also, ECommerce.PMethod.Sql.SqlConns.Open() uses its own connection string, not the one loaded by spring, it's different module from diffrent team. And I am sure the connection string is correct.
And, this ysod cames up randomly. Sometimes nothing is wrong, and sometimes, it appears.
I thought there could be something wrong with my database or the network/firewall, I will check it later, but now I want understand this tricky stack trace.

A: Looks to me like they are all relevant. They seem to be to do with instantiating objects using Spring.Net. Ultimately it looks like your database server is either not responding or your connection string is completely wrong.
Can you access the database using the DB managemnet software that you use?

A: Im guessing that your connection string is wrong or the database server is not turned on when your application tries to connect to the database. Double check your connection string.


text:
Q: Can the code within a
A: You just need to get the postback values using the Request.Form.
This exposes all the input values in properties.
Look at this:
HttpRequest.Form
If you have an iput with id "name", you can read the user input like so:
  Request.Form["name"]

The result is always a string, so that you'll need to parse it to convert it to another data type.


text:
Q: changing and saving ProcessParameters programatically TFS Build Definitions TFS 2012
VS 2012
I have large number of Build Definitions that are derived from single template.
I also have a Master Build to queue all those builds and pass arguments if I need to do so.
That part was done using TFS Community Extension: QueueBuilds.
Problem:
Is there a way to access Build Definitions, loop through them, (can get up to here by myself) and change their ProcessParameters and save them.

A: You can use the Microsoft.TeamFoundation.Build.Client and related assemblies to update the process parameters via PowerShell or C#.  The one tricky part is the parameters are stored in XML so you have to deserialize, make your changes,  then serialize again to set them.
This likely won't run without some tweaking but here are some snippets from one of my scripts that will help:
    [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.TeamFoundation.Build.Client')
    [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.TeamFoundation.Build.Workflow')
$projectCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($TFSUri)
$buildServer = $projectCollection.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])    $buildServer = GetBuildServer -TFSUri $TFSUri
$buildDefinition = $buildServer.GetBuildDefinition($TeamProjectName, $BuildName);
...

  $parameters = [Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers]::DeserializeProcessParameters($buildDefinition.ProcessParameters)
  $msBuildArguments = $parameters.Get_Item("MSBuildArguments")
  $msBuildArguments = "$msBuildArguments /p:ImportParametersFilesOverride=true"
  $parameters.Set_Item("MSBuildArguments", $msBuildArguments)
  $parameters.Add("GetVersion", "c$TFSChangeSetNumber")
  $buildRequest.ProcessParameters = [Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers]::SerializeProcessParameters($parameters)


text:
Q: GRPC Installation - Unable to load dynamic library 'grpc.so' After getting my problem solved on this brilliant ansewer on how to get Pear running with success on Mac OS, I'm in trouble with the below errors while I'm trying to install and configure GRPC according to this google instruction
I understand that the problem is that the system is "Unable to load dynamic library 'grpc.so'"
Please can anybody give me a path on how to solve those issues or maybe show me what I'm doing wrong?
I'm running my localhost with PHP 8 served by MAMP
Thank you very much!!
composer require "grpc/grpc:^1.38"

PHP Warning:  PHP Startup: Unable to load dynamic library 'grpc.so' (tried: /usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so (dlopen(/usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so, 0x0009): dlopen(): file not found: /usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so), /usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so.so (dlopen(/usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so.so, 0x0009): dlopen(): file not found: /usr/lib/php/extensions/no-debug-non-zts-20180731/grpc.so.so)) in Unknown on line 0

A: My solution is just create directory by run command
"mkdir /usr/local/lib/php/pecl"

A: In my case, I am using PHP 7.4 in MacOS. When I ran the
pecl install grpc

... command; it installed the .../20190902/grpc.so inside the current PHP version folder, so, I just copy-paste the grpc.so in the right path mentioned in console:
php@7.4/7.426_1/pecl/20190902/grpc.so --> /usr/local/lib/php/pecl/20190902/grpc.so

I hope this can be helpful to anybody!


text:
Q: Can't open PDF's in Outlook using Parallels 8 vm All of the sudden, I am not able to open PDF's that are attached to emails, UNLESS I save/copy them to different location.
Once I save it/copy it or drag it from the email to my OSX 10.8.5 Desktop, I can open it.
I run Win 7 on an MBA w/10.8.5 running in a Parallels vm.
Thanks-

A: Solved the issue. I needed to re-associate PDF's w/Adobe in the Win 7 Control panel.


text:
Q: Why do I have an error when I try to override a generic binding with Guice? (TypeLiteral) I'd like to override a generic type binding, but I allways got the same "No implementation was bound" error.
I'm using roboguice 3.
Here is a exemple of code that I use:
public interface IParser<I, O> {}

public class Parser1 implements IParser<String, String> {
    IParser<String, String> mParser;

    @Inject
    public Parser1(IParser<String, String> parser) {
        mParser = parser;
    }
}

public class Parser2 extends Parser1 {
    @Inject
    public Parser2(IParser<String, String> parser) {
        super(parser);
    }
}

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1>() {});
    }
}

And here is my injector creation :
RoboGuice.getOrCreateBaseApplicationInjector(this,
                RoboGuice.DEFAULT_STAGE,
                RoboGuice.newDefaultRoboModule(this),
                Modules.override(new MyModule()).with(new AbstractModule() {
                    @Override
                    protected void configure() {
                        bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser2>() {});
                    }
                })
);

If I don't try to override it (only user Parser1), all is fine, when I override standard object with providers, it works well too, but not with TypeLiteral.
My error is :
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for IParser<String, String> was bound.

What am I doing wrong?
Thanks.

A: You should change definition of classes which are implemented your interface.
Try this:
public class Parser1<I, O> implements IParser<I, O> {
}
public class Parser2<I, O> extends Parser1<I, O> {
}

And then you can bind your interface to class by this way:
bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1<String, String>() {});

A: I'm not shure, but it looks remarkable to me that a binding to a conrete instance is used instead to a Class:
bind(new TypeLiteral>() {}).to(new TypeLiteral() {});
did you try
bind(new TypeLiteral<IParser<String, String>>() {}).to(Parser2.class});

?


text:
Q: Dependency properties concept I don't understand the Wpf dependency properties use.
Can anybody explain what is it and it's use and how to use and learn simple the concept.

A: Dependency properties work much like ordinary properties, but you can set their values in XAML. For example, take the following dependency property declaration made in a class called MyCustomControl:
public bool EditMode
{
    get { return (bool)GetValue(EditModeProperty); }
    set { SetValue(EditModeProperty, value); }
}
public static readonly DependencyProperty EditModeProperty = DependencyProperty.Register("EditMode", typeof(bool), typeof(MyCustomControl), new PropertyMetadata(null));

I can now set the EditMode property in the tag itself:
<controls:MyCustomControl EditMode="True"/>

Dependency properties also raise PropertyChanged events, so you can bind to them without having to implement INotifyPropertyChanged yourself.


text:
Q: hashcode varbinary(20) c# I have this class:
public class SomeClass
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    public string Str3 { get; set; }
    public string Str4 { get; set; }
}

and I would like to create a hashkey, which is persisted in a database as varbinary(20), to determine uniqueness of the class (case insensitive). I guess the usual GetHashCode method could not be used in this case. What would be best practice in this scenario?

A: Simple example:
public class SomeClass
{
    public string Str1 { get; set; }
    public string Str2 { get; set; }
    public string Str3 { get; set; }
    public string Str4 { get; set; }

    public byte[] SHA256()
    {
        using (var sha256 = new SHA256Managed())
        {
            var strings = new[] { Str1, Str2, Str3, Str4 };

            for (int i = 0; i < strings.Length; i++)
            {
                string str = strings[i];

                if (str != null)
                {
                    // Commented lines are for using ToUpperInvariant()
                    //str = str.ToUpperInvariant()
                    byte[] length2 = BitConverter.GetBytes(str.Length);
                    sha256.TransformBlock(length2, 0, length2.Length, length2, 0);

                    // byte[] sortKeyBytes = Encoding.UTF8.GetBytes(str);
                    byte[] sortKeyBytes = CultureInfo.InvariantCulture.CompareInfo.GetSortKey(str, CompareOptions.IgnoreCase).KeyData;

                    sha256.TransformBlock(sortKeyBytes, 0, sortKeyBytes.Length, sortKeyBytes, 0);
                }
                else
                {
                    byte[] length2 = BitConverter.GetBytes(-1);
                    sha256.TransformBlock(length2, 0, length2.Length, length2, 0);
                }
            }

            sha256.TransformFinalBlock(new byte[0], 0, 0);

            byte[] hash = sha256.Hash;
            return hash;
        }
    }
}

I'm using SHA256 and the solution is based on the solution suggested by @usr in https://stackoverflow.com/a/10452967/613130 . The generated hash code is 32 bytes long, but you can truncate it to 20 (clearly you'll reduce its uniqueness).
I prepend the length of the various strings to the strings. In this way { "ABCD", "", "", "" } will produce a different hash than { "A", "B", "C", "D" }.
If you prefer you can use good old ToUpperInvariant() and hash based on it (there are some commented lines in the code... You uncomment them, remove the byte[] sortKeyBytes = CultureInfo.InvariantCulture and live happy :-) ).
I have to tell the truth, I'm not sure of the "stability" of GetSortKey... Will GetSortKey return the same weights in 5 years, in .NET 10.0 with Unicode 11.0? Who knows? I surely don't!
MSDN suggests that they could change:

If an application serializes a SortKey object, the application must regenerate all the sort keys when there is a new version of the .NET Framework.

So in the end I suggest the alternative solution based on .ToUpperInvariant() (to be clear, if my boss asked me to do it, I would tell him: use .ToUpperInvariant()). Note that even with .ToUpperInvariant() there could be small changes in the future. New upper case characters could be introduced for existing lower case characters. See http://unicode.org/faq/casemap_charprop.html "Can a case pair be added if one of the pair is already encoded?"

A: A varbinary(20) is 160 bits so you are looking for a 160 bit hash algorithm. The SHA-1 algorithm produces a 160 bit hash value.
It seems that the purpose of your question is to create a hash value that is expected to be unique for a given instance of SomeClass so you should favor fast hash algorithms over cryptographic hash algorithms. SHA-1 is a cryptographic algorithm but it is pretty fast and there is an implementation in the .NET Framework. Also, there exists attacks on the SHA-1 algorithm so you should not use it for cryptographic purposes but instead chose algorithms like SHA-256 (that are slower).
All in all I believe that SHA-1 is a good fit for your problem. It is simple to use the algorithm. 1) Concatenate the strings, 2) convert them to upper case, 3) convert them to bytes using a suitable encoding (I use UTF-8) and 4) compute the hash:
Byte[] GetHash(SomeClass someClass) {
  if (someClass == null)
    throw new ArgumentNullException("someClass");

  var byteBuffers = GetStrings(someClass).Select(
    s => String.IsNullOrEmpty(s)
         ? new Byte[0] : Encoding.UTF8.GetBytes(s.ToUpperInvariant())
  );
  var bytes = byteBuffers
    .Aggregate(new List<Byte>(), (l, b) => { l.AddRange(b); return l; })
    .ToArray();
  using (var sha1 = new SHA1Managed())
    return sha1.ComputeHash(bytes);
}

IEnumerable<String> GetStrings(SomeClass someClass) {
  yield return someClass.Str1;
  yield return someClass.Str2;
  yield return someClass.Str3;
  yield return someClass.Str4;
}

Note that any hash algorithm (also cryptographic algorithms) can and will produce collisions.
Xanatos has a very good point:

I prepend the length of the various strings to the strings. In this way { "ABCD", "", "", "" } will produce a different hash than { "A", "B", "C", "D" }.

Here is an alternative solution that solves the same problem in a slightly different way where each string length modulo 256 is included in the hash:
Byte[] GetHash(SomeClass someClass) {
  if (someClass == null)
    throw new ArgumentNullException("someClass");

  var byteBuffers = GetBuffers(GetStrings(someClass));
  var bytes = byteBuffers
    .Aggregate(new List<Byte>(), (l, b) => { l.AddRange(b); return l; })
    .ToArray();
  using (var sha1 = new SHA1Managed())
    return sha1.ComputeHash(bytes);
}

IEnumerable<String> GetStrings(SomeClass someClass) {
  yield return someClass.Str1?.ToUpperInvariant();
  yield return someClass.Str2?.ToUpperInvariant();
  yield return someClass.Str3?.ToUpperInvariant();
  yield return someClass.Str4?.ToUpperInvariant();
}

IEnumerable<Byte[]> GetBuffers(IEnumerable<String> strings) {
  foreach (var @string in strings) {
    if (!String.IsNullOrEmpty(@string)) {
      yield return new[] { (Byte) (@string.Length%256) };
      yield return Encoding.UTF8.GetBytes(@string);
    }
    else
      yield return new Byte[1];
  }
}


text:
Q: Inject object into dynamically created component constructor I have an Angular 7 component:
export class HelloComponent {
  constructor(private data: any) {}
}

And I am creating it dynamically using ComponentFactoryResolver:
private create(data: any) {

  var componentRef = this.componentFactoryResolver
    .resolveComponentFactory(HelloComponent)
    .create(this.injector);

  this.appRef.attachView(componentRef.hostView);

  var element = (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

}

How to inject data object in HelloComponent constructor?

A: You have to use custom injector for that
const injector: Injector = ReflectiveInjector.resolveAndCreate(
[{
     provide: 'config', useValue: {
     value: 'Any value or object here'}
}]);

and in your component use this
export class HelloComponent {
  constructor(@Inject('config') private data: any) {}
}


text:
Q: Ошибка легкого кода: TypeError: unsupported operand type(s) for /: 'int' and 'tuple' решил написать простенький кальулятор ,только ошибка в предпоследней строке:TypeError: unsupported operand type(s) for /: 'int' and 'tuple'
# I = tok
# U = naprezhenye
# p = мощность
# tok = moschonost / (1.73 *naprezhenye* cos f )
u = eval(input("введите напряжение: ") )
P = eval(input("введите мощность:"))
z = 1.73 * u
o = z * 0,86
v = P/o
print ("тoк:", v)

A: Ошибка в этой строке:
o = z * 0,86

Замените запятую на точку.


text:
Q: Unit Tests fail, then don't After some serious frustration and headaches, I've managed to add unit tests to an existing project. The problem is, the tests only get executed 50% of the time. I have a test method with an STFail macro inside, when I run the tests, it fails as I'd expect. Then, I run the tests again without touching any code/settings and it will pass without hitting breakpoints in the test fixture. The console prints out this output when this happens:
The executable for the test bundle at  ... octest could not be found.
I've had a Google but there doesn't seem to be many/any people with this exact issue and other discussions on the subject are going over my head. If anyone can shed some light on this issue, It'll be very much appreciated.
Thanks.

A: I took your fresh project and reproduced the problem. There are a number of issues, and one unknown:
Build Phases of test target:

*

*Target Dependencies: Specify TestApp, so that the main target is always built first.

*Compile Sources: Don't include any main sources. Only include TestAppUnitTests.mm

*Link Binary With Libraries: The only one needed is SenTestingKit.framework. We can throw in Foundation and UIKit for good measure.

*Copy Bundle Resources: Should have nothing. (Later, you may want test-specific resources.)

Build Settings of test target:

*

*Bundle Loader should be $(BUILT_PRODUCTS_DIR)/TestApp.app/TestApp

*Test Host should be $(BUNDLE_LOADER)
Scheme of main target:

*

*Test -> Info should specify the test target

But even if I make all these changes, your project still has the odd behavior. The simulator sometimes gets a version of the app named, literally, ${PRODUCT_NAME}. Even debugging the app sometimes shows "Debug ${EXECUTABLE_NAME}" in the Log Navigator. So something else is awry, and I don't know what.
The best solution is to create a new project from scratch, specifying "Include Unit Tests". I've verified that this works.


text:
Q: Is there a way to create a "general" login for all Stack Exchange sites? On Stack Overflow, I'm user user:4279155. Imagine I login on that site, then:

*

*I surf to the Software Engineering site.

*I surf to the Super User site.

This gives different behaviour for Microsoft Edge and Google Chrome web browsers:
For both web browsers, I get logged in immediately at the Software Engineering site.
At the Super User site however:

*

*using Microsoft Edge, I get logged in automatically.

*using Google Chrome, I don't get logged in automatically.

Is this a bug of the Stack Exchange site? (I'm a regular user of Google Chrome and I would like to get logged in at every Stack Exchange site I visit.)
Before I forget, I have the habit of surfing incognito (also known as InPrivate).


text:
Q: Pad bytes to number I'm trying to work on seperating TCP socket messages between a server and client. The way I'm trying to do this is by starting each message with 4 bytes which contains an integer describing the size of the message. The problem is I don't know how to pad that integer with the extra bytes to make it's size 4 bytes. I am on windows.
Also the server is written in node but I think I have that side of the equation figured out.
Here is some of my code if it helps:
    $data = JSON->new->utf8->encode({test=>123});
    print $OUTPUT_SOCKET length(encode('UTF-8', $data)); # This needs to be 4 bytes
    print $OUTPUT_SOCKET $data

A: sprintf "%32d",  $length  # Padded with spaces
sprintf "%032d", $length  # Padded with zeroes

If it doesn't need to be a text format, use the following:
pack 'N',  $length   # 32-bit unsigned int (4 bytes) in BE byte order.
pack 'Q>', $length   # 64-bit unsigned int (8 bytes) in BE byte order.

If you take this approach, you can combine everything:
print $SOCK pack 'N/a*', $encoder->encode($data);  # Or Q>/a*


text:
Q: unable to use import.sql in playframework I'm trying to import an initial db into my play application but i get the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at end of input

full error: https://gist.github.com/rolandg/8e10e9be18a57a057e060bd9f02c6141
config:
persistence.xml
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
         version="2.1">

<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <non-jta-data-source>DefaultDS</non-jta-data-source>

    <properties>
        <!--Hibernate properties-->
        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
        <property name = "hibernate.hbm2dll.import_files" value="conf/import.sql"/>
    </properties>
</persistence-unit>

import.sql
INSERT INTO Usr (entrydate, email, birthdate, lastname, password, phone, username, firstname, superior) VALUES
  ('2016-01-01', 'rossi.mario@gmail.com', '1987-06-25', 'rossi', '123456', '0471287130', 'mario', '', '');

Usr.java
package models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.Date;

@Entity
public abstract class Usr {

        @Id
        @GeneratedValue private Long personId;

        @Column public String username;
        @Column private String password;

        @Column private String firstname;
        @Column private String lastname;
        @Column private Date birthdate;
        @Column private Date entrydate;
        @Column private String email;
        @Column private String phone;

        // cons
        public Usr() {
        }

        //getter
        public Long getPersonId() {
            return personId;
        }

        public String getUsername() {
            return this.username;
        }

        public String getPassword() {
            return this.password;
        }

        public String getFirstname() {
            return this.firstname;
        }

        public String getLastname() {
            return this.lastname;
        }

        public Date getBirthdate() {
            return this.birthdate;
        }

        public Date getEntrydate() {
            return this.entrydate;
        }

        public String getEmail() {
            return this.email;
        }

        public String getPhone() {
            return this.phone;
        }

        //setter
        public void setUsername(String username) {
            this.username = username;
        }

        public void setPersonId(Long personId) {
            this.personId = personId;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public void setFirstname(String vorname) {
            this.firstname = vorname;
        }

        public void setLastname(String nachname) {
            this.lastname = nachname;
        }

        public void setBirthdate(Date geburtsdatum) {
            this.birthdate = geburtsdatum;
        }

        public void setEntrydate(Date eintritt) {
            this.entrydate = eintritt;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public void setPhone(String telefon) {
            this.phone = telefon;
        }

}

What am I doing wrong? The table gets created but there seems to be some error in my import.sql/config.
Please help..

A: just add the following line to persistence.xml to allow sql statements with multiple lines.
<property name="hibernate.hbm2ddl.import_files_sql_extractor" value="org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor" />

source


text:
Q: Blogger show external image thumbnail in popular posts There is a Popular Post Widget provided by Blogger, which can find the popular posts' first image and show it on the sidebar of your blog.
But it can only find images which are directly uploaded to Blogger, it doesn't work on external image links. I'm wondering if there's a way to read the external image by editing its code, maybe in javascript I think...
The default generated code:

<data:post.title/>

<data:post.snippet/>

Since there are so many b:if and data: in the code, I'm not sure if I can treat it as a normal html file or not.

A: I made a widget below, which can show popular posts' thumbnail by external images. Copy all the code and add it as a widget fixes the problem.
It gets the first image in the posts, both internal images and external images worked well.
Code: GitHub

A: try this one

<data:post.title/>

<data:post.snippet/>


text:
Q: Intellij IdeaVim: access IDE shortcuts without making vim give up control of that shortcut ctrl-O is used to jump to the previous entry in the jump list.
But in the IDE, according to the documentation, ctrl-O helps you override methods declared in a base class, kind of like ctrl-enter in Eclipse when the cursor is on an empty line.
One can change a setting that will assign the control of ctrl-O to the IDE. That would make vim loose access to that key, and you'd no longer can use it to jump around the jump list.
Is there a special shortcut key, so that the next key is handled by the IDE instead of vim?

A: You can assign another shortcut to the override methods action via Settings | Keymap while keeping CTRL-O under control of IdeaVim in Settings | Vim Emulation.


text:
Q: Android: Proper way to download lots of files In my app I need to download a bunch of files. My original plan was use an individual AsyncTask for each file, so that I can notify the rest of the app when each file is downloaded. I found it testing that while this works, its seems really memory in-efficient. Is there a good way to use a single AsyncTask or maybe a Service to download the files and notify on each files complete?

A: There's no reason to use numerous AsyncTasks, since you may create the list of file names, pass it to the single AsyncTask, and after each file is downloaded, publish the download progress with publishProgress() and onProgressUpdate(), which is run in UI thread and can easily notify other activities in your application.
private class DownloadFilesTask extends AsyncTask<URL, String, Long> {
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        for (int i = 0; i < count; i++) {
            Downloader.downloadFile(urls[i]);
            publishProgress(urls[i].toString());
        }
        return 0;
    }

    protected void onProgressUpdate(String... progress) {
        // notify whomever you like with url from progress[0]
        // this is run on UI thread
    }

    protected void onPostExecute(Long result) {
        // do something else
        // this is also run on UI thread
    }
}

A: A remote service would work, but I think it is the wrong approach since you have just a limited functionality for it.
I would use AsyncTask, but have it called by a method.
When you are finished in the AsyncTask then call the method again that will create a new AsyncTask after removing the item in the list, or updating some counter.
Remember that an AsyncTask cannot be reused, so it needs to be created fresh each time.

A: From memory and network standpoint you would be better off using just one AsyncTask (or a Java thread) and download all files one by one. This greatly improves device's responsiveness and also consumes a little of memory.
In case you can control server side, I would also suggest you zip smaller files to one archive (my project also downloads a lot of files via HTTP) and it shows great improvement of speed if files are combined into archives with size of about 2-4 MB and downloaded.
In case you are downloading using just TCP/IP connection, it will not matter how big are files if you will not reestablish connection every time.
But again for HTTP the biggest time waster is usually connection establishment.


text:
Q: How to delete a file that is stored in Ceph via Block device mounted on Ubuntu? I have followed the docs here and created a basic Ceph block device
I can also read/write to the block device using basic C# file operation.
Howerver when i delete a file using rm command in linux terminal, the file is removed from mounted device but the disk still remains occupied (at least that is what is shown in dashboard plugin).
Any why one knows the cause?

A: Ceph block storage (rbd) allows you to create full file systems on top of ceph. However these filesystems don't know they're on top of ceph and behave as they would normally. When an object is deleted the filesystem marks it as deleted without actually releasing space to the underlying data store.
You can force the filesystem to release the space by running the fstrim command on the block device.
See this post for a more detailed explanation of what's going on: https://www.sebastien-han.fr/blog/2015/01/26/ceph-and-krbd-discard/


text:
Q: Is it certain that two (new Date()).getTime in one JavaScript file will get two different results? I want to generate unique ids for some variables. I need to create a new id everytime for some variable.
Is it safe to use such kind of code?
var id = 'id_' + (new Date()).getTime();

I need to make sure there's no duplicate id during running my script.

A: I don't think that's ideal for generating unique ids, I'd suggest using UUIDs instead. They are globally unique, you will never get collisions.
If you make several calls of 'id_' + (new Date()).getTime() in the same millisecond, you will get duplicated ids.
You can easily create UUIDs using the uuid library:

const ids = Array.from({ length: 5}, () => uuid.v4());
console.log("Ids:", ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.2/uuid.min.js" integrity="sha512-UNM1njAgOFUa74Z0bADwAq8gbTcqZC8Ej4xPSzpnh0l6KMevwvkBvbldF9uR++qKeJ+MOZHRjV1HZjoRvjDfNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

You'll see that if you generate a bunch of ids at the same time they can easily be duplicates, so that approach will be very risky:

let ids = Array.from({ length: 5}, () => 'id_' + (new Date()).getTime());

console.log("IDS:", ids);

A: UUID package is recommended of course but perhaps you can still get pretty unique IDs by doing
(Date.now()*Math.random()).toString(36).replace(".","").toUpperCase()

Lets test a 1000000 successively generated IDs for uniqueness.

var uid      = _ => (Date.now()*Math.random()).toString(36).replace(".","").toUpperCase(),
    uids     = Array.from({length:1000000}, _ => uid())
                    .sort(),
    isUnique = uids.slice(1)
                   .every((id,ix) => id !== uids[ix]);

console.log(isUnique);


text:
Q: Обновление формы с файлом в Symfony Доброго времени суток!
Я учусь работать с Symfony и построил простейшую форму для добавления в БД. Проблема в том, что при использовании такой же формы при редактировании записи валидатор ругается на то, что файл не может быть найден, пустое поле с файлом или нет. При редактировании записи загрузка файла по сути не должна быть обязательной, поэтому добавил новую опцию в FormType, но всё равно ошибка :(
ProjectsController:
   /**
     * @Route("/projects/{id}/edit", name="project_edit", methods={"GET", "POST"})
     */
    public function edit($id, Request $request) {
        $project = $this->getDoctrine()
            ->getRepository(Project::class)
            ->find($id);
        $em = $this->getDoctrine()->getManager();

        $form = $this->createForm(ProjectType::class, $project, ['require_photo' => false]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $project = $form->getData();

            if ($request->files->get('photo')) {
                $filesystem = new Filesystem();
                $path = $this->getParameter('photos_directory') . '/' . $project->getPhoto();
                $filesystem->remove($path);

                $file = $form['photo']->getData();
                $fileName = uniqid() . '.' . $file->guessExtension();

                $file->move(
                    $this->getParameter('photos_directory'),
                    $fileName
                );

                $project->setPhoto($fileName);
            }

            $em->persist($project);
            $em->flush();

            $this->addFlash('success', 'Das Projekt wurde erfolgreich erschafft!');
            return $this->redirectToRoute('projects', [
            ]);
        }

ProjectEntity.php
/**
 * @ORM\Entity(repositoryClass="App\Repository\ProjectRepository")
 */
class Project
{
    ...

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Image(maxSize="5000k")
     */
    private $photo;

    ...

    public function getPhoto(): ?string
    {
        return $this->photo;
    }

    public function setPhoto(?string $photo): self
    {
        $this->photo = $photo;

        return $this;
    }
}

ProjectType:
public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name', TextType::class, [
            'attr' => ['class' => 'form-control'],
        ]);
        $builder->add('description', TextareaType::class, [
            'attr' => ['class' => 'form-control'],
            'empty_data' => 'Beschreibung',
        ]);
        $builder->add('site', TextType::class, [
            'attr' => ['class' => 'form-control'],
            'empty_data' => 'Website'
        ]);
        $builder->add('photo', FileType::class, [
            'attr' => ['class' => 'custom-file-input'],
            'required' => $options['require_photo'],
            'mapped' => false,
        ]);
        $builder->add('save', SubmitType::class, [
            'label' => 'Projekt erstellen',
            'attr' => ['class' => 'btn btn-lg btn-success']
        ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Project::class,
            'require_photo' => true,
        ]);

        $resolver->setAllowedTypes('require_photo', 'bool');
    }

edit.html.twig
<div class="custom-file">
        {{ form_widget(form.photo) }}
        {{ form_label(form.photo, 'Das Foto des Projektes', {
            'label_attr': {'class': 'custom-file-label'},
        }) }}

        {{ form_errors(form.photo) }}
    </div>

A: Проблема была в ProjectType, нужно было добавить contraints для билдера поля с файлом, и удалить валидацию файла в Entity и validator.yaml
$builder->add('photo', FileType::class, [
            'attr' => ['class' => 'custom-file-input'],
            'required' => $options['require_photo'],
            'mapped' => false,
            'constraints' => [
                new Image([
                    'maxSize' => '5000k'
                ])
            ]
        ]);


text:
Q: OrderedDict Isn't Ordered? I'm trying to use an OrderedDict, but it keeps being created out of order. For example,
from collections import OrderedDict
OrderedDict(a=1,b=2,c=3)

yields
OrderedDict([('a', 1), ('c', 3), ('b', 2)])

rather than the expected
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

How can I make sure it's created in the proper order I intend?

A: collections.OrderedDict keeps track of the order in which elements were added to it. This would work fine in a loop:
c = collections.OrderedDict()
for a,b in zip('abc', (1,2,3)):
    c[a] = b

However, the expression OrderedDict(a=1,b=2,c=3) creates an OrderedDict by passing several keyword arguments to its constructor. In Python 2.7, the order of keyword arguments is not guaranteed. If you want that, you'll have to move to Python 3.6, which implements PEP 468, Preserving the order of **kwargs in a function.

The **kwargs syntax in a function definition indicates that the interpreter should collect all keyword arguments that do not correspond to other named parameters. However, Python does not preserved the order in which those collected keyword arguments were passed to the function. In some contexts the order matters. This PEP dictates that the collected keyword arguments be exposed in the function body as an ordered mapping.

A: That is because the keyword arguments (variable = value, ) that you pass will be consolidated into a Python dictionary first. And Python dictionaries are unordered. kwds  will be that dictionary as you can see in the Init signature.
Init signature: OrderedDict(self, *args, **kwds)

This is how the OrderedDict will be initialized internally when you pass the keyword arguments:
for key, value in kwds.items():
   self[key] = value

Since kwds is unordered, you will get an unordered OrderedDict.
You may create the ordered dict like so:
from collections import OrderedDict
from string import ascii_lowercase

d = OrderedDict()
for a,b in enumerate(ascii_lowercase[:3], 1):
    d[b] = a

Or:
n=3
d = OrderedDict(zip(ascii_lowercase[:n], range(1,n+1)))
print d

Output:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

A: It's weird that it hasn't been mentioned already but the representation of OrderedDict shows you how to create it so that the order is kept:
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

it's not meant as an obstacle that the representation is like that - it's because that representation can be used to create an identical ordered OrderedDict.

Just for completeness (it has been mentioned already), the order is lost because OrderedDict(a=1, b=2, c=3) catches these arguments as **kwargs, which is a normal unordered-dict. At least until python 3.6 came along and made the promise that the order of the kwargs will be kept when you pass it in as you did:

What's New In Python 3.6
PEP 468: Preserving Keyword Argument Order
**kwargs in a function signature is now guaranteed to be an insertion-order-preserving mapping.

A: Read the docs:

The OrderedDict constructor and update() method both accept keyword arguments, but their order is lost because Python's function call semantics pass-in keyword arguments using a regular unordered dictionary.

You must pass the input as a sequence of tuples (or an existing ordered dict type) to preserve ordering.
Note that Python 3.6 now provides a guarantee that keyword arguments are passed in the same order they appear in the code (from left to right), thanks to PEP 468, so on Python 3.6 and later, your code will just work.

A: You can create the desired mapping by using sorted():
dict = {"a":"some_value", "b":"other_value", "c":"foo"}
ordered = OrderedDict(sorted(dict.items(), key=lambda t: t[0]))

This sorts the items prior to passing them to the OrderedDict constructor.
The key= section sets the sorting, and t[0] sorts by the dictionary key.


text:
Q: AdminClient self-signed certificates I am using in my program the com.ibm.websphere.management.AdminClient to connect to multiple DMGRs. The problem is that those servers are all using self signed certificates. Is there a way to force AdminClient to accept self signed certificates no matter what?

A: It seems that when you create your admin client, you can set it so that it can auto-accept.  You set the AdminClient.CONNECTOR_AUTO_ACCEPT_SIGNER property to "true".
http://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.javadoc.doc/web/apidocs/com/ibm/websphere/management/AdminClient.html
You can also use the com.ibm.wsspi.ssl.RetrieveSignersHelper class to auto-accept signer-certificates.  You can call autoAcceptSignerAndStoreInTrustStore() or autoAcceptSignerForThisConnectionOnly().
For instance:
com.ibm.wsspi.ssl.RetrieveSignersHelper.getInstance().autoAcceptSignerForThisConnectionOnly();
https://www.ibm.com/support/knowledgecenter/SSAW57_8.5.5/com.ibm.websphere.javadoc.doc/web/spidocs/com/ibm/wsspi/ssl/RetrieveSignersHelper.html


text:
Q: Using Unity over Java for building AR application with Tango I am planning to build an augmented reality app using Tango. It will allow to add virtual objects into real scenes. Should I go with Unity or Java or C?
Is Unity capable building AR applications with Tango and can it use Area Learning and depth features in Unity App?
According to StackOverflow that are quite many bugs that happens when using Unity? Are they a big problem?
Thanks!

A: I started with JAVA cause I was most familiar with that language but then switched to Unity as I found it to be more mature with Tango and easier to do stuff with AR.

A: I also started with Java but realistically there is nothing as powerful and simple as Unity available on the Tango platform for 3D content and gaming style interactive development.
In addition, if you want to develop utility applications such as mapping, 3D scanning or those that are not content based then C++ might be a better alternative.
Java seems the least good option of the possibilities as it has no really well supported Scenegraph like Unity, whereas C++ can take advantage of the many open source tools that can do interesting things with 3D.


text:
Q: Complete Merge/Copy/Push of a Branch As part of a build process, I need to essentially make one branch look exactly like another.  It needs to be an actual branch (tagging is not an option).
Both branches will already exist.  The Destination branch will never be touched by anything other than this process.
This is what I have:
git checkout Destination
git merge Source
git push

Does this look like a good approach?  Is there a simpler way?
Edit
To clarify, the end goal would be to take a snapshot of Source and push it to the remote as Destination. We would do this each time a specific build was run.

A:
I need to essentially make one branch look exactly like another.

git branch -f one_branch another

Now one_branch looks exactly like another.  If you want to have one_branch checked out locally as well, replace branch -f with checkout -B.

A: So if you need the exact state why you don't use the Source branch on your destination System?
We use the master Branch for production and a dev Branch for the test system. On the daily work we work with feature branches. So you make a new branch from the master branch work on it and merge the feature branch in the maste and dev branch.
In this case you should never merge the dev in the master branch. With this szenatio you have the abillity to put your feature branch first on the dev and test the feature. After that you merge the feature branch in the master and put it live.
Here is a good tutorial with merge strategies.
https://www.atlassian.com/git/tutorial/git-branches#!merge
If you really need the exact state its better if you make a hard reset to the source branch. Then you can be sure that its really the same.

A: If you want to create a new commit on the tip of my_branch that has exactly the same contents as the tip of other_branch, here's one way to do that:
$ git checkout my_branch                        # make sure we are on the branch we want to add to
$ git rm -rf .                                  # remove everything belonging to current tip
$ git archive other_branch | tar xf -           # replace with the contents of other_branch tip
$ git add -A .                                  # stage all the modifications
$ git commit -m "updated to other_branch"       # commit the changes

If you're on Windows and don't have tar available, the git archive step may need to look more like git archive --format=zip other_branch | unzip ... - I don't use Windows' unzip often enough to remember the appropriate options, and you might have a different unzipper, like winzip or something, so the exact command may need some adjusting. But the basic process should stay the same...
Your approach with git merge is valid, but may not produce exactly the results you want, since it creates a new commit that contains the changes made on both branches merged together (hence the name...), and so it isn't really a snapshot. The above takes a snapshot of the current tip of other_branch and adds that as a new commit on the top of my_branch, and would be appropriate for example if you are building a side branch that contains only release snapshots, or other specific milestone-type commits without all the intermediate commits.
You might also be able to achieve this with a git merge -s ours --squash or something, followed by moving branch pointers around, but I tend to think the above is at least conceptually easier to follow.


text:
Q: Why is my Hybrid App WKWebView unexpectedly reloading Since upgrading to IOS 13, the WKWebView in my hybrid app unexpectedly reloads after invoking the camera app.
The app is also requesting location at the same time, so I wondered if this was somehow due to the app requesting location whilst being backgrounded to bring the camera app to the front. However the app is not terminated, it is simply the WKWebView that reloads.
So perhaps it is a memory issue, the camera app probably uses a lot of memory. However I cannot see what would cause the WKWebView to be reloaded.
It is causing me a lot of grief because the main functionality of the app is all inside the javascript so the context behind taking the photo is lost when the WKWebView reloads.
Anyone any ideas what could be causing this. It all worked fine from IOS7 up to IOS12 (obviously UIWebView in the app's early days)
I have run this in XCode and watched to see if there are any error messages in the console, but all I get displayed is
[BackgroundTask] Background Task 2 ("Called by MyApp, from -[BackgroundTaskManager beginNewBackgroundTask]"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.
[Snapshotting] Snapshotting a view (0x100e6c180, CAMHDRButton) that has not been rendered at least once requires afterScreenUpdates:YES.
[Snapshotting] Snapshotting a view (0x100e43ee0, CAMTimerButton) that has not been rendered at least once requires afterScreenUpdates:YES.

A: I have just realised that this is because I moved the WKWebView generation code from ViewDidLoad to ViewDidAppear and I failed to check that it was not appearing for the first time.


text:
Q: Understanding Feynman's argument about Stevinus In the Feynman lectures vol 1, chapter 4, he mentioned a "Brilliant, clever" way of solving a problem named:

A simple example is a smooth inclined plane which is, happily, a
  three-four-five triangle. We hang a one-pound weight on the
  inclined plane with a pulley, and on the other side of the pulley, a
  weight $W$. We want to know how heavy $W$ must be to balance the one
  pound on the plane.

After solving the problem with a simple insight on conservation of energy, he describes:

It can be deduced in a way which is even more brilliant, discovered
  by Stevinus and inscribed on his tombstone. Figure 4–4 explains that
  it has to be $\frac{3}{5}$ of a pound, because the chain does not go around. It
  is evident that the lower part of the chain is balanced by itself, so
  that the pull of the five weights on one side must balance the pull of
  three weights on the other, or whatever the ratio of the legs. You
  see, by looking at this diagram, that WW must be $\frac{3}{5}$ of a pound. (If
  you get an epitaph like that on your gravestone, you are doing fine.)

After trying for around three days, I can't understand how you solve the problem with the Stevinus' epitaph (but I understand partially why the three weights on the vertical side should balance the five weights on the slanted, but they are same weight)

A: The ball-chain is intended to represent uniform weight distribution along to two upper sides of the triangle; if they were 10 times smaller you would have 30 on the vertical face, and 50 on the ramp.  The hanging loop completes the chain.
Does the chain begin to rotate on its own? If it does, we have found a mechanical perpetual motion machine!  So no, it doesn't move.
What about the forces at the two ends of the hanging loop? The tension must be the same, or the hanging loop would be pulled to one side -- and the chain would start to move.
Since the tension is the same on both sides, we can cut off the hanging loop, and the rest of the chain will remain stationary, for it was already balanced.
Also see History of Mechanics of the Inclined Plane, and the many footnotes.

A: Looking at the diagram, you can see there are five "units of weight" along the diagonal, and three units along the vertical. We need to prove that these two sets of weight are in equilibrium; because, if they are, then "five units along the diagonal" is in equilibrium with "three units along the vertical", and thus if I have 1 unit along the diagonal (1/5th of the original), then I need 3/5 of a unit along the vertical.
So - why is this in equilibrium? Let's look at the chain as drawn. Should it move? If it would freely move clockwise, then I can put a very small generator on it to extract power - because as it moves, weights travel up one side as they come down the other, and this means that after it's moved one "click" (one unit of weight spacing) we have the same situation as before. Ditto if it moved anti-clockwise by itself. We conclude that the whole system is in equilibrium, or we have a perpetuum mobile. And we don't...
Would it still be in equilibrium without the bottom part? Well, the chain below the triangle is symmetrical. That means that the tension applied on the left must equal the tension on the right. And if these are the same, then removing the chain at the bottom shouldn't change the equilibrium.
And there you have it. This means that without the chain at the bottom, the thing is still in equilibrium: five along the diagonal equals three along the vertical.
Clever Stevinus.

A: because it is a 345 triangle.  If the triangle were rotated and the beads were on the 4 and 5 sides it would be the same, 4/5 of a pound, answer.  If it were a flat surface the answer would be 0/5, meaning  the beads would go nowhere.  Make sense?