text:
Q: String to enum using valueOf crashes with java.lang.IllegalArgumentException I have an enum with String defined as below
public enum MyEnumType {
    PRIMARY("primary"),
    SECONDARY("secondary");

    private final String myEnumType;

    MyEnumType(String myEnumType) {
        this.myEnumType = myEnumType;
    }

    public boolean equalsType(String myOtherEnumType) {
        return myOtherEnumType != null && myEnumType.equals(myOtherEnumType);
    }

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

When I defined my enum with a string below
MyEnumType myEnumType = MyEnumType.valueOf("primary");

It crashes
Exception in thread "main" java.lang.IllegalArgumentException: No enum constant HelloWorld.MyEnumType.primary
    at java.lang.Enum.valueOf(Enum.java:238)
    at HelloWorld$MyEnumType.valueOf(HelloWorld.java:11)
    at HelloWorld.main(HelloWorld.java:36)

Did I miss anything?

A: You can call MyEnumType.valueOf(x.toUpperCase()) to make it look up the upper case version.
e.g.
MyEnumType e = MyEnumValue.valueOf("primary".toUpperCase());

Is it possible that I have a way to provide Secondary-Style, and it get to instantiate the enum that I want, without need to manually manipulate the string?

You can provide a mapping of alternative lookups.
static final Map<String, MyEnumType> altMap = new HashMap<>();
static {
   for (MyEnumType met : MyEnumType.values()) {
        altMap.put(met.myEnumType, met);
        // add more aliases as desired.
   }
}

public static MyEnumType lookup(String str) {
    MyEnumType met = altMap.get(str);
    return met == null ? valueOf(str) : met;
}


text:
Q: WordPress gives 500 server error after changing the site url to work with Weglot translation plugin I am a new WordPress user and recently I added Weglot multilingual support to my website. I wanted to have English as my default URL so I foolishly try to change the site address URL and WordPress address URL at Settings->General to https://example.com/en, which started the problem, I was not able to access WordPress itself.
Then I changed the WordPress address URL and site address URL in the WordPress database wp_options table. Now I am able to access WordPress but my other pages or the URL generated by Weglot to support multilingual stuff like https://example.com/en/servizi/ is not loading and giving the same error as below:

Internal Server Error The server encountered an internal error or
misconfiguration and was unable to complete your request.
Please contact the server administrator at [no address given] to
inform them of the time this error occurred, and the actions you
performed just before this error.
More information about this error may be available in the server error
log.
Additionally, a 500 Internal Server Error error was encountered while
trying to use an ErrorDocument to handle the request.
Apache/2.4.41 Server at example.com Port 443

And when I checked respective pages, it shows below error for wp-asset-clean-up: CSS and javascript manager plugin.

Note: The checked URL returned an error when fetching the assets via
AJAX call. This could be because of a firewall that is blocking the
AJAX call, a redirect loop or an error in the script that is
retrieving the output which could be due to an incompatibility between
the plugin and the WordPress setup you are using.
Here is the response from the call:
Status Code Error: 500 * for more information about client and server
errors, check this link Suggestion: Select "WP Remote Post" as a
method of retrieving the assets from the "Settings" page. If that
doesn't fix the issue, just use "Manage in Front-end" option which
should always work and submit a ticket about your problem. Output:
Internal Server Error The server encountered an internal error or
misconfiguration and was unable to complete your request.
Please contact the server administrator at [no address given] to
inform them of the time this error occurred, and the actions you
performed just before this error.
More information about this error may be available in the server error
log.
Additionally, a 500 Internal Server Error error was encountered while
trying to use an ErrorDocument to handle the request.
Apache/2.4.41 Server at example.com Port 443

A: Did you flush your permalinks? Go to Wordpress admin -> Settings -> Permalinks and click save, It should flush your permalinks.
After that check your .htaccess, I had simular issue once and I had to change the .htaccess to work properly.
This seems like a problem from .htaccess...
First check If .htaccess looks like this.
# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>
# END WordPress

After that try this solution, this worked for me once when I had that issue.
DirectoryIndex index.php
RewriteEngine on
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php [L]

Then check your apache logs via ssh
sudo tail /var/log/apache2/error.log

Last thing I recommend If you have any cache plugins disable them.
Oh and all the time try to flush your permalinks.

A: 1. Set your WP urls correctly
Firstly, you haven't moved the location of the WP installation, so your Site URL shouldn't change. If you want the WP site to run from /en by default, then you only need to change your Home URL.

*

*WP_SITEURL: https://example.com/

*WP_HOME : https://example.com/en/
2. Change all the URLs in the database
WP websites store a lot of full URLs in the database, and changing the site & home URLs doesn't change the URLs in the db entries.
I assume you need to change all your urls to use /en/ for the site to work (that's specific to the plugin so I can only guess based on your question) - if so you need to find all the URLs in the database that use https://example.com/ and replace them with https://example.com/en/.
You could do this manually, but it can be tricky so my suggestion is to use a plugin such as which will find and change all the URLs. The one I use is Better Search Replace but there are others.
Make a backup first! Of course, before you do this make sure you make a backup - once you change the database, you can't just undo those changes!
I'm not familiar this plugin, so I'm not sure if there are plugin-specific changes after that - that's a question for the plugin support as its specific to that plugin and is beyond the scope of how we can help out here. But those steps should get you back up & running again anyway.
TIP - resetting your Home and Site URLs after making a mistake
If you change your Home and Site URLs and can no longer get the site to work, you can override the WP Home and Site address URLs in your wp-config.php file - just add these lines near the top:
define('WP_HOME','https://example.com/');
define('WP_SITEURL','https://example.com/');

Now you can get back into the admin and website,  to fix whatever changes you made.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WPF why is TextBox in WrapPanel is cutted XAML:
<WrapPanel>
        <TextBox  ScrollViewer.VerticalScrollBarVisibility="Auto"  AcceptsReturn="True"/>
        <TextBox  ScrollViewer.VerticalScrollBarVisibility="Auto"  AcceptsReturn="True"/>
</WrapPanel>

As you can see at the following picture, the second TextBox is cut after it wrapped, to second line.
Picture:

A: Put the WrapPanel in a ScrollViewer if you want to be able to scroll its content:
<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <ScrollViewer>
        <WrapPanel>
            <TextBox Width="400"></TextBox>
            <TextBox Height="500" ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBox>
        </WrapPanel>
    </ScrollViewer>
</Window>

The WrapPanel won't automatically adopt to the size of the window.


text:
Q: Why java 8 introduces iterable.forEach() loop even though it has for each? I'm not able to understand why java 8 has forEach loop and taking the Consumer functional interface as parameter. Even though we can do the same task using traditional for each loop without creating any extra overhead to create a class implements that from Consumer and implements a method and then pass this as reference to the forEach(). Although there is lambda expression to make it short.
Q1- why iterable.forEach()?
Q2. Where to use it?
Q3. which one is faster traditional for each of Java 8 forEach()?
Sample:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Consumer;
import java.lang.Integer;

public class ForEachExample {

    public static void main(String[] args) {

        //creating sample Collection
        List<Integer> myList = new ArrayList<Integer>();
        for(int i=0; i<10; i++) myList.add(i);

        //traversing using Iterator
        Iterator<Integer> it = myList.iterator();
        while(it.hasNext()){
            Integer i = it.next();
            System.out.println("Iterator Value::"+i);
        }

        //traversing through forEach method of Iterable with anonymous class
        myList.forEach(new Consumer<Integer>() {

            public void accept(Integer t) {
                System.out.println("forEach anonymous class Value::"+t);
            }

        });

        //traversing with Consumer interface implementation
        MyConsumer action = new MyConsumer();
        myList.forEach(action);

    }

}

//Consumer implementation that can be reused
**class MyConsumer implements Consumer<Integer>{
    public void accept(Integer t) {
        System.out.println("Consumer impl Value::"+t);
    }
}**

A: The general idea of the new APIs inspired by Functional Programming is to express what to do instead of how to do it. Even when using the simplified for-each loop,
for(Integer i: myList) System.out.println("Value::"+i);

it's just syntactic sugar for the instructions "acquire an Iterator instance and call repeatedly hasNext() and next() on it".
In contrast, when using
myList.forEach(i -> System.out.println("Value::"+i));

you provide an action, to be applied to each element, but don't specify how to do it. The default implementation will just perform the Iterator based loop, but actual Iterable implementations may override it to perform the operation differently.
Note that a lot of Iterator implementations are performing checks twice, once in hasNext(), then again in next() as there is no guaranty that the caller did hasNext() first, to throw a NoSuchElementException if there is no next element. Sometimes this even implies holding additional state within the Iterator instance to remember whether a particular "fetch-next" operation has been performed already. A dedicated forEach implementation can be straight-forward, more efficient while being simpler in code.
For example, ArrayList performs an int-index based loop without constructing an Iterator instance, Collections.emptyList() does nothing but checking the Consumer against null, TreeSet resp. its backing TreeMap traverses entry links, which is much simpler than its Iterator implementation which has to support the remove operation, and so on.
Whether a dedicated forEach implementation may compensate the Consumer construction related overhead, if there is one (mind that not every lambda expression creates a new object), is not predictable and assumptions about that should not drive the software design. More than often, the performance differences are negligible.
But there can be semantic differences too. When using one of the collections returned by Collections.synchronized…, an Iterator based loop can not provide consistency guarantees when the underlying collection is modified by another thread. The application would need to lock on the collection manually and have to care to use the right object instance, e.g. if the iterable is a subList or subSet. In contrast, the specialized forEach(Consumer) locks correctly during the entire operation, whereas the operation itself is as simple as delegating to the source's forEach method, to still perform it in the optimal way according to the actual underlying collection.

A: It just a tasty problem.
If you want something more functional, use forEach, but in your case, the traditional for-each loop is good.
In fact, there are two things for-loop supports but forEach not:

*

*flow control keywords like continue, break, return

*Checked exception

A: Q1- why iterable.forEach()?
It introduce to reduce the lines of code. Your loop can see in following as old way and new way
old way
   for (Integer t : myList) {
        System.out.println("forEach old way Value::"+t);
    }

new way
   myList.forEach(t ->System.out.println("forEach lambda way::"+t));

Q2. Where to use it?
Any where you want to iterate over the collection.
Q3. which one is faster traditional for each of Java 8 forEach()?
Older way and new way both there is no big performance difference. But if you use stream to iterate it has some latency than old for each.

A: forEach has been created to use lambda syntax :
myList.forEach(System.out::println);

or
myList.forEach(e->System.out.println(e));

This is the whole purpose of functional interface


text:
Q: cut data frame using grep in row names I have this data frame and I'm trying to create a new data frame from the first column.
> dput(test)
structure(list(r = structure(c(1, -0.242175528061635, -0.0666583192103071,
0.747898462006041, -0.273127322801604, -0.854174676122907, -0.326472398494847,
-0.242175528061635, 1, 0.610093319116511, -0.716174286974882,
0.369971592520776, 0.508225738755394, -0.696867613186299, -0.0666583192103071,
0.610093319116511, 1, -0.701926352509189, -0.38572193914295,
-0.559677556010383, -0.125875964382533, 0.747898462006041, -0.716174286974882,
-0.701926352509189, 1, 0.269630040258706, -0.614852282668006,
0.230479322245116, -0.273127322801604, 0.369971592520776, -0.38572193914295,
0.269630040258706, 1, 0.0600998872561921, 0.116913308995612,
-0.854174676122907, 0.508225738755394, -0.559677556010383, -0.614852282668006,
0.0600998872561921, 1, 0.0794305579734066, -0.326472398494847,
-0.696867613186299, -0.125875964382533, 0.230479322245116, 0.116913308995612,
0.0794305579734066, 1), .Dim = c(7L, 7L), .Dimnames = list(c("Age0",
"Age1", "Age2", "Age3", "Age4", "Age5", "Age6"), c("Age0", "Age1",
"Age2", "Age3", "Age4", "Age5", "Age6"))), n = structure(c(11L,
10L, 9L, 7L, 7L, 6L, 5L, 10L, 10L, 9L, 7L, 7L, 6L, 5L, 9L, 9L,
9L, 7L, 7L, 6L, 5L, 7L, 7L, 7L, 7L, 6L, 6L, 5L, 7L, 7L, 7L, 6L,
7L, 6L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L), .Dim = c(7L, 7L), .Dimnames = list(c("Age0", "Age1", "Age2",
"Age3", "Age4", "Age5", "Age6"), c("Age0", "Age1", "Age2", "Age3",
"Age4", "Age5", "Age6"))), P = structure(c(NA, 0.500232797835481,
0.864706601629758, 0.0532193933767151, 0.553424124702133, 0.0303470480407344,
0.591829340417803, 0.500232797835481, NA, 0.0810438517167933,
0.0702490823574873, 0.414004850479571, 0.303297069271903, 0.19097470996879,
0.864706601629758, 0.0810438517167933, NA, 0.078730337182463,
0.392783486027188, 0.248140075649853, 0.840153996654778, 0.0532193933767151,
0.0702490823574873, 0.078730337182463, NA, 0.605356039921348,
0.193941978043868, 0.709163811251702, 0.553424124702133, 0.414004850479571,
0.392783486027188, 0.605356039921348, NA, 0.909958709405365,
0.851481168303219, 0.0303470480407344, 0.303297069271903, 0.248140075649853,
0.193941978043868, 0.909958709405365, NA, 0.898972319533829,
0.591829340417803, 0.19097470996879, 0.840153996654778, 0.709163811251702,
0.851481168303219, 0.898972319533829, NA), .Dim = c(7L, 7L), .Dimnames = list(
    c("Age0", "Age1", "Age2", "Age3", "Age4", "Age5", "Age6"),
    c("Age0", "Age1", "Age2", "Age3", "Age4", "Age5", "Age6")))), class = "rcorr")

I used do.call and rbind to convert to a dataframe
test <- do.call(rbind.data.frame, test)

> dput(test)
structure(list(Age0 = c(1, -0.242175528061635, -0.0666583192103071,
0.747898462006041, -0.273127322801604, -0.854174676122907, -0.326472398494847,
11, 10, 9, 7, 7, 6, 5, NA, 0.500232797835481, 0.864706601629758,
0.0532193933767151, 0.553424124702133, 0.0303470480407344, 0.591829340417803
), Age1 = c(-0.242175528061635, 1, 0.610093319116511, -0.716174286974882,
0.369971592520776, 0.508225738755394, -0.696867613186299, 10,
10, 9, 7, 7, 6, 5, 0.500232797835481, NA, 0.0810438517167933,
0.0702490823574873, 0.414004850479571, 0.303297069271903, 0.19097470996879
), Age2 = c(-0.0666583192103071, 0.610093319116511, 1, -0.701926352509189,
-0.38572193914295, -0.559677556010383, -0.125875964382533, 9,
9, 9, 7, 7, 6, 5, 0.864706601629758, 0.0810438517167933, NA,
0.078730337182463, 0.392783486027188, 0.248140075649853, 0.840153996654778
), Age3 = c(0.747898462006041, -0.716174286974882, -0.701926352509189,
1, 0.269630040258706, -0.614852282668006, 0.230479322245116,
7, 7, 7, 7, 6, 6, 5, 0.0532193933767151, 0.0702490823574873,
0.078730337182463, NA, 0.605356039921348, 0.193941978043868,
0.709163811251702), Age4 = c(-0.273127322801604, 0.369971592520776,
-0.38572193914295, 0.269630040258706, 1, 0.0600998872561921,
0.116913308995612, 7, 7, 7, 6, 7, 6, 5, 0.553424124702133, 0.414004850479571,
0.392783486027188, 0.605356039921348, NA, 0.909958709405365,
0.851481168303219), Age5 = c(-0.854174676122907, 0.508225738755394,
-0.559677556010383, -0.614852282668006, 0.0600998872561921, 1,
0.0794305579734066, 6, 6, 6, 6, 6, 6, 5, 0.0303470480407344,
0.303297069271903, 0.248140075649853, 0.193941978043868, 0.909958709405365,
NA, 0.898972319533829), Age6 = c(-0.326472398494847, -0.696867613186299,
-0.125875964382533, 0.230479322245116, 0.116913308995612, 0.0794305579734066,
1, 5, 5, 5, 5, 5, 5, 5, 0.591829340417803, 0.19097470996879,
0.840153996654778, 0.709163811251702, 0.851481168303219, 0.898972319533829,
NA)), row.names = c("r.Age0", "r.Age1", "r.Age2", "r.Age3", "r.Age4",
"r.Age5", "r.Age6", "n.Age0", "n.Age1", "n.Age2", "n.Age3", "n.Age4",
"n.Age5", "n.Age6", "P.Age0", "P.Age1", "P.Age2", "P.Age3", "P.Age4",
"P.Age5", "P.Age6"), class = "data.frame")

I apologize for not removing the column R did not like it when i removed the others.
I'm trying to use grep to break the 1st 2 vectors (row names and column 1) into my desired columns based on the first character of the row name.
test  <- cut(test[,0],
                            breaks = c(grep("r"), grep("n"),  grep("P")),
                            labels = c("r", "n", "P"),
                            right = FALSE)

So basically my df would look like this with rounded values (another thing I clearly didn't know how to do with dput). this would use the first letter of the row name for the new column names.
         r   n     P
Age0  1.00  11    NA
Age1 -2.42  10  0.50
Age2 -0.07   9  0.86
Age3  0.75   8  0.05
Age4 -0.27   7  0.55
Age5 -0.85   6  0.03
Age6 -0.33   5  0.59

I could not find a single post about cutting or breaking by row names in r.
I'm sure some smart soul on here can accomplish this in a much cleaner way straight from the initial list, but that person is clearly not me.
Again I apologize for the long data and number of digits. Thanks.

A: Without converting the test data to a single data.frame with do.call, the desired output can be obtained with:
as.data.frame(lapply(test, function(x) x[1, ]))
#                r  n          P
# Age0  1.00000000 11         NA
# Age1 -0.24217553 10 0.50023280
# Age2 -0.06665832  9 0.86470660
# Age3  0.74789846  7 0.05321939
# Age4 -0.27312732  7 0.55342412
# Age5 -0.85417468  6 0.03034705
# Age6 -0.32647240  5 0.59182934

A: Using tidyverse on the data.frame:
library(dplyr)
library(tidyr)
test %>%
  add_rownames(var = "rowname") %>%
  separate(rowname, c("Var", "Age")) %>%
  select(Var, Age, Age0) %>%
  pivot_wider(names_from = Var, values_from = Age0)


text:
Q: Why is cgImage?.cropping rotating the image? I have written a UICropperViewController and it is working perfectly for images in landscape mode. Images in portrait mode have a huge problem. The following picture shows a simple picture with a yellow crop frame:

The cropping result is:

Now when it comes to portrait images we got this situation:

with the following result:

So what happend here? The original image got automatically rotated to the left.
I researched alot and basically found two suggestions:
Suggestion 1
Save the image orientation before cropping and restore it.
func didTapCropButton(sender: AnyObject) {
    let originalOrientation = self.imageView.image?.imageOrientation;

    // raw value of originalOrientation is `3` so its rotated to the right

    let croppedCGImage = self.imageView.image?.cgImage?.cropping(to: self.cropArea);

    // create a cropped cgImage

    let croppedImage = UIImage(cgImage: croppedCGImage!, scale: (self.imageView.image?.scale)!, orientation: (originalOrientation)!);

    // create the UIImage with the result from cgImage cropping and original orientation

    if (self.callback != nil) {
        self.callback.croppingDone(image: croppedImage);
    }

    self.dismiss(animated: true, completion: nil);
}

But the result now is:

So obviously this suggestion does not work because it is simply rotating back the already cropped image.
Suggestion 2
Orientation fixing. I found the following piece of code with the promise that it would fix the error:
func didTapCropButton(sender: AnyObject) {
    let image = self.imageView.image?.fixOrientation();
    let croppedCGImage = image?.cgImage?.cropping(to: self.cropArea);
    let croppedImage = UIImage(cgImage: croppedCGImage!);

    if (self.callback != nil) {
        self.callback.croppingDone(image: croppedImage);
    }

    self.dismiss(animated: true, completion: nil);
}

extension UIImage {

    /// Extension to fix orientation of an UIImage without EXIF
    func fixOrientation() -> UIImage {

        guard let cgImage = cgImage else { return self }

        if imageOrientation == .up { return self }

        var transform = CGAffineTransform.identity

        switch imageOrientation {

        case .down, .downMirrored:
            transform = transform.translatedBy(x: size.width, y: size.height)
            transform = transform.rotated(by: CGFloat(M_PI))

        case .left, .leftMirrored:
            transform = transform.translatedBy(x: size.width, y: 0)
            transform = transform.rotated(by: CGFloat(M_PI_2))

        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: size.height)
            transform = transform.rotated(by: CGFloat(-M_PI_2))

        case .up, .upMirrored:
            break
        }

        switch imageOrientation {

        case .upMirrored, .downMirrored:
            transform.translatedBy(x: size.width, y: 0)
            transform.scaledBy(x: -1, y: 1)

        case .leftMirrored, .rightMirrored:
            transform.translatedBy(x: size.height, y: 0)
            transform.scaledBy(x: -1, y: 1)

        case .up, .down, .left, .right:
            break
        }

        if let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {

            ctx.concatenate(transform)

            switch imageOrientation {

            case .left, .leftMirrored, .right, .rightMirrored:
                ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))

            default:
                ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
            }

            if let finalImage = ctx.makeImage() {
                return (UIImage(cgImage: finalImage))
            }
        }

        // something failed -- return original
        return self
    }
}

But this results in a wrong cropping area. The result now could be something like:

So what could be a real solution for that problem? Anyway, what's the sense of rotating the image automatically if the user does not want it? Is it possible to disable this automatic rotation?
EDIT
Complete Source of my Cropper:
import Foundation
import UIKit

protocol CropperCallback {

    func croppingDone(image: UIImage);

    func croppingCancelled();
}

class CropperViewController : UIViewController {
    @IBOutlet var imageView: UIImageView!;
    var imageViewScaleCurrent: CGFloat! = 1.0;
    var imageViewScaleMin: CGFloat! = 0.5;
    var imageViewScaleMax: CGFloat! = 5.0;
    @IBOutlet var cropAreaView: CropAreaView!;
    @IBOutlet weak var cropAreaViewConstraintWidth: NSLayoutConstraint!
    @IBOutlet weak var cropAreaViewConstraintHeight: NSLayoutConstraint!
    @IBOutlet var btnCrop: UIButton!;
    @IBOutlet var btnCancel: UIButton!;

    var callback: CropperCallback! = nil;
    var image: UIImage! = nil;
    var imageOriginalWidth: CGFloat!;
    var imageOriginalHeight: CGFloat!;
    var cropWidth: CGFloat! = 287;/
    var cropHeight: CGFloat! = 292;
    var cropHeightFix: CGFloat! = 1.0;
    var cropArea: CGRect {

        get {
            let factor = self.imageView.image!.size.width / self.view.frame.width;
            let scale = 1 / self.imageViewScaleCurrent;
            let x = (self.cropAreaView.frame.origin.x - self.imageView.frame.origin.x) * scale * factor;
            let y = (self.cropAreaView.frame.origin.y - self.imageView.frame.origin.y) * scale * factor;
            let width = self.cropAreaView.frame.size.width * scale * factor;
            let height = self.cropAreaView.frame.size.height * scale * factor;

            return CGRect(x: x, y: y, width: width, height: height);
        }
    }

    static func storyboardInstance() -> CropperViewController? {
        let storyboard = UIStoryboard(name: String(describing:  NSStringFromClass(CropperViewController.classForCoder()).components(separatedBy: ".").last!), bundle: nil);

        return storyboard.instantiateInitialViewController() as? CropperViewController;
    }

    override func viewDidLoad() {
        super.viewDidLoad();

        /*
        if (self.image.imageOrientation != .up) {
            self.image = UIImage(cgImage: self.image.cgImage!, scale: self.image.scale, orientation: UIImageOrientation(rawValue: 0)!);
        }
        */

        self.imageView.image = self.image;
        self.imageView.isUserInteractionEnabled = true;
        self.imageView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.handlePan(_:))));
        self.imageView.addGestureRecognizer(UIPinchGestureRecognizer(target: self, action: #selector(self.handlePinch(_:))));

        self.cropAreaViewConstraintWidth.constant = self.cropWidth;
        self.cropAreaViewConstraintHeight.constant = self.cropHeight;

        self.btnCrop.addTarget(self, action: #selector(self.didTapCropButton), for: UIControlEvents.touchUpInside);
        self.btnCancel.addTarget(self, action: #selector(self.didTapCancelButton), for: UIControlEvents.touchUpInside);
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews();

        let imageOriginalRect = self.getRectOfImageInImageView(imageView: self.imageView);

        self.imageOriginalWidth = imageOriginalRect.size.width;
        self.imageOriginalHeight = imageOriginalRect.size.height;

        self.createOverlay();
    }

    func createOverlay() {
        let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height));
        let pathRect = UIBezierPath(rect: CGRect(x: self.cropAreaView.frame.origin.x, y: self.cropAreaView.frame.origin.y, width: self.cropWidth, height: self.cropHeight));

        path.append(pathRect);
        path.usesEvenOddFillRule = true;

        let fillLayer = CAShapeLayer();
        fillLayer.path = path.cgPath;
        fillLayer.fillRule = kCAFillRuleEvenOdd;
        fillLayer.fillColor = UIColor.white.cgColor;
        fillLayer.opacity = 0.1;

        self.view.layer.addSublayer(fillLayer);
    }

    func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
        if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
            let rect = self.getRectOfImageInImageView(imageView: self.imageView);
            let xImage = rect.origin.x;
            let yImage = rect.origin.y;
            let widthImage = rect.size.width;
            let heightImage = rect.size.height;

            let xCropView = self.cropAreaView.frame.origin.x;
            let yCropView = self.cropAreaView.frame.origin.y;
            let widthCropView = self.cropAreaView.frame.size.width;
            let heightCropView = self.cropAreaView.frame.size.height;

            let translation = gestureRecognizer.translation(in: self.view);

            var x: CGFloat;
            var y: CGFloat;

            if (translation.x > 0) {
                if (!(xImage >= xCropView)) {
                    x = gestureRecognizer.view!.center.x + translation.x;
                } else {
                    x = gestureRecognizer.view!.center.x;
                }
            } else if (translation.x < 0) {
                if (!((xImage + widthImage) <= (xCropView + widthCropView))) {
                    x = gestureRecognizer.view!.center.x + translation.x;
                } else {
                    x = gestureRecognizer.view!.center.x;
                }
            } else {
                x = gestureRecognizer.view!.center.x;
            }

            if (translation.y > 0) {
                if (!(yImage >= (yCropView - self.cropHeightFix))) {
                    y = gestureRecognizer.view!.center.y + translation.y;
                } else {
                    y = gestureRecognizer.view!.center.y;
                }
            } else if (translation.y < 0) {
                if (!((yImage + heightImage) <= (yCropView + heightCropView + self.cropHeightFix))) {
                    y = gestureRecognizer.view!.center.y + translation.y;
                } else {
                    y = gestureRecognizer.view!.center.y;
                }
            } else {
                y = gestureRecognizer.view!.center.y;
            }

            gestureRecognizer.view!.center = CGPoint(x: x, y: y);
            gestureRecognizer.setTranslation(CGPoint.zero, in: self.view);

            self.fixImageViewPosition();
        }
    }

    func handlePinch(_ gestureRecognizer: UIPinchGestureRecognizer) {
        if let view = gestureRecognizer.view {
            let widthCropView = self.cropAreaView.frame.size.width;
            let heightCropView = self.cropAreaView.frame.size.height;

            if (((self.imageViewScaleCurrent * gestureRecognizer.scale * self.imageOriginalWidth) > widthCropView)
                && ((self.imageViewScaleCurrent * gestureRecognizer.scale * self.imageOriginalHeight) > (heightCropView + (2 * self.cropHeightFix)))
                && ((self.imageViewScaleCurrent * gestureRecognizer.scale) < self.imageViewScaleMax)) {

                self.imageViewScaleCurrent = self.imageViewScaleCurrent * gestureRecognizer.scale;

                view.transform = CGAffineTransform(scaleX: self.imageViewScaleCurrent, y: self.imageViewScaleCurrent);
            }

            gestureRecognizer.scale = 1.0;

            self.fixImageViewPosition();
        }
    }

    func fixImageViewPosition() {
        let rect = self.getRectOfImageInImageView(imageView: self.imageView);
        let xImage = rect.origin.x;
        let yImage = rect.origin.y;
        let widthImage = rect.size.width;
        let heightImage = rect.size.height;

        let xCropView = self.cropAreaView.frame.origin.x;
        let yCropView = self.cropAreaView.frame.origin.y;
        let widthCropView = self.cropAreaView.frame.size.width;
        let heightCropView = self.cropAreaView.frame.size.height;

        if (xImage > xCropView) {
            self.imageView.frame = CGRect(x: xCropView, y: self.imageView.frame.origin.y, width: widthImage, height: heightImage);
        }

        if ((xImage + widthImage) < (xCropView + widthCropView)) {
            self.imageView.frame = CGRect(x: ((xCropView + widthCropView) - widthImage), y: self.imageView.frame.origin.y, width: widthImage, height: heightImage);
        }

        if (yImage > yCropView) {
            self.imageView.frame = CGRect(x: self.imageView.frame.origin.x, y: (yCropView - self.cropHeightFix), width: widthImage, height: heightImage);
        }

        if ((yImage + heightImage) < (yCropView + heightCropView + self.cropHeightFix)) {
            self.imageView.frame = CGRect(x: self.imageView.frame.origin.x, y: ((yCropView + heightCropView + self.cropHeightFix) - heightImage), width: widthImage, height: heightImage);
        }
    }

    func getRectOfImageInImageView(imageView: UIImageView) -> CGRect {
        let imageViewSize = imageView.frame.size;
        let imageSize = imageView.image!.size;

        let scaleW = imageViewSize.width / imageSize.width;
        let scaleH = imageViewSize.height / imageSize.height;
        let aspect = min(scaleW, scaleH);

        var imageRect = CGRect(x: 0, y: 0, width: (imageSize.width * aspect), height: (imageSize.height * aspect));

        imageRect.origin.x = (imageViewSize.width - imageRect.size.width) / 2;
        imageRect.origin.y = (imageViewSize.height - imageRect.size.height) / 2;

        imageRect.origin.x += imageView.frame.origin.x;
        imageRect.origin.y += imageView.frame.origin.y;

        return imageRect;
    }

    func getCGImageWithCorrectOrientation(_ image : UIImage) -> CGImage {
        if (image.imageOrientation == UIImageOrientation.up) {
            return image.cgImage!;
        }

        var transform : CGAffineTransform = CGAffineTransform.identity;

        switch (image.imageOrientation) {
        case UIImageOrientation.right, UIImageOrientation.rightMirrored:
            transform = transform.translatedBy(x: 0, y: image.size.height);
            transform = transform.rotated(by: CGFloat(-1.0 * M_PI_2));
            break;
        case UIImageOrientation.left, UIImageOrientation.leftMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0);
            transform = transform.rotated(by: CGFloat(M_PI_2));
            break;
        case UIImageOrientation.down, UIImageOrientation.downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: image.size.height);
            transform = transform.rotated(by: CGFloat(M_PI));
            break;
        default:
            break;
        }

        switch (image.imageOrientation) {
        case UIImageOrientation.rightMirrored, UIImageOrientation.leftMirrored:
            transform = transform.translatedBy(x: image.size.height, y: 0);
            transform = transform.scaledBy(x: -1, y: 1);
            break;
        case UIImageOrientation.downMirrored, UIImageOrientation.upMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0);
            transform = transform.scaledBy(x: -1, y: 1);
            break;
        default:
            break;
        }

        let contextWidth : Int;
        let contextHeight : Int;

        switch (image.imageOrientation) {
        case UIImageOrientation.left, UIImageOrientation.leftMirrored,
             UIImageOrientation.right, UIImageOrientation.rightMirrored:
            contextWidth = (image.cgImage?.height)!;
            contextHeight = (image.cgImage?.width)!;
            break;
        default:
            contextWidth = (image.cgImage?.width)!;
            contextHeight = (image.cgImage?.height)!;
            break;
        }

        let context : CGContext = CGContext(data: nil, width: contextWidth, height: contextHeight,
                                            bitsPerComponent: image.cgImage!.bitsPerComponent,
                                            bytesPerRow: image.cgImage!.bytesPerRow,
                                            space: image.cgImage!.colorSpace!,
                                            bitmapInfo: image.cgImage!.bitmapInfo.rawValue)!;

        context.concatenate(transform);
        context.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: CGFloat(contextWidth), height: CGFloat(contextHeight)));

        let cgImage = context.makeImage();

        return cgImage!;
    }

    func didTapCropButton(sender: AnyObject) {
        let fixedImage = self.getCGImageWithCorrectOrientation(self.imageView.image!);

        // let image = self.imageView.image?.fixOrientation();

        let croppedCGImage = fixedImage.cropping(to: self.cropArea);
        let croppedImage = UIImage(cgImage: croppedCGImage!);

        if (self.callback != nil) {
            self.callback.croppingDone(image: croppedImage);
        }

        self.dismiss(animated: true, completion: nil);
    }

    func didTapCancelButton(sender: AnyObject) {
        if (self.callback != nil) {
            self.callback.croppingCancelled();
        }

        self.dismiss(animated: true, completion: nil);
    }
}

extension UIImageView {

    func imageFrame() -> CGRect {
        let imageViewSize = self.frame.size;

        guard let imageSize = self.image?.size else {
            return CGRect.zero;
        }

        let imageRatio = imageSize.width / imageSize.height;
        let imageViewRatio = imageViewSize.width / imageViewSize.height;

        if (imageRatio < imageViewRatio) {
            let scaleFactor = imageViewSize.height / imageSize.height;
            let width = imageSize.width * scaleFactor;
            let topLeftX = (imageViewSize.width - width) * 0.5;

            return CGRect(x: topLeftX, y: 0, width: width, height: imageViewSize.height);
        } else {
            let scaleFactor = imageViewSize.width / imageSize.width;
            let height = imageSize.height * scaleFactor;
            let topLeftY = (imageViewSize.height - height) * 0.5;

            return CGRect(x: 0, y: topLeftY, width: imageViewSize.width, height: height);
        }
    }
}

extension UIImage {

    // Extension to fix orientation of an UIImage without EXIF

    func fixOrientation() -> UIImage {
        guard let cgImage = self.cgImage else {
            return self;
        }

        if self.imageOrientation == .up {
            return self;
        }

        var transform = CGAffineTransform.identity;

        switch self.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: self.size.width, y: self.size.height);
            transform = transform.rotated(by: CGFloat(M_PI));
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: self.size.width, y: 0);
            transform = transform.rotated(by: CGFloat(M_PI_2));
        case .right, .rightMirrored:
            transform = transform.translatedBy(x: 0, y: self.size.height);
            transform = transform.rotated(by: CGFloat(-M_PI_2));
        case .up, .upMirrored:
            break;
        }

        switch self.imageOrientation {
        case .upMirrored, .downMirrored:
            transform.translatedBy(x: self.size.width, y: 0);
            transform.scaledBy(x: -1, y: 1);
        case .leftMirrored, .rightMirrored:
            transform.translatedBy(x: self.size.height, y: 0);
            transform.scaledBy(x: -1, y: 1);
        case .up, .down, .left, .right:
            break;
        }

        if let ctx = CGContext(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {
            ctx.concatenate(transform);

            switch self.imageOrientation {
            case .left, .leftMirrored, .right, .rightMirrored:
                ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: self.size.height, height: self.size.width));
            default:
                ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height));
            }

            if let finalImage = ctx.makeImage() {
                return (UIImage(cgImage: finalImage));
            }
        }

        // something failed -- return original
        return self;
    }
}

A: You have to understand the scale and orientation properties.
Your suggestion 1 (use the orientation of the original image) is obviously a correct suggestion and it would work, if you were able to also rotate and scale your cropArea.
Your suggestion 2 is a good to handle rotation but you still have to scale the cropArea. Currently you are not handling the scale at all.
(minor note, rotating cropArea would probably have better performance than rotating the whole image, see https://stackoverflow.com/a/14712184/669586).
You have to:

*

*Scale (multiply) cropArea by the scale of the image.

*Use the original image scale when creating the result

For example, if your UIImage has size 200x100 and it has scale 2x (it's a retina image), your cgImage will have size 400x200 but you are still working with a crop area inside 200x100!
Something along the lines of:
func didTapCropButton(sender: AnyObject) {
    guard let image = self.imageView.image else {
        return
    }

    let cgImage = self.getCGImageWithCorrectOrientation(image);

    let scaledCropArea = CGRect(
        x: self.cropArea.x * image.scale,
        y: self.cropArea.y * image.scale,
        width: self.cropArea.width * image.scale,
        height: self.cropArea.height * image.scale
    )

    let croppedCGImage = cgImage.cropping(to: scaledCropArea)
    let croppedImage = UIImage(cgImage: croppedCGImage!, scale: image.scale, orientation: .up)

    if (self.callback != nil) {
        self.callback.croppingDone(image: croppedImage)
    }

    self.dismiss(animated: true, completion: nil)
}

The automatic rotation and transforms in UIImage are simply an optimization. Thanks to this optimization, multiple images can share the same storage (the same memory data). The optimization is done already in your asset loader and you cannot disable it.
Also, please see https://stackoverflow.com/a/18602671/669586 for a simpler and safer implementation.


text:
Q: OffsetDateTime - print offset instead of Z I have this code:
String date = "2019-04-22T00:00:00+02:00";

OffsetDateTime odt = OffsetDateTime
      .parse(date, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
      .withOffsetSameInstant(ZoneOffset.of("+00:00"));

System.out.println(odt);

This print: 2019-04-21T22:00Z
How can I print 2019-04-21T22:00+00:00? With offset instead of Z.

A: None of the static DateTimeFormatters do this in the standard library.
They either default to Z or GMT.
To achieve +00:00 for no offset, you will have to build your own DateTimeFormatter.
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));

DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
        .append(ISO_LOCAL_DATE_TIME) // use the existing formatter for date time
        .appendOffset("+HH:MM", "+00:00") // set 'noOffsetText' to desired '+00:00'
        .toFormatter();

System.out.println(now.format(dateTimeFormatter)); // 2019-12-20T17:58:06.847274+00:00

A: My version would be:
    DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssxxx");

    String date = "2019-04-22T00:00:00+02:00";

    OffsetDateTime odt = OffsetDateTime
          .parse(date)
          .withOffsetSameInstant(ZoneOffset.UTC);

    System.out.println(odt.format(outputFormatter));

Output is the desired:

2019-04-21T22:00:00+00:00

When toString() gives output in an unwanted format, the answer is using a DateTimeFormatter for formatting into the desired format. Lowercase xxx in the format pattern string produces offset formatted in hours and minutes with a colon as shown, also when the offset is 0.
While OffsetDateTime.toString() doesn't produce the format that you wanted, OffsetDateTime is still able to parse it without any explicit formatter. So in my version of the code I left it out.
There is a constant already declared for ZoneOffset.of("+00:00"), which I prefer to use: ZoneOffset.UTC.


text:
Q: SCNNode Bounding size and Scaling I am trying to get the size of a node on screen. This is the code:
var v1 = SCNVector3(x:0, y:0, z:0)
var v2 = SCNVector3(x:0, y:0, z:0)
carNode.getBoundingBoxMin(&v1, max: &v2)
print(v2)

carNode.scale = SCNVector3(0.9, 1.2, 0.5)
//carNode.transform = SCNMatrix4MakeScale(0.9, 1.2, 0.5)

carNode.getBoundingBoxMin(&v1, max: &v2)
print(v2)

However the values returned by getBoundingBoxMin before and after are identical, as if the scaling had not been taken in consideration. Why is that? I need this information to set the correct size for the physics body on the node for collision detection and the determine if other nodes are within some range from the object.

A: Per SCNBoundingVolume Protocol Reference:

The SCNBoundingVolume protocol's ... methods measure the location and size of an object in the object's local coordinate space, expressed as either a box or a sphere.

Scaling a node doesn't change its local coordinate space. So you're getting a correct result.
You might not need to do anything, though. Note under SCNPhysicsShapeScaleKey documentation (under SCNPhysicsShape class reference:

SceneKit's physics simulation ignores the scale property of nodes containing physics bodies when simulating collisions. Instead, use this option to provide a scale factor when creating custom physics shapes. (If you create a physics body for a node without specifying a custom shape, SceneKit uses the node's scale property to infer this scale factor at creation time.)

So if your scale factor isn't automatically applied, it appears (I haven't tested it) that passing your scale vector to SCNPhysicsShape.init(node:options:), using the options key SCNPhysicsShapeScaleKey, will do what you want.


text:
Q: The specified framework 'Microsoft.AspNetCore.App', version '2.2.5' was not found After upgrading targetFramework for my web app from netcoreapp2.1 to netcoreapp2.2 my web app works great on local machine but when published to Azure WebApp environment fails to start with the following error:
HTTP Error 502.5 - ANCM Out-Of-Process Startup Failure
Common causes of this issue:
The application process failed to start
The application process started but then stopped
The application process started but failed to listen on the configured port
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=808681

And if I go to Azure console and try to run the app manually with dotnet xxx.dll I get the following error:

My reference to Microsoft.AspNetCore.App is added without the version as recommended by the warning:
    <PackageReference Include="Microsoft.AspNetCore.App" />

I've found the similar issue here for previous version update but with no help to me:
https://github.com/aspnet/AspNetCore.Docs/issues/8794
How can I troubleshoot this issue?

A: Looking at the error it seems that ASP.NET Core 2.2.5 is not yet installed on the Azure web app instances. You'll either have to wait or explicitly specify the runtime version you want to use instead of the SDK picking the latest version:
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.4" />

After you've updated the project file you have to re-publish your application.


text:
Q: decode in PHP a simple text from database I have a simple text into my database with a string like this:
"Online il nuovo sito web di QINT'X: rinnovato nella grafica presenta una struttura più lineare e facilmente fruibile rispetto al precedente, a tutto vantaggio della navigazione"
I have make a query in PHP to retrieve data but when I take the string doesn't decode the character'ù'. Why?
This is my code (I have hidden the part of query because the problem I think is in the utf8_decode):
echo''.utf8_decode(htmlentities(substr($news['descrizione_it'],0,200))).'
';

A: You should set encoding when you connect the DB.
SET NAMES 'utf8'


text:
Q: Spring MySQL : Error creating bean with name 'org.springframework.security.filterChains' I am creating a MySQL connection , but I have a problem with applicationContextMySQL and web.xml.
I have this content in web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>Archetype Created Web Application</display-name>
    <servlet>
        <!-- Automáticamente inicializa el contexto spring con el formato servlet-name=nombre-servlet.xml -->
        <servlet-name>prueba</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--
        La alternativa de inicialización de spring MVC es mediante un init-param como se describe
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/prueba-servlet.xml</param-value>
        </init-param>-->
    </servlet>

    <servlet-mapping>
        <servlet-name>prueba</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContextMySQL.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>
<!-- Spring security filtro -->
<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

In the applicationContextMySQL.xml , I have this content.
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd">
    <http auto-config="true" use-expressions="true">
        <intercept-url pattern="/inicio.do" access="hasRole('ROLE_ADMIN')" />
    </http>
    <authentication-manager>
        <authentication-provider>
            <jdbc-user-service data-source-ref="myDataSource" />
        </authentication-provider>
    </authentication-manager>
    <beans:bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <beans:property name="url"
            value="jdbc:mysql://localhost:3306/m12spring" />
        <beans:property name="username" value="root" />
        <beans:property name="password" value="" />
    </beans:bean>
</beans:beans>

The exactly error in the code.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.filterChains': Cannot resolve reference to bean 'org.springframework.security.web.DefaultSecurityFilterChain#0' while setting bean property 'sourceList' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.DefaultSecurityFilterChain#0': Cannot resolve reference to bean 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0' while setting constructor argument with key [5]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0': Cannot resolve reference to bean 'org.springframework.security.authentication.ProviderManager#0' while setting bean property 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.ProviderManager#0': Cannot resolve reference to bean 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.authentication.AuthenticationManagerFactoryBean#0': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager': Cannot resolve reference to bean 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0' while setting constructor argument with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authentication.dao.DaoAuthenticationProvider#0': Cannot resolve reference to bean 'org.springframework.security.provisioning.JdbcUserDetailsManager#0' while setting bean property 'userDetailsService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.provisioning.JdbcUserDetailsManager#0': Cannot resolve reference to bean 'myDataSource' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.apache.commons.dbcp.BasicDataSource] for bean with name 'myDataSource' defined in ServletContext resource [/WEB-INF/applicationContextMySQL.xml]; nested exception is java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveManagedList(BeanDefinitionValueResolver.java:382)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:157)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1481)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:725)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:326)
    at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:196)
    at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
    at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
    at weblogic.servlet.internal.EventsManager.executeContextListener(EventsManager.java:251)
    at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:204)
    at weblogic.servlet.internal.EventsManager.notifyContextCreatedEvent(EventsManager.java:189)
    at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1910)
    at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3063)
    at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1830)
    at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:875)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
    at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:237)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:232)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:82)
    at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:52)
    at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:753)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:263)
    at weblogic.application.internal.EarDeployment.activate(EarDeployment.java:67)
    at weblogic.application.internal.DeploymentStateChecker.activate(DeploymentStateChecker.java:165)
    at weblogic.deploy.internal.targetserver.AppContainerInvoker.activate(AppContainerInvoker.java:80)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.activate(AbstractOperation.java:601)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.activateDeployment(ActivateOperation.java:171)
    at weblogic.deploy.internal.targetserver.operations.ActivateOperation.doCommit(ActivateOperation.java:121)
    at weblogic.deploy.internal.targetserver.operations.StartOperation.doCommit(StartOperation.java:151)
    at weblogic.deploy.internal.targetserver.operations.AbstractOperation.commit(AbstractOperation.java:343)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleDeploymentCommit(DeploymentManager.java:895)
    at weblogic.deploy.internal.targetserver.DeploymentManager.activateDeploymentList(DeploymentManager.java:1422)
    at weblogic.deploy.internal.targetserver.DeploymentManager.handleCommit(DeploymentManager.java:454)
    at weblogic.deploy.internal.targetserver.DeploymentServiceDispatcher.commit(DeploymentServiceDispatcher.java:181)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.doCommitCallback(DeploymentReceiverCallbackDeliverer.java:195)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer.access$100(DeploymentReceiverCallbackDeliverer.java:13)
    at weblogic.deploy.service.internal.targetserver.DeploymentReceiverCallbackDeliverer$2.run(DeploymentReceiverCallbackDeliverer.java:68)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:643)
    at weblogic.invocation.ComponentInvocationContextManager._runAs(ComponentInvocationContextManager.java:348)
    at weblogic.invocation.ComponentInvocationContextManager.runAs(ComponentInvocationContextManager.java:333)
    at weblogic.work.LivePartitionUtility.doRunWorkUnderContext(LivePartitionUtility.java:54)
    at weblogic.work.PartitionUtility.runWorkUnderContext(PartitionUtility.java:41)
    at weblogic.work.SelfTuningWorkManagerImpl.runWorkUnderContext(SelfTuningWorkManagerImpl.java:617)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:397)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:346)

A: You can see in your log :  Cannot find class [org.apache.commons.dbcp.BasicDataSource]
Are your sure that you have import the class with adding commons-dbcp dependency ?
If it's not the case, just add this in your pom.xml:
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>


text:
Q: What should happen to when user changes username in Oauth2 Am pretty new to Oauth2 and I wondering what should happen in a scenario where a user changes the username used to authorize a client.
Should all access tokens expire after change is successful requesting the client to a new access code?
or
The access tokens are to be updated with the new username by the authentication server?

A: In normal cases, username of a user and the unique ID of the user are different. If an access token is associated with the unique ID (not with username), you don't have to invalidate or update access tokens even if username is changed.
Otherwise, if you associate access tokens with username (not with the unique ID), when username is changed, you should invalidate access tokens or update access tokens with the new username.

A: The OAuth spec doesn't specify what should happen -- one the user passes authentication and gets a token, they have an active authorization "session" as long as that token is valid.
You can invalidate tokens, and authorization sessions, as you like, though. So as a matter of policy, if you want to invalidate their tokens when there's a change to the account, then you are free to do that.
Just remember to invalidate both access tokens and refresh tokens for the user, or else they might just use their refresh token to start over with a access token.


text:
Q: Make sure input Double has certain format I would like to check if a certain Double input is of the form: "the number has maximum one decimal". So what would be ok is, for example,
100 //this is ok
100.3 //this is ok
100.3 //this is ok
1.333 //this is not ok
10.333 //this is not ok

I tried using a regex, but somehow it doesn't work. Is there any easier solution I could use?
I've used this code
func validate(input: Double) -> Bool {
    let regex = "^[1-9]*((\\.|,)[0-9]{1})?$"

    let inputTest = NSPredicate(format: "SELF MATCHES %@", regex)
    return inputTest.evaluate(with: String(input))
}

A: Using a regular expression is the wrong approach since it doesn't really deal well with locale specific issues.
A better approach would be to convert the string into a number using NumberFormatter. Then convert the number back into a string using another NumberFormatter setup with your specific requirements (such as at most one decimal digit). Then see if the original and the newly formatter strings match or not.
If they match, the user entered a valid number in their given locale meeting your desired requirements.

A: try this regex:
^\d+([.,](?!\d{3,})\d+)?$
in english: start of string, followed by one or more numbers, followed optionally by a decimal and more numbers, if 3 or more digits do not follow the decimal (the negative lookahead part)
demo


text:
Q: How do I force call of labels autoposition algorithm? I'm trying to use JSXGraph 1.00.0 for drawing a sketch (just points and lines). All the point labels are created with "autoPosition: true". Automatic positioning works fine after first user action (a point moving, or an element deletion). But before the first action, the autoposition algorithm does not run. How do I force run it?

A: Just call board.update(). The autoposition algorithm is still considered experimental. If you have a small example which does not work as expected, please open an an issue at github and post the code.


text:
Q: VLC player won't open I tried to get vlc 2.2, so that I could run vlsub. In terminal, I entered sudo add-apt-repository ppa:videolan/master-daily followed by sudo apt-get update and then sudo apt-get install vlc.
VLC appears in my dock and in applications, but it cannot open now.
What is the problem? Did I add updates from the repository that I shouldn't have? How can I close it and revert back to my older version of VLC?

A: Yay, I fixed it on my own! I just removed the repository I added above and updated with the commands: sudo rm /etc/apt/sources.list.d/videolan-* && sudo apt-get update .


text:
Q: quote_from_bytes() expected bytes error when data is in bytes format when uploading to blob storage in Python3 Can someone tell me what I am doing wrong with trying to upload an image to blob storage? Below is my code.
print(type(img['image'])) #Output is <class 'bytes'>

connection_string = get_blob_connection_string()
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_client = blob_service_client.get_blob_client(container="images", blob=img['id'])

exists = blob_client.exists()
if (exists == False):
    result = blob_client.upload_blob(img['image'], blob_type="blockblob")
    print(result)

When inserting the blob, it throws the error

quote_from_bytes() expected bytes

This error makes no sense, I gave it bytes. What am I missing?

A: After reproducing from my end, I have received the same issue. You are receiving this error because of incompatible type of the file (i.e., file format).

After changing the below line to the correct format I could able to achieve your requirement.
blob_client = blob_service_client.get_blob_client(container="images", blob=img['id'])

Below is the correct format
blob_client=blob_service_client.get_blob_client(container='container', blob='<LOCAL FILE PATH>');

Below is the complete code that worked for me
from  azure.storage.blob  import  BlobServiceClient
from  PIL  import  Image

connection_string = "<CONNECTION STRING>"
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
blob_client=blob_service_client.get_blob_client(container='container', blob='<LOCALPATH>');

with  open(file='<PATH IN YOUR STORAGE ACCOUNT WITH FILE NAME>', mode="rb") as  data:

blob_client.upload_blob(data)

RESULTS:


text:
Q: Wait the end of subprocesses with multiple parallel jobs I'm running some subprocesses from python in parallel. I want to wait until every subprocess have finished. I'm doing a non elegant solution:
runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
  args = ["root", "-l", "-q", script]
  p = subprocess.Popen(args)
  ps.append(p)
while True:
  ps_status = [p.poll() for p in ps]
  if all([x is not None for x in ps_status]):
    break

is there a class that can handle multiple subprocess? The problem is that the wait method block my program.
update: I want to show the progress during the computation: something like "4/7 subprocess finished..."
If you are curious root compile the c++ script and execute it.

A: How about

import os, subprocess
runcodes = ["script1.C", "script2.C"]
ps = {}
for script in runcodes:
    args = ["root", "-l", "-q", script]
    p = subprocess.Popen(args)
    ps[p.pid] = p
print "Waiting for %d processes..." % len(ps)
while ps:
    pid, status = os.wait()
    if pid in ps:
        del ps[pid]
        print "Waiting for %d processes..." % len(ps)

A: You could do something like this:
runcodes = ["script1.C", "script2.C"]

ps = []
for script in runcodes:
    args = ["root", "-l", "-q", script]
    p = subprocess.Popen(args)
    ps.append(p)

for p in ps:
    p.wait()

The processes will run in parallel, and you'll wait for all of them at the end.

A: If your platform is not Windows, you could probably select against the stdout pipes of your subprocesses.  Your app will then block until either:

*

*One of the registered file descriptors has an I/O event (in this case, we're interested in a hangup on the subprocess's stdout pipe)

*The poll times out

Non-fleshed-out example using epoll with Linux 2.6.xx:
import subprocess
import select

poller = select.epoll()
subprocs = {} #map stdout pipe's file descriptor to the Popen object

#spawn some processes
for i in xrange(5):
    subproc = subprocess.Popen(["mylongrunningproc"], stdout=subprocess.PIPE)
    subprocs[subproc.stdout.fileno()] = subproc
    poller.register(subproc.stdout, select.EPOLLHUP)

#loop that polls until completion
while True:
    for fd, flags in poller.poll(timeout=1): #never more than a second without a UI update
        done_proc = subprocs[fd]
        poller.unregister(fd)
        print "this proc is done! blah blah blah"
        ...  #do whatever
    #print a reassuring spinning progress widget
    ...
    #don't forget to break when all are done

A: This answer is related to this answer and uses a similar mechanism underneath (based on the select syscall) called asyncio.
You can read more about asyncio here.
Asyncio is good when your process is IO-bound. Your process seems to be IO-bound, at least in this section of your program, spending most of its time waiting for the external scripts to complete and only printing a message at their end.
The following code should work for you (with some minor adjustments perhaps):
import asyncio

# The scripts you want to run concurrently
runcodes = ["script1.C", "script2.C"]

# An awaitable coroutine that calls your script
# and waits (non-blocking) until the script is done
# to print a message
async def run_script(script):
    # You will need to adjust the arguments of create_subprocess_exec here
    # according to your needs
    p = await asyncio.create_subprocess_exec(script)
    await p.wait()
    print("Script", script, "is done")

# You create concurrent tasks for each script
# they will start in parallel as soon as they are
# created
async def main():
    tasks = []
    for script in runcodes:
        tasks.append(asyncio.create_task(run_script(script)))

    # You wait until all the tasks are done before
    # continuing your program
    for task in tasks:
        await task

if __name__ == "__main__":
    asyncio.run(main())

Some detailed explanation.
Asyncio allows you to execute concurrent tasks with a single thread by alternating the various asynchronous tasks and simply waiting when all of them are blocked.
The function run_script is asynchronous and will call your script using a similar mechanism to subprocess.Popen. The difference here is that the returning object is awaitable meaning that you can jump to something else while the wait function is blocked.
You can read more about subprocess management with asyncio here. You will notice the management of the subprocess is very similar to the "normal" Python subprocessing. The arguments of the Popen are also similar.
Notice that this is different to threading. In fact, this program is single-threaded. Do not confuse asyncio with multi-threading. They are two different approaches to run tasks concurrently (with pros and cons).
The main function will create multiple tasks, one for each script you want to run and wait on them.
The important thing is that this await will not be blocking and at the same time it will not do live-polling. It will sleep until any of the tasks will be ready. Once a task is ready the execution returns to that task that can print a statement about your message.
The program will not exit the main function until all awaited tasks are done, though. It will stay within the loop of awaited functions generated by asyncio.run until everything is completed.

A: I think the answer is not in python code or language features but it is in the system capabilities , consider this solution   :
runcodes = ["script1.C", "script2.C"]

Args = []
for script in runcodes:
    Args += " ".join(["root", "-l", "-q", script])

P = subprocess.Popen(" & ".join(Args))
P.wait()


text:
Q: Which is preferable controller or link function in AngularJS directives? Angular docs said:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Why should we use link functions if we don't have any APIs to expose from the directive and if there is no data to share between the directives?


text:
Q: Not able to get response code for 401 with http url connection Hi in my android application I am using HttpUrlconnection for web services. So for any web resource request with response 401 it's not giving any header fields or response code.And it showing content length -1.It Fires exception java.io.IOException: Received authentication challenge is null. Now my problem is that how to check response code for such conditions. Need Help. I check those request in rest clients and there I found that my response coming properly with header response code with 401 and other fields also
My request looks like
String urlString ="http://WWW.ABC.com";
URL url = new URL(urlString);
login_urlConnection = (HttpURLConnection) url.openConnection();
login_urlConnection.setRequestMethod("GET");
int statusCode = login_urlConnection.getResponseCode() // Here I am getting exception I want this status code to check authentication failure

How to solve this problem. Need Help. Thank you.
I did same call with HttpClient and then I am able to get response code then why not with HttpUrlConnection. Am I doing something wrong Need Help.

A:    URL url = new URL("http://www.android.com/");
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   try {
     InputStream in = new BufferedInputStream(urlConnection.getInputStream());
     read(in);
    finally {
     urlConnection.disconnect();
   }

for reading use this block:
int i;
      char c;

      try{
         // new input stream created
         is = new FileInputStream("C://test.txt");

         System.out.println("Characters printed:");

         // reads till the end of the stream
         while((i=is.read())!=-1)
         {
            // converts integer to character
            c=(char)i;

            // prints character
            System.out.print(c);
         }
      }catch(Exception e){

         // if any I/O error occurs
         e.printStackTrace();
      }finally{

         // releases system resources associated with this stream
         if(is!=null)
            is.close();
      }

A: urlString should be changed into "http://WWW.ABC.com". Url Scheme (like http:// or ftp://, and so on) is needed.
Also, you need to make connection to the server.
login_urlConnection.setRequestMethod("GET");
try {
    login_urlConnection.connect();
} catch (IOException e) {
    e.printstackTrace();
}
int statusCode = login_urlConnection.getResponseCode()


text:
Q: How to only select child entities of an entity in entity framework? I'd like to select only child below CFO and its subchild entities in an Entity Framework select statement.
Here's my table:
+-------+------------+----------+
| OrgId | Name       | ParentId |
+-------+------------+----------+
| 1     | COO        |          |
+-------+------------+----------+
| 2     | CFO        |          |
+-------+------------+----------+
| 3     | Accountant | 2        |
+-------+------------+----------+
| 4     | Bookkeeper | 3        |
+-------+------------+----------+
| 5     | Controller | 2        |
+-------+------------+----------+
| 6     | Operations | 1        |
+-------+------------+----------+

I'd like to select only this:
+-------+------------+----------+
| OrgId | Name       | ParentId |
+-------+------------+----------+
| 3     | Accountant | 2        |
+-------+------------+----------+
| 4     | Bookkeeper | 3        |
+-------+------------+----------+
| 5     | Controller | 2        |
+-------+------------+----------+

The entity framework select:
public virtual IList<OrgStructureModel> GetAll()
{
    using (var db = _context)
    {
        var result = _session.GetObjectFromJson<IList<OrgStructureModel>>("OrgStructure");

        if (result == null)
        {
            result = db.OrgStructures
                .Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
                .ToList();

            _session.SetObjectAsJson("OrgStructure", result);
        }

        return result;
    }
}

How can this be achieved in EF?
Here's what I've tried
I've tried testing to just show child with any parent .Where(e => e.ParentId != null):
            result = db.OrgStructures
                .Select(org => org.ToOrgStructureModel(db.OrgStructures.Where(s => s.ParentId == org.OrgId).Count() > 0))
                .Where(e => e.ParentId != null)
                .ToList();

But this returned 0 results
Definition of ToOrgStructureModel:
public static OrgStructureModel ToOrgStructureModel(this OrgStructure org, bool hasChildren)
{
    return new OrgStructureModel
    {
        OrgId = org.OrgId,
        ParentId = org.ParentId,
        Name = org.Name
        hasChildren = hasChildren
    };
}

Update:
It looks like something's wrong with the Telerik TreeList Control where the above query has data, but the control won't output the data. But the question remains, how do I get OrgId: 3,4,5 with LINQ?

A: Only bring back the results where the ParentId is not null.


text:
Q: installation issue with matplotlib The following happens whenever I try to install matplotlib
vijay@vijay-Inspiron-1545:~$ python -mpip install matplotlib
Collecting matplotlib
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 353, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 278, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "/usr/lib/python2.7/dist-packages/pip/index.py", line 792, in get_page
    "Cache-Control": "max-age=600",
  File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 501, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/download.py", line 386, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 488, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/sessions.py", line 609, in send
    r = adapter.send(request, **kwargs)
  File "/usr/share/python-wheels/CacheControl-0.11.7-py2.py3-none-any.whl/cachecontrol/adapter.py", line 47, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
  File "/usr/share/python-wheels/requests-2.12.4-py2.py3-none-any.whl/requests/adapters.py", line 423, in send
    timeout=timeout
  File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 643, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 315, in increment
    total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

A: matplotlib is packaged.
You can install it with
sudo apt-get install python-matplotlib python3-matplotlib


text:
Q: ViewModel binds not updating UI my issue is I don't update the user interface (TextBlock).
In summary:
by executing a method under translation (ImportData, which performs a series of Inserts in an MS SQL DB) the textblock should contain the time as the Insert proceeds in the ImportData method.
For this purpose I have created a Timer that is started before the transaction
This is the code involved.
  <TextBlock Text="{Binding NumRig}" />

I have also used this statement but without success
  <TextBlock Text="{Binding NumRig, UpdateSourceTrigger=PropertyChanged}" />

The property
private string _NumRig;
public string NumRig
{
    get { return _NumRig; }
    set
    {
        _NumRig= value;
        base.OnPropertyChanged("NumRig");
    }
}

The declaration of the Timer and the transaction that calls ImportData
  {
    Timer t = new Timer(TimerCallback, null, 0, 500);
     using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new System.TimeSpan(0, 10, 0)))
     {
          importResult = ImportData();
              if (importResult)
                  ts.Complete();
     }
    t.Dispose();
 }

and now the TimerCallback procedure
1st version of the procedure performed by the Timer (and which does not work)
 void TimerCallback(object sender, EventArgs e)
 {
    NumRig= DateTime.Now.ToString("HH:mm:ss");
 }

2nd version of the procedure performed by the Timer (and which does not work)
     void TimerCallback(object sender, EventArgs e)
 {
        Application.Current.Dispatcher.Invoke(() =>
        {
            NumRig= DateTime.Now.ToString("HH:mm:ss");
        });
 }

3rd version of the procedure performed by the Timer (and which does not work)
     void TimerCallback(object sender, EventArgs e)
 {
        Application.Current.Dispatcher.Invoke(() =>
        {
            NumRig= DateTime.Now.ToString("HH:mm:ss");
            ONpropertyChanged("NumRig");
        });
 }

I'm wondering, why does the TextBlock never update?
What am I doing wrong ??
Thanks to who will answer me
Bye


text:
Q: Why angular app dist build needs to be served on web server? why we need a web server for the angular build?

*

*Why I cannot directly run dist/index.html?

*If my angular build has all the bundled js files hosted and someone copies page source then why it does not run?
I referenced: SO question and Github discussion to understand this process.
But could not find out the reason behind why the angular app cannot be accessed through file://.
It would be great if someone can spare some time to explain this conceptual issue.
Thanks!


text:
Q: How to catch text into input textbox value jquery In below code i have appended list of groups, if i clicked on any group, a model box will be opened. i need to edit list of values from textbox.. in my code if i clicked on any group.. the data is showing same in modal box.. but i need to show data in modal box in input textboxes..
DEMO

$(document).ready(function() {
  var $appendItemsToList;
  $("#btn2").click(function() {
    var text = $('#newCheckText').val();
    $("#oo", $appendItemsToList).append('<input type="checkbox" /> ' + text + '
');
    $("#ol").append("<input type='text' value=" + text + ">
");
  });

  $("#add_list").on('click', function() {
    $("#list_group").append("

List (//click)

<input type='checkbox' />List item 1
<input type='checkbox' />List item 2
<input type='checkbox' />List item 3

");
  });

  $("#dialog").dialog({
    autoOpen: false,
  });

  $(document).on('click', '.opener', function() {
    $appendItemsToList = $(this);
    $("#dialog").dialog("open");
    $("#ol").html($('#oo', $appendItemsToList).html());
  });
});

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

<button id="add_list">add list</button>

List items

    <input value="List item 1">

    <input value="List item 2">

    <input value="List item 3">

  <input type="text" id="newCheckText" value="enter" />
  <button id="btn2">Add</button>

List (//click)

      <input type="checkbox" />List item 1

      <input type="checkbox" />List item 2

      <input type="checkbox" />List item 3

A: Change the Opener click event code to below
  $(document).on('click', '.opener', function() {

    $appendItemsToList = $(this);
    $("#ol").empty();
    $appendItemsToList.find('input[type="checkbox"]').each( function(i){

        var value = "List Item "+ i;
        $("#ol").append('<input type="text" value="'+value+'" />');
     });
    $("#dialog").dialog("open");
  });

A:     <!DOCTYPE html>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

<button id="btnAddList" onclick="addList()">Add List</button>

List items

  <input type="text" id="newCheckText" value="Enter Value" />
  <button id="btnAddItem" onclick="addItem()">Add</button>

List (//click)

      <input type="checkbox" class='chk1' index="0"/> List Item 1

      <input type="checkbox" class='chk1'index="1"/> List Item 2

      <input type="checkbox" class='chk1' index="2"/> List Item 3


text:
Q: Autolayout bug with UIAlertView/Controller? I am trying to switch the Autolayout constraints of my project for each orientation and am doing so by programmatically removing and adding a portrait and landscape set of NSAutoLayoutConstraints. I have the correct auto layout constraints (I think) for the layout for both orientations. My storyboard is not using Size Classes for compatibility.
I have taken screenshots of the correct layouts. The red portion is a UIView colored red.

Portrait layout

Landscape layout
My viewWillLayoutSubviews: is
- (void)viewWillLayoutSubviews {
    [self.termToolbar invalidateIntrinsicContentSize];
}

and all the constraints adding and removing is in updateViewConstraints
When starting the app in portrait orientation and then rotating to landscape, I get a constraint error:
2015-07-26 10:50:42.856 reproduce[1084:23311] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<_UILayoutSupportConstraint:0x786436c0 V:[_UILayoutGuide:0x7864cb70(20)]>",
    "<_UILayoutSupportConstraint:0x78643680 V:|-(0)-[_UILayoutGuide:0x7864cb70]   (Names: '|':UIView:0x7864ca90 )>",
    "<NSLayoutConstraint:0x78657bc0 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7864ca90(480)]>",
    "<NSLayoutConstraint:0x78657bf0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7864ca90(320)]>",
    "<NSLayoutConstraint:0x786593c0 V:[_UILayoutGuide:0x7864cb70]-(0)-[UISearchBar:0x78a21a70]>",
    "<NSLayoutConstraint:0x786593f0 V:[UISearchBar:0x78a21a70]-(0)-[UITableView:0x7982aa00]>",
    "<NSLayoutConstraint:0x78659420 V:[UITableView:0x7982aa00]-(0)-[UIView:0x78a216f0]>",
    "<NSLayoutConstraint:0x78620570 V:[UIView:0x78a216f0]-(0)-[UIToolbar:0x78b81d00]>",
    "<NSLayoutConstraint:0x786205a0 V:[UIToolbar:0x78b81d00]-(0)-|   (Names: '|':UIView:0x7864ca90 )>",
    "<NSLayoutConstraint:0x786590a0 UIView:0x78a216f0.height == 0.75*UIView:0x78a216f0.width>",
    "<NSLayoutConstraint:0x786596d0 H:|-(0)-[UIView:0x78a216f0]   (Names: '|':UIView:0x7864ca90 )>",
    "<NSLayoutConstraint:0x78659720 H:[UIView:0x78a216f0]-(0)-|   (Names: '|':UIView:0x7864ca90 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x786593f0 V:[UISearchBar:0x78a21a70]-(0)-[UITableView:0x7982aa00]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Note that I am rotating from portrait to landscape and the error shown are for the portrait orientation! When rotating from landscape to portrait, no debug output/error occurs. Rotating back to landscape causes the same error.
Even with these errors, the view layout appears fine for both portrait and landscape until I show a UIAlertView/Controller. Once an alert is shown, the layout fails and both portrait and landscape layouts are displayed wrong (UITableView disappears, red UIView takes up whole screen, etc). It doesn't matter if the alert is dismissed or still being presented, the layout will fail everytime after the alert.
I created a sample project to reproduce this behavior that can be found here. UI Element outlets are connected in IB.  All the code is in the default ViewController class. Any idea why this behavior is occurring or is this a bug in AutoLayout for a simple layout change between orientations? Thanks.
Portrait constraints:
<NSLayoutConstraint:0x7b05cda0 V:|-(0)-[_UILayoutGuide:0x7b0648a0]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05cc30 V:[_UILayoutGuide:0x7b0648a0]-(0)-[UISearchBar:0x7b0e9590]>,
<NSLayoutConstraint:0x7b05cc00 V:[UISearchBar:0x7b0e9590]-(0)-[UITableView:0x7cb4d600]>,
<NSLayoutConstraint:0x7b05cbd0 V:[UITableView:0x7cb4d600]-(0)-[UIView:0x7b0e9210]>,
<NSLayoutConstraint:0x7b05cba0 V:[UIView:0x7b0e9210]-(0)-[UIToolbar:0x7b069f10]>,
<NSLayoutConstraint:0x7b05cb70 V:[UIToolbar:0x7b069f10]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05ced0 UIView:0x7b0e9210.height == 0.75*UIView:0x7b0e9210.width>,
<NSLayoutConstraint:0x7b05c990 H:|-(0)-[UISearchBar:0x7b0e9590]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c940 H:[UISearchBar:0x7b0e9590]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c8a0 H:|-(0)-[UIView:0x7b0e9210]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c850 H:[UIView:0x7b0e9210]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c780 H:|-(0)-[UITableView:0x7cb4d600]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c730 H:[UITableView:0x7cb4d600]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c6c0 H:|-(0)-[UIToolbar:0x7b069f10]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c670 H:[UIToolbar:0x7b069f10]-(0)-|   (Names: '|':UIView:0x7b064990 )>

Landscape constraints:
<NSLayoutConstraint:0x7b05c530 V:|-(0)-[_UILayoutGuide:0x7b0648a0]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c4e0 V:[_UILayoutGuide:0x7b0648a0]-(0)-[UISearchBar:0x7b0e9590]>,
<NSLayoutConstraint:0x7b05c4b0 V:[UISearchBar:0x7b0e9590]-(0)-[UIView:0x7b0e9210]>,
<NSLayoutConstraint:0x7b05c480 V:[UIView:0x7b0e9210]-(0)-[UIToolbar:0x7b069f10]>,
<NSLayoutConstraint:0x7b05c450 V:[UIToolbar:0x7b069f10]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c290 V:|-(0)-[_UILayoutGuide:0x7b0648a0]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c240 V:[_UILayoutGuide:0x7b0648a0]-(0)-[UISearchBar:0x7b0e9590]>,
<NSLayoutConstraint:0x7b05c210 V:[UISearchBar:0x7b0e9590]-(0)-[UITableView:0x7cb4d600]>,
<NSLayoutConstraint:0x7b05c1e0 V:[UITableView:0x7cb4d600]-(0)-[UIToolbar:0x7b069f10]>,
<NSLayoutConstraint:0x7b05c1b0 V:[UIToolbar:0x7b069f10]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05bf70 H:|-(0)-[UITableView:0x7cb4d600]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05bf20 H:[UITableView:0x7cb4d600]-(0)-[UIView:0x7b0e9210]>,
<NSLayoutConstraint:0x7b05bef0 H:[UIView:0x7b0e9210]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05c2f0 UIView:0x7b0e9210.height == 0.75*UIView:0x7b0e9210.width>,
<NSLayoutConstraint:0x7b05be30 H:|-(0)-[UISearchBar:0x7b0e9590]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05bde0 H:[UISearchBar:0x7b0e9590]-(0)-|   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05bd70 H:|-(0)-[UIToolbar:0x7b069f10]   (Names: '|':UIView:0x7b064990 )>,
<NSLayoutConstraint:0x7b05bd20 H:[UIToolbar:0x7b069f10]-(0)-|   (Names: '|':UIView:0x7b064990 )>

A: I also filed an Apple Bug Report and TSI for this and got good answers back.
The solution for a method called before the device's returned orientation changes depends on what iOS versions you want to support.
iOS < 8 willRotateToInterfaceOrientation:
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];

    [self.view setNeedsUpdateConstraints];
}

iOS 8+ viewWillTransitionToSize:
and some checks to determine which orientation we are in.
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
    if (size.width < size.height && self.view.bounds.size.width > self.view.bounds.size.height) {
        [NSLayoutConstraint deactivateConstraints:landscapeConstraints];
    } else if (size.width > size.height && self.view.bounds.size.width < self.view.bounds.size.height) {
        [NSLayoutConstraint deactivateConstraints:portraitConstraints];
    }
    [self.view setNeedsUpdateConstraints];
}


text:
Q: linux - columns with width position I need columns to be with width position.is it possible ?
right now:
Z_mn_BS_1   2/01/2017 03:09:11  02/23/2017 01:02:51  FA
Z_mn_BS_1   2/01/2017       03:09:11       02/23/2017 01:02:51  FA

But i need :
Z_mn_BS_1   2/01/2017 03:09:11  02/23/2017 01:02:51  FA
Z_mn_BS_1   2/01/2017 03:09:11  02/23/2017 01:02:51  FA

A: you can do it with column -t file
man column for more information.


text:
Q: hibernate (grails) with Oracle 11g - insufficient privileges I'm using Grails 1.3.4, which uses Hibernate, going against an Oracle 11g database. My application fails on startup, with the following error:
2010-11-04 09:45:34,671 INFO  [grails.spring.BeanBuilder] [RuntimeConfiguration] Configuring data source for environment: TEST
2010-11-04 09:45:36,812 ERROR [org.hibernate.util.JDBCExceptionReporter] ORA-01031: insufficient privileges

2010-11-04 09:45:36,812 ERROR [org.hibernate.tool.hbm2ddl.SchemaUpdate] could not complete schema update
org.hibernate.exception.SQLGrammarException: could not get table metadata: MY_TABLE
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:90)

When I add the following in Oracle to my database user role, it works. However, my DBA states in Production, he will not grant ANALYZE ALL because it's no longer needed in 11G, and it messes up his statistics. What is the resolution?
GRANT ANALYZE ANY to APP_USER_ROLE;

More setup info below:
Grails DataSource.groovy
    dataSource {
        driverClassName = "oracle.jdbc.driver.OracleDriver"
        username = "APP_USER"
        password = "APP_USER_PASS"
        dbCreate = "update"
        url = "jdbc:oracle:thin:@MY_servername:1521:MY_SCHEMANAME"
        dialect="org.hibernate.dialect.Oracle10gDialect"
    }
    hibernate {
        default_schema="WEBSYS"
    }

Grails domain object using table:
static mapping = {
    table 'MY_TABLE'
    id generator:'sequence',params:[sequence:'MY_SEQ']
}

Oracle user and role setup:
CREATE ROLE APP_USER_ROLE NOT IDENTIFIED;
GRANT QUERY REWRITE TO APP_USER_ROLE;
GRANT CREATE SESSION TO APP_USER_ROLE;
GRANT GLOBAL QUERY REWRITE TO APP_USER_ROLE;
GRANT APP_USER_ROLE TO APP_USER;
CREATE USER APP_USER
  IDENTIFIED BY APP_USER_PASS
  DEFAULT TABLESPACE APPL_DATA
  TEMPORARY TABLESPACE TEMP
  PROFILE DEFAULT
  ACCOUNT UNLOCK;
  GRANT APP_USER_ROLE TO APP_USER;
  ALTER USER APP_USER DEFAULT ROLE ALL;
  ALTER USER APP_USER QUOTA UNLIMITED ON APPL_DATA;

  GRANT SELECT,UPDATE,DELETE,INSERT ON MYSCHEMA.MY_TABLE to APP_USER_ROLE;
  GRANT SELECT ON MYSCHEMA.MY_SEQ to APP_USER_ROLE;

A: Grails probably needs that permission to determine whether changes have been made to domain objects that aren't reflected in the schema.
Do you need grails to update the production schema automatically?  If not, try removing dbCreate = "update" for the production environment.


text:
Q: Vlookup then return a different row in Google Sheets I'm struggling to figure out how to get sheets to first look up the location of a key value and then look up which of the sub values it should take.  Best would be to include an example, which:
https://docs.google.com/spreadsheets/d/1pL62W7pSImMlTdnU3RMV4VDK3KIuNBT8l3VxClLGTd4/edit?usp=sharing
What I'm hoping to achieve is that the values for item 1, when selected, auto fill in the correct gear builder fields.
Any advice on this is hugely appreciated.

A: try:
=ARRAYFORMULA(IFNA(VLOOKUP(
 IF(F4:F12<>"", VLOOKUP(ROW(A4:A12),
 IF(G4:G12<>"", {ROW(A4:A12), G4:G12&"♦"}), 2, 1), )&F4:F12, {
 IF(B4:B12<>"", VLOOKUP(ROW(A4:A12),
 IF(A4:A12<>"", {ROW(A4:A12), A4:A12&"♦"}), 2, 1), )&B4:B12, C4:C12}, 2, 0)))