text:
Q: web crawling performance in node.js vs C# I'm writing an application that crawls over a long list of links , downloads pages, searching for html elements using xpath queries and stores some of the retrieved info in mysql database. I use multi-threaded solution to get the most of my servers and eliminate the effect of latency.
I write most of my applications using csharp and java, and my web applications I write with asp.net/c#.
What I want to ask is whether or not Node.js is something worth considering from performance view point? given the throughput is the most important factor. Node.js being more portable and cross platform is another reason, but performance is more important for me.

A: I think the bottleneck in your application is on the network (HTTP or MySQL), rather than on the code.
Up or down, Node.js is single-threaded and based on message queue, when all "messages" are completed, it quit. Every I/O is waited on thread pool (unless you use sync methods, which is not encouraged).
Few things on your case:

*

*You don't have simple and full controls on processors/threads, but you can always limit number of simultaneous job yourself

*You don't need to worry about concurrency because there is no concurrency at all

*All APIs in Node.js are designed with streamlined I/O in mind, you may only write 20-50% of code (in terms of lines) to write a web crawler, than in C#

*Node.js has no XML library built-in, you can find a few on NPM

*JavaScript is an interpreted language, code is slower than C#. But since your are more on I/O, I think it shouldn't slow you down too much

*Debugging JavaScript on Node.js is painful, but web crawling should not be very complicated either

I have wrote a few simple web crawlers on Node.js and would definitely recommend you to give it a try.


text:
Q: Generic browser with no tracking Most of the mainstream browsers nowadays can be easily tracked via regular cookies, flash supercookies, unique id numbers (e.g. Chrome), and various other less known tricks.
Does there exist any browser implementation whose main focus is on privacy, such that when http requests are sent to a server, the only thing known to the server is the IP address of the client and nothing else? The browser must present a generic face to the server indistinguishable from any other user of the browser.

A: Unfortunately, browsers are complex and trying to implement too much anonymity can create havoc with website compatibility. Just ask anyone who keeps cookies off.  It wreaks with functionality.
On that note, I suspect you are shooting for privacy rather than anonymity.  IE9 is probably the best one with its No tracking feature.  While other browsers are at the mercy of third party compliance, IE9 give users a bit more control by forcing compliance upon third party trackers.
I remember reading about the politics and drama that went to implementing this feature.  When it was first announced, ad companies threaten to sue.  That tells me this is a good feature when it threatens their business model.
Link
Another feature I would strongly suggest is a password manager.  LastPass is my choice here.  Along with strong plugins, two factor authentication, my favorite feature is the one time passwords.  Along with your master password, you can also use the one time passwords if you are logging into a public machine, rather than using your master password.
Outside of Firefox/Chrome/Opera/IE Privacy modes, I wouldn't bother with the rest of the hacks.  It's debatable how effective they are at protecting your privacy.

A: Some people use a "browser on a USB stick" ( a b ). Since all the cookies, etc. are stored on the stick, when you unplug the "stick I use for banking" and plug in the "stick I use for browsing Youtube", there's no way either site can access the data stored in the other unplugged stick.
Other people recommend booting an entire operating system from a USB stick when doing online banking.
I have Ubuntu on one USB stick and Fedora on another USB stick. I hear that other people like Puppy Linux or Chrome OS for their "OS on a USB stick".
In particular, the Fedora "Live USB creator" tool allows you to set how much of the USB stick to reserve for "persistent storage".
If that is set to zero, then you can be sure that no cookies, etc. are stored on the stick.

A: Its a little quirky but qtweb has the most finely grained privacy controls of any browser i've seen, and does user agent spoofing out of the box. You can disable most features easily including user agents, plugins and and cookies.
I'd note despite turning off nearly everything that could identify me(plugins, useragent, etc) the profile that pantopticlick gave me was unique, but things like supercookies and other client side tracking would not work. However this is the closest i could get to your requirements

A: SRWare Iron is based on Chromium with a focus on privacy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: View external library source code added by nuget in visual studio I use resharper and have configured symbol source providers as describe http://www.symbolsource.org/Public/Home/VisualStudio
And now I can debug code (view it source on debugging), but i cannot just view it (without starting of debugging).
For example I can view String class source code by using "go to definition". But when i try use it for nuget libraries I cannot see source code. I see only member declaration (interface) That is gotten by "Decompiled with JetBrains decompiler" (but still i can see that full source code on debugging).


text:
Q: BigDecimal evaluated as a string in Velocity, Struts2 I am using struts2 with Velocity 1.5 and Velocity Tools 1.3. In my template I want to do a loop like:
#set ($count = ${item.qty})
#foreach($i in [1..$count])
    ${item.price}
     ...........
#end

${item.qty} is a BigDecimal but it seems like its passed to Velocity as a String maybe. Since this loop does not work. Replacing to $count = 5 works fine, and printing ${item.qty} gives me a result of 5. Velocity 1.5 and Tools 1.3 is the highest version Struts2 will support. Ideas? Workarounds? Thanks

A: I think you need to cast/convert it to an integer for your loop to work.
#set ($count = $item.getQty().intValue())

A: perhaps you need to implement your own iterator - it will just store the start and end of the list of bigDecimals, and return the current one. This way, you can have an unlimited sized list of numbers (i assume that is what you wanted because you are using BigDecimals. Otherwise, just use an int or a long):
#set ($countIterator = ${item.qtyIterator})
#foreach($i in $countIterator)
    ${i}
     ....use $i as a string...
#end

and
public class QuantityIterator implement Iterator<BigDecimal> {
   QuantityIterator(BigDecimal start, BigDecimal end) { this.start = start;this.end=end;}
   //..implement the iterator methods like hasNext() etc
   public hasNext() {return this.current.compareTo(this.end) < 0;} //current <= end
   public BigDecimal next() {
      if (!hasNext()) {
         throw new NoSuchElementException();
      }
      this.current = this.current.add(BigDecimal.ONE);
      return this.current;
   }
   public void remove(){throw new UnsupportedException();}
}


text:
Q: Integrate Dojo Widgets inside React js application I am trying to Integrate Dojo Widgets inside React application. SO need to check if its possible and if yes , How its possible.

A: Even if you succeed the code would be messy and really difficult to maintain. I suggest using WebComponents to isolate the code.
See: https://developer.mozilla.org/en-US/docs/Web/Web_Components for a tutorial.


text:
Q: Set intersections and discrete intervals (a) Suppose F is a family of subsets of {1, 2,..., 60}, and that |x| = 3 for all x ∈ F. Assume further that x ∩ y = ∅ for every x, y ∈ F. What is the largest possible value of |F|?
(b) For any integer k ≥ 1, a discrete interval of length k is defined as a set of k consecutive integers. For example, {4, 5, 6, 7} and {−8, −7, −6, −5} are discrete intervals of length four, and {101, 102, 103} is a discrete interval of length three. A family F of discrete intervals of length k is called intersecting if x ∩ y ≠ ∅ for all x, y ∈ F. Describe a largest possible intersecting family F of discrete intervals of length 240, say how large it is, and prove that it is largest possible.
I am not entirely sure how to approach either of these problems. For part a, am I supposed to use the inclusion and exclusion principle or a set of Venn diagrams? Am I supposed to check for different subsets and then try to find the largest about of subsets in $F$?
And for part b, am I supposed to find a set of subsets of length 240 that all have common elements? I am not entirely sure about how to approach how to do that. Once again, will it have to involve drawing a sett of Venn diagrams and further manipulation?
Any help?

A: For (a), there's 60 numbers available, each subset has exactly 3 of them, and no two subsets contain the same number. So there can be at most 60/3=20 subsets in the family. You could dress it up in set theory notation for a more formal proof but I don't see the benefit.
For (b), you want 240 consecutive intervals, starting from the numbers 1 to 240. They all have non-zero intersection because they all include the number "240" itself. It's maximal because if you have 241 intervals then at least one pair must differ in starting value by at least 240, and that pair will not overlap.


text:
Q: TableView change of of behaviour I had a perfectly working app with multiple table views defined in a single Storyboard that has operated without issue for 18 months.
I recently changed to Xcode 5.0 and created a duplicate Storyboard, one configured for 4" screen and one for 3.5 with appropriate Delegate code to call the appropriate SB.
Although each TableView is essentially identical, some get called successfully and others crash with:-
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "m8N-d4-mjD-view-Yms-ZT-B8U" nib but didn't get a UITableView.'
What's also unexpected, is some table views work on a connected device, but not in the Simulator and vice versa.
I have researched and tried many different things, but cannot fathom the apparent variable behaviour - any help gratefully received. Thanks.

A: During the upgrade to Xcode5.0 my storyboards were damaged.
Check the following:
- Are the actual locations of the items in the Views correct (I had a lot of negative X and Y locations)?
- Are the links between the code and the items correct?
You said that you have copied the storyboard, a third solution is checking that the items are linked to the correct code version and not also to the previous version.


text: Q: How to compile laravel and vuejs app on live server or run 'npm run watch' command? I have a laravel and vuejs application on a live server. I have changed some text and add some features to my vuejs component but It can not affect my frontend. I think I should run 'npm run watch' or 'npm run dev' command but where is cmd? where I can run this command? Help Please


text:
Q: Interesting and not too difficult topics in geometry I was asked to give a talk to a mixture of undergraduate and graduate students on a topic of my choosing from differential geometry. The students will mostly not be in geometry; however, I believe I can assume they know the definition of a manifold, vector fields and integral curves as well as differential forms along with some other basic concepts.
I am looking for some suggestions of concepts in geometry, which can be geared towards a not-so-geometrical audience, that are really attention grabbing. The talk will be pretty informal and an hour long.
The talk can be in other areas of geometry too (Riemannian, Sympletic,...) but accessible enough that I can explain what I need to before getting to the crux, or the cool part, of the talk

A: I'd be quite careful about your background assumptions. Very many undergraduates, at least in the United States, don't learn the definition of a manifold during their degree-so your assumptions are only accurate if they've all taken an advanced geometry course.
As for advice, a first idea is to talk about the theorema egregium. The independence of a manifold from its embedding is one of the most important conceptual contributions of the twentieth century in geometry. For a different tack, you might consider focusing the talk around transversality and all the spectacular results that follow from it, along the line of Guillemin and Pollack. I find this stuff immensely more beautiful than the better known homological techniques that get the same results, and it's very amenable to pictures, to legitimate proofs in a short time span, and is again conceptually of the utmost significance.


text:
Q: how to add another object like the created one How do i add another object like this one without doing all the code again and without displaying it in 2 separate MovieClip Containers?
i have this
BG is a simple square 10px x 10px
    private var bg:BG = new BG();
    private var myContainer:MovieClip = new MovieClip();

    public function MainClass_Test() {
        createRow_Col();
    }

    private function createRow_Col() {
        var bg:MovieClip = new BG();
        for (var i:int = 0; i < 5; i++) {
            bg[i] = new BG();
            for (var j:int = 0; j < 5; j++) {
                bg[i][j] = new BG();
                myContainer.addChild(bg[i][j]);
                bg[i][j].x = bg[i][j].width * j + j * 10;
                bg[i][j].y = bg[i][j].height*i + i*10
                ;
            }

        }
        myContainer.x = stage.x
        myContainer.y = stage.stageHeight / 2 - myContainer.height / 2;
        addChildAt(myContainer,0);
    }

how do i make a myContainer2  with the same movie clips as the 1st one ,so then i can add it next to the 1st one
myContainer2.x = myContainer.x + myContainer.width +10
myContainer2.y = stage.stageHeight / 2 - myContainer2.height / 2;

A: A simple way is to change createRow_Col to take in a container and an x,y :
private var bg:BG = new BG(); // this is not used as another `bg` is declared in side the function
private var myContainer:MovieClip = new MovieClip();
private var myContainer2:MovieClip = new MovieClip();

public function MainClass_Test() {
    createRow_Col(myContainer, stage.x, stage.stageHeight/2 - myContainer.height/2);
    createRow_col(myContainer2, myContainer.x + myContainer.width + 10);
}

private function createRow_Col(container:MovieClip, x:Number, y:Number) {
    var bg:MovieClip = new BG();
    for (var i:int = 0; i < 5; i++) {
        bg[i] = new BG();
        for (var j:int = 0; j < 5; j++) {
            bg[i][j] = new BG();
            container.addChild(bg[i][j]);
            bg[i][j].x = bg[i][j].width * j + j * 10;
            bg[i][j].y = bg[i][j].height * i + i * 10;
        }

    }
    container.x = x;
    container.y = y;
    addChildAt(container, 0);
}

A better way would be to wrap the functionality in createRow_Col in a class that you derive from MovieClip so you only instantiate 2 instances and add to stage.

A: Why don't you just create a class for the container? You can then instantiate it as many times as you want with the same properties...

A: I would make it like this.
Create Background class and put
private function createRow_Col()

as part of Background.as and call that function when bg is added to stage using
addEventListener(Event.ADDED_TO_STAGE, onAdded) // in Background.as

Then in main class
make vars bg1 and bg2, and add the to your container. I would guess that you whant this so you can make some transition effect, if thats not the case, you can just leave it as is and put j < 10 instead of j < 5 in loop.
Hope this will help!


text:
Q: Getting ID with no Incomplete Status in SQL I have these data below to play with, and I want to pull only the ID/s with no Incomplete or 'I' status.
ID  SUBJECT   STATUS
1   Math        C
1   Physics     C
1   Chemistry   I
2   Math        I
2   Physics     C
2   Chemistry   I
3   Math        C
3   Physics     C
3   Chemistry   C

How do you code this in SQL wherein only ID #3 gets pulled since it is the only one without 'I' in its status.

A: You can use not exists :
select *
from table t
where not exists (select 1 from table where id = t.id and STATUS = 'I');

You can also re-express this as by using group by:
select id
from table
group by id
having count(distinct STATUS) = 1 and
       sum(case when STATUS <> 'C' then 1 else 0 end) = 0;

A: you can use "NOT IN"
select id
    from tablename
    where id NOT IN (select id from tablename where STATUS = 'I')

A: You can also do it like this,
SELECT id
  FROM tablename
 GROUP BY id
HAVING MIN(status) = MAX(status)
   AND MIN(status) = 'C';
/


text:
Q: To change the default bootstrap css values with less I'm doing a site with HTML5 andbootstrap-lessnothing works normally but I needed to change some colors in the navbar menu and I know I can do this throughvariables.less inside this file I navigate to the menus where I copy all the code related to the menu that I want to edit and paste in my .less file but it does not work I do not want to have to use! important to change the menu being that I know I can do this by only variables in the less that comes in the bootsrap this is theless code of the menu
LESS:
@navbar-default-color:             #fff;
@navbar-default-bg:                #f8f8f8;
@navbar-default-border:            darken(@navbar-default-bg, 6.5%);

//* Navbar links*/
@navbar-default-link-color:                #fff;
@navbar-default-link-hover-color:          #fff;
@navbar-default-link-hover-bg:             transparent;
@navbar-default-link-active-color:         #fff;
@navbar-default-link-active-bg:            darken(@navbar-default-bg, 6.5%);
@navbar-default-link-disabled-color:       #fff;
@navbar-default-link-disabled-bg:          transparent;

/* Navbar brand label*/
@navbar-default-brand-color:               @navbar-default-link-color;
@navbar-default-brand-hover-color:         darken(@navbar-default-brand-color, 10%);
@navbar-default-brand-hover-bg:            transparent;

/* Navbar toggle*/
@navbar-default-toggle-hover-bg:           #fff;
@navbar-default-toggle-icon-bar-bg:        #fff;
@navbar-default-toggle-border-color:       #fff;

even though I change the values it does not change on my site notice that I left everything white to do a test and my site does not change:

this is my menu:

Rod SP 215 Km 197 - Dourado - SP

+55 (16) 3345 4004

Contato

                    <button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
                        Toggle navigation

                    </button>

resort

acomodações

gastronomia

atividades

SPA

eventos

monitoria

pacotes

programação

                          Contato

Localização

I'm importing everything normal bootstrap``css andjs together with jquery and I'm doing@ import right away
<link rel="stylesheet" href="assets/vendor/bootstrap/dist/css/bootstrap.min.css">

my app.less file with the import:
@import "../vendor/bootstrap/less/bootstrap.less";
@import "app.css";

image of my variables with the colors I need to change, I copied the variables from the variables.less file and added it to myapp.less I changed the colors they appear on the console but they do not overwrite.

my less file with the color changes (remembering that this is a copy of thevariables.less file)


text:
Q: Owl carousel right side space issue I have added owl carousel slider on a web page https://jeffbrownyachts.com/site/test5 (news section). Please click on news from the navigation.
Currently, the news is showing as 2 rows 3 columns in an owl carousel slider. The issue is that the owl carousel shows unexpected space at the right corner of the slide.
https://prnt.sc/patw11. Could anyone tell me the issue?
// owl carousel code
$('.owl-carousel').owlCarousel({
      dots: false,
      stagePadding: 0,
      loop:true,
      margin:0,
      nav:true,
      center: true,
      responsive:{
          0:{
            items:1,
            nav:true
          },
          600:{
            items:2,
            nav:false
          },
          1000:{
            items:3,
            nav:true,
          }
      }
  });

A: There is a width issue in .owl-stage element. The issue is solved by recalculating the width of .owl-stage element through onInitialized event of owl carousel. I solved the issue using this Github issue
$(document).ready(function(){
      var fixOwl = function(){
        var $stage = $('.owl-stage'),
            stageW = $stage.width(),
            $el = $('.owl-item'),
            elW = 0;
        $el.each(function() {
            elW += $(this).width()+ +($(this).css("margin-right").slice(0, -2))
        });
        if ( elW > stageW ) {
            $stage.width( elW );
        };
      }
         $('.owl-carousel').owlCarousel({
              dots: false,
              stagePadding: 0,
              margin:0,
              onInitialized: fixOwl,
              onRefreshed: fixOwl,
              responsive:{
              0:{
                items:1,
                nav:true
              },
              600:{
                items:2,
                nav:false
              },
              1000:{
                items:3
              }
          }
      });
    });


text:
Q: Bounding boxes around text regions with different font size I am trying to implement some kind of text detection algorithm and I want to separate the image into regions where each region contains different font size.
As in this image, for example:

Is there any easy way to implement it using python and/or opencv? if so, how?
I did tried googling it but could not find anything useful..
Thanks.

A: This is an interesting question. There are a few steps that you need to take in order to achieve your goals. I hope you are sufficiently informed of basic computer vision algorithm (knowledge in openCV function helps) to understand the steps i am suggesting.

*

*Group all the words together using morphological dilation process.

*Use openCV findcountour function to label all the blobs. This will give you the width and height information of each blob as well.

*Here is the tricky part, now that you have data on each blob, try to run a clustering algorithm on the data with the location(x,y) and geometry(width,height) as your features.

*Once you cluster them correctly, its a matter of finding the leftmost, rightmost, topmost and bottom data to draw the bounding rect.

I hope this will provide you enough information to start you work. Its is not detailed but i think its enough to guide you.


text:
Q: setInterval() only fires once

var x = 0;

window.addEventListener("keydown", function(e) {
    switch (e.key) {
    case "ArrowLeft":
        setInterval(changeValue, 1000, "up");
        break;
    case "ArrowRight":
        setInterval(changeValue, 1000, "down");
        break;
    }
})

function changeValue(direction) {
    switch (direction) {
    case "up":
        x += 10;
        console.log(x);
        break;
    case "down":
        x -= 10;
        console.log(x);
        break;
    }
}

I was expecting my code to keep adding or subtracting 10 from x every second depending on what arrow key the user has pressed. However, setInterval only seems to fire once, and I can't figure out why.

A: A way to do what you are looking for:

var
  conterVal = 0
, addValue  = -10
, refIntv   = null
  ;
bt_tenMoreLess.onclick =_=>
  {
  addValue = -addValue
  if (!refIntv)
    {
    counter.textContent = conterVal += addValue
    refIntv = setInterval( changeValue , 1000)
    bt_stop.disabled = false
    }
  }
bt_stop.onclick =_=>
  {
  clearInterval( refIntv )
  refIntv = null
  bt_stop.disabled = true
  }
function changeValue()
  { counter.textContent = conterVal += addValue }

0

<button id="bt_tenMoreLess">count ± 10</button>
<button id="bt_stop" disabled >stop</button>


text:
Q: Safely uninstalling GNOME desktop environment on Fedora 29 This question is similar to What is secure to remove from GNOME Desktop => GNOME (but not a duplicate).
I want to remove the GNOME desktop environment. Running the proposed command in this question does not work on Fedora 29.
$ sudo dnf group remove gnome-desktop-environment
Warning: Group 'gnome-desktop-environment' is not installed.
Error: No groups marked for removal.

I noticed there is a group called gnome-desktop instead.
However, sudo dnf group remove gnome-desktop lists hundreds (all?) of installed packages for removal. It includes packages that are not at all related to GNOME (such as lib*, plasma-*, texlive-*, ...). I fear that running this command will force me to do a full re-install of the system.
Is there a safe way to remove GNOME's desktop environment from Fedora 29 that leaves me with a functioning KDE install?
I just want to reclaim some disk space (not all of it..)

A: As the other answer point out, you can remove all of GNOME with # dnf group remove gnome-desktop. This will delete most of the packages even not related to GNOME itself (Xorg for example).
However if you just want to switch from one DE without complete reinstall, you can install other environment with e.g. # dnf groupinstall kde-desktop. This will bring back X and all the nessesary packages as in fresh Fedora spin.
One annoying little thing I found is that you have to reinstall packages like chromium using dnf. They will keep their configs though, so it wasn't a huge deal for me.

A: You can actually remove and install packages in the same operation, with dnf swap. And since the option takes groups as well as just single package names, you can switch one for another very simply:
dnf swap @gnome-desktop @kde-desktop

A: This is probably no a satisfying answer, but I don't think so. I recently tried to remove gnome from Fedora 29 to switch to i3. After setting the window manager up, I used $ sudo dnf group remove gnome-desktop to 'just' get rid of gnome and I wasn't even able to start up an xserver afterwards. As you said, $ dnf group remove gnome-desktop-environment seems to be obsolete. I found this thread to be interesting, too.

A: I was able to do this in Fedora 37 to switch to Cinnamon, and I have provided a similar one that should work for KDE below. You can replace that with another name found via dnf grouplist --hidden -v if neither switching to KDE nor Cinnamon. You must be in a text-mode tty (Such as by pressing Ctrl+Alt+F2 or whichever F key is non-graphical) since it removes gdm (and switches to lightdm)!
If you can stuck and have no graphical login screen, press Ctrl+Alt+F3 or another unused terminal and sudo dnf install sddm and sudo systemctl enable sddm (or lightdm if desired for Cinnamon) as per the steps below.
I suggest saving this as a script to your home directory (~) since you will not have a GUI and cannot easily read this page on the same computer (install lynx browser if you get really stuck).
Any updates to the KDE (below) and Cinnamon versions of this script will be at https://github.com/poikilos/linux-preinstall.

*

*KDE version: wget -O ~/swap-gnome-to-kde.fedora.sh https://github.com/Poikilos/linux-preinstall/raw/master/everyone/optional/swap-gnome-to-kde.fedora.sh

*Cinnamon version: wget -O ~/swap-gnome-to-cinnamon.fedora.sh https://github.com/Poikilos/linux-preinstall/raw/master/everyone/optional/swap-gnome-to-cinnamon.fedora.sh
Before choosing whether to continue, accept license including the disclaimer: https://github.com/Poikilos/linux-preinstall/blob/master/license.txt
Before doing any of this:

*

*save all of your work and close all GUI programs and logout (all
GUI applications in all TTYs will close when switching to a
different desktop manager!)

*do the wget command above of your choice

*as stated, go to text mode (such as Ctrl+Alt+F2 or whatever tty is non-graphical) not a GUI Terminal application.

echo "This script was not tested with KDE. Only the Cinnamon version was tested."
echo "If you're not sure what you're doing or are in a GUI Terminal application press Ctrl+C to cancel!"
echo "5 seconds left to cancel..."
sleep 5
sudo dnf install -y sddm
sudo mkdir /etc/dnf/protected.d-unprotected-by-linux-preinstall
sudo mv /etc/dnf/protected.d/fedora-workstation.conf /etc/dnf/protected.d-unprotected-by-linux-preinstall/
# ^ has NetworkManager & gnome-shell, but KDE uses NetworkManager:
echo "NetworkManager" | sudo tee /etc/dnf/protected.d/cinnamon-fedora-workstation-linux-preinstall.conf
sudo dnf groupremove "GNOME desktop Environment"
echo "Only say 'y' to the following if you're really sure and you are in a text-mode tty, not a GUI terminal!"
# Remove extras that will block gnome-shell uninstall:
sudo dnf remove "gnome-shell-*"
# swap avoids removing packages that both use:
sudo dnf swap gnome-shell @kde-desktop-environment
sudo systemctl enable sddm

Please let me know your successes or failures or submit a pull request on the repo.


text:
Q: Is the any way to create String Literal Types in Java? I'm new to Java.
I've been using Typescript to type my projects in the Front-end and I'm very used to creating String Literal Types to limit possible inputs. Is there any easy way to this in Java?
For eye candy, here's how you create it in Typescript:
type Easing = "ease-in" | "ease-out" | "ease-in-out";

A: No. The most similar thing is an enum Type.
public enum Easing {
    EASE_IN, EASE_OUT, EASE_IN_OUT;
}


text:
Q: net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: dao.entities.CourseMaster.chapterCourseMappings, no session or session was closed
My Entity:
    @Entity
    @Table(name = "course_master")
    public class CourseMaster implements Serializable {

private Integer id;
private String courseName;
private String category;
private Set<CourseWeightage> courseWeightages = new HashSet<CourseWeightage>();
private Set<ChapterCourseMapping> chapterCourseMappings = new HashSet<ChapterCourseMapping>();

public CourseMaster() {
}

public CourseMaster(String courseName, String category) {
    this.courseName = courseName;
    this.category = category;
}

public CourseMaster(String courseName, String category,
        Set<CourseWeightage> courseWeightages, Set<ChapterCourseMapping> chapterCourseMappings) {
    this.courseName = courseName;
    this.category = category;
    this.courseWeightages = courseWeightages;
    this.chapterCourseMappings = chapterCourseMappings;
}

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

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

@Column(name = "course_name", nullable = false, length = 100)
public String getCourseName() {
    return this.courseName;
}

public void setCourseName(String courseName) {
    this.courseName = courseName;
}

@Column(name = "category", nullable = false, length = 2)
public String getCategory() {
    return this.category;
}

public void setCategory(String category) {
    this.category = category;
}

@OneToMany(fetch = FetchType.EAGER, mappedBy = "courseMaster")
public Set<CourseWeightage> getCourseWeightages() {
    return this.courseWeightages;
}

public void setCourseWeightages(Set<CourseWeightage> courseWeightages) {
    this.courseWeightages = courseWeightages;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "courseMaster")
public Set<ChapterCourseMapping> getChapterCourseMappings() {
    return this.chapterCourseMappings;
}

public void setChapterCourseMappings(Set<ChapterCourseMapping> chapterCourseMappings) {
    this.chapterCourseMappings = chapterCourseMappings;
}
}

Controller Method: (RESTful Web Service API)
Potential Operations in Method causing Exception!
    net.sf.json.JSONObject data = new net.sf.json.JSONObject();

    List<CourseMaster> alrCourseMasters = genericBusiness.getCourses();

    data.put("courselist", alrCourseMasters);

    view = new Viewable("/test.jsp", data);

    return Response.status(200).entity(view).build();

DAO Method:
public List<CourseMaster> getCourses()
{
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    Query query = session.createQuery("from CourseMaster");
    List<CourseMaster> alrCourseMasters = query.list();
    transaction.commit();
    session.flush();
    session.close();
    return alrCourseMasters;
}

A: If you are serializing the Object into the string, you should have eager initializing in your associated hibernate entities.
in your case,
 @OneToMany(fetch = FetchType.LAZY, mappedBy = "courseMaster")
public Set<ChapterCourseMapping> getChapterCourseMappings() {
return this.chapterCourseMappings;
}

rename to as below
@OneToMany(fetch = FetchType.EAGER, mappedBy = "courseMaster")
public Set<ChapterCourseMapping> getChapterCourseMappings() {
return this.chapterCourseMappings;
}

Also check all associations should be eager fetch.
OR ELSE you can use create SQlQueries in hibernate and map that result to some pojo and convert that into json string. it will works.


text:
Q: How to fix AMD Vision Engine Control Center seeing my display as CRT? I'm running an HP Pavilion dv6-3010us, with a Radeon HD 4200 series GPU. I have updated the ATI Catalyst Control Center, and now it's completely changed to AMD Vision Engine Control Center.
I have removed the laptop's monitor and hooked it up to a Dell 2009wt monitor that I bought recently via the VGA connection. I have also manually installed Dell's driver for it, and the Device Manager recognizes it as the 2009wt that it is. However, the Vision Engine Control Center only recognizes it as "Unknown Display," and a CRT at that.
Does anyone know why it's doing this, or some way I can force a manual detection, similar to forcing the monitor driver to update even though Windows thought "Generic Non-PnP Monitor" was best?
Alternatively, will I have more luck using an adapter to hook up the HDMI out of the laptop to the DVI in on the monitor?
EDIT: My HDMI to DVI adapter cable just arrived, and it works perfectly. The settings adjusted instantly when I plugged it in (the monitor was on auto-detect), and now I'm running max resolution with a 16:10 picture!
Should I answer my own question and mark that as best, or just leave the question alone now?


text:
Q: Number of possible American radio station call letter sequences containing a Q The problem goes like this (8.6 #17 Precalc with limits aga 5th edition):

Typically radio stations are identified by four "call letters." Radio stations east of the Mississippi River have call letters that start with the letter W and radio stations west of the Mississippi River have call letters that start withe the letter K.
(a) Find the number of different sets of radio station call letters that are possible in the United States.
(b) Find the number of different sets of radio station call letters that are possible if the call letters must include a Q.

Textbook's answers:
a) 35152
b) 3902
When I did the problem for (b), I got the answer by $2 \cdot 3 \cdot 26 \cdot 26 = 4056$. This means that the first letter can either be a K or W (2), and the Q can be placed anywhere in the other three spots (3), and the other two spots can be filled with any letter of the alphabet ($26 \cdot 2$). What am I doing wrong here that makes my answer not match up with the textbook answer (or the other way around)? Am I over counting?
edit: The textbook solution said that the answer came from subtracting the non-Qs from the total amount ((answer from (a)) $- (2 \cdot 25^3)$).

A: The book's method of using complementary counting is the optimal way to solve the problem of counting sequences of radio station call letters that contain at least one Q.
As Daniel Mathias indicated in the comments, you counted sequences with more than one Q multiple times.
A direct count
Sequences of call letters with exactly one Q: Since the first position must be filled with a K or a W, there are two ways to fill it.  There are three ways to choose the position of the only Q.  Each of the remaining positions may be filled with one of the other $25$ letters.  Hence, there are $2 \cdot 3 \cdot 25 \cdot 25 = 3750$ such sequences.
Sequences of call letters with exactly two Qs:  As above, there are two ways to fill the first position.  There are $\binom{3}{2}$ ways to select two of the other three positions for the Qs.  The remaining position can be filled with one of the other $25$ letters.  Hence, there are $2 \cdot \binom{3}{2} \cdot 25 = 150$ such sequences.
Sequences of call letters with exactly three Qs:  There are two ways to fill the first position.  The remaining three positions must be filled with Qs.  Hence, there are $2$ such sequences, namely KQQQ and WQQQ.
Total:  Since the three cases above are mutually exclusive and exhaustive, the number of permissible sequences of call letters is $3750 + 150 + 2 = 3902$.
Correcting your count
You chose the first letter, the position of a Q, and then filled the remaining two positions with any of the $26$ letters, which gave you a count of $2 \cdot 3 \cdot 26 \cdot 26$ for sequences that contain a Q.
However, you have counted sequences with two Qs such as KQRQ twice, once for each way you could have designated one of those Qs as the Q in the sequence.  Since we only want to count sequences with two Qs once, we must subtract them from the total.
We count sequences with two Qs.  We still have two ways of choosing the first letter.  We now have $\binom{3}{2}$ ways to select the positions of the two Qs.  We also have $26$ ways to select the letter that goes in the remaining position.  Hence, there are $2 \cdot \binom{3}{2} \cdot 26$ sequences that contain two Qs.
Subtracting these from the total gives us a running count of $2 \cdot 3 \cdot 26 \cdot 26 - 2 \cdot \binom{3}{2} \cdot 26$.
However, we have subtracted too much.  We only want to count sequences with three Qs once.  However, we counted them three times in your original count, once for each way we could have designated one of those Qs as the Q that is contained in the sequence.  We also subtracted three times, once for each of the $\binom{3}{2}$ ways we could have designated two of them as the two Qs in the sequence.  Thus, we have not yet counted them at all.  Therefore, we need to add them to the total.
As we saw above, there are two possible sequences of call letters with three Qs.
Thus, the number of permissible sequences of call letters is
$$2 \cdot 3 \cdot 26 \cdot 26 - 2 \cdot \binom{3}{2} \cdot 26 + 2 = 4056 - 156 + 2 = 3902$$
This method of counting uses the Inclusion-Exclusion Principle.


text:
Q: Summernote image upload gives an SQL error I am stuck with a problem containing Summernote. I added the Summernote bar to my div, all functions work except the image uploader. It allows the image to be uploaded but when I click save. This error shows up:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'description' at row 1 (SQL: update tasks set updated_at = 2018-11-20 09:08:43

Does someone know how to resolve this problem? Thanks in advance.

A: First option:
You can make description column type text without length.
Second option:
By default summernote insert image data to src. You can reduce data length, by upload images to server and insert image url instead of image data.
$('.summernote').summernot({
    callbacks: {
        onImageUpload: function(image, editor) {
            let data = new FormData();
            data.append('file', image[0]);
            $.ajax({
                url: 'path to your upload method',
                cache: false,
                contentType: false,
                processData: false,
                data: data,
                type: 'post',
                success: function (url) {
                    editor.summernote('insertImage', url);
                }
            });
        }
    }
});

A: Change description column type to TEXT. if that is allready TEXT then change it to MEDIUMTEXT.
Remember length of TEXT type is 65,635 character only.
Use MEDIUMTEXT or LONGTEXT for big content.


text:
Q: Qt4: QMenuBar/QMenu doesn't show up on Mac OS X I'm having difficulties to make a QMenuBar display a QMenu with a QAction under Mac OS X (Snow Leopard).
Here is the code I'm using for creating the menu:
void ClientWindow::setUpMenu ()
{
   QMenu * file = menuBar()->addMenu("&File");
   QAction * quit = new QAction("&Quit", this);
   file->addAction(quit);

   connect(quit, SIGNAL(triggered()), this, SLOT(quit()));
}

Here is the ClientWindow class interface:
class ClientWindow : public QMainWindow
{
    public:
        ClientWindow (QWidget * parent = 0);
        void setUpMenu ();
};

And here is my main() method:
int main (int argc, char * argv[])
{
    QApplication app(argc, argv);
    ClientWindow window;

    window.setUpMenu();
    window.show();

    return app.exec();
}

Any ideas why it wouldn't show up on the menu bar?
Thank you all.

A: I solved the problem.
It appears that there is one action called "Quit" already, which is part of the default application's menu (every Mac OS X GUI app has such menu). This causes my attempt to add another action called "Quit" to be ignored by either Qt or the Window Server.
Simply renaming the action to "Close" solved the problem.

A: Some menupoints are automatically mapped to the mac osx native menu:
see http://doc.trolltech.com/4.6/mac-differences.html#menu-bar


text:
Q: Incorrect use of the plural form ("one questions/answers") This is a minor grammar quibble with respect to the UI.
Is it possible to add some logic to the Network Profile page, on the accounts tab, that changes the label "answers" to the singular "answer", in the case of there only being one question or answer?

Admittedly this is a duplicate of the question Wrong pluralization on accounts tab of user profile. The answer to that question was that it will not be fixed. However, the logic already exists elsewhere on the site. The logic required is demonstrated here. Here, you can find words "1 Question" & "1 Answer".

In addition, Oded's comment on his answer to the question "1 edit suggestions rejected" suggests that it could quite easily be fixed now.

A: Nope, this still can't be done, sorry.
On our Q&A sites, we use our in-house localisation platform, called MoonSpeak, to provide pluralisation support. However, the issue you're mentioning is on stackexchange.com, which is a separate product area from our Q&A sites. stackexchange.com does not currently use MoonSpeak, nor does it have any localisation support at present.


text:
Q: childNode inside a div element I'm learning the JavaScript right now and I'm writing functions to change the style of the each paragraph tag and the font-style tag emphasis(em) and bold(b) which is inside the
 element.Here is my program.

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.

what I'm trying is to change the color of the
 tags used inside the div element. But when I run the output, the console says sampDiv2.childNodes[0].style is undefined

A: The childNodes includes text nodes also, so it's better to use children instead which returns html elements.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: You can do what you want with css.

With this all
 element will have that background colors, em elements will be red and bold elements will be dark blue. Learn more about css to know more.
By the way, the code above works if put in the html file, but it's recommended to put in in a separate css file (with


text:
Q: Python Regex for URLs need help with Python regex for URLs
    re.findall(r"((^hxxp|http|https)+:+//+([a-zA-Z]{1,32})+((.){1,4})+(([a-z]|.){1,10}))", datastream)

This is matching full URLs as designed but also chunks of the string to be matched resulting in Python crapping out.
I would prefer to use findall using .match would require some sizeable changes.


text:
Q: perform trigger on a particular date I am having a table which contains columns named as 'Date of joining' and 'Eligible for appraisal' and monthscycle.
in this process according to the employess 'date of joining'  and the number of monthscycle i have to update the 'Eligible for appraisal'.
Example:
Name : abc ;
Date of joining : 07/4/2014 ;
Monthscycle : 12 ;
cosider that , if todays date is 07/4/2015 it should automatically trigger the value of
'Eligible for appraisal' from 0 to 1 .
is this is possible if so please help me .
Thanks in advance

A: As stated in the comment, consider running this once a day instead of every time the table is updated.  Then it is a simple update statement that looks like this:
UPDATE `YourTable`
SET EligibleAppraisal = 1
WHERE CURRENT_DATE - DATE(JoinDate) >= 365;


text:
Q: Copy URL parameters and inject them in another URL )I've to copy the parameters of the current page URL and inject them in a new URL to place in the href of a button, on the same current page. The page is made by WordPress + Divi.
So I put a custom ID for the button that fires a script. My script is quite complicated and I suppose it could be simplified but it works...until I try to inject the new URL in the href button.
So my goal is to have "https://website.com/new-url/?f=John&l=Doe& ..."
from "https://website.com/current-url/?f=John&l=Doe& ..."
and place the new URL in the href button that is on the current-url
If someone could help me, I thank him in advance!
Heres is my code :

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var f_value = getParameterByName('f');
var l_value = getParameterByName('l');
var e_value = getParameterByName('e');
var ph_value = getParameterByName('ph');
var id_value = getParameterByName('id');
(function( $ ) {
    $( "#js-caller" ).on( "click", function( event ){
        const myUrlWithParams = new URL("https://website.com/new-url/");
        myUrlWithParams.searchParams.append("f", f_value);
        myUrlWithParams.searchParams.append("l", l_value);
        myUrlWithParams.searchParams.append("e", e_value);
        myUrlWithParams.searchParams.append("ph", ph_value);
        myUrlWithParams.searchParams.append("id", id_value);

        console.log(myUrlWithParams.href);
        alert(myUrlWithParams);
        event.preventDefault();
    });
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
var f_value = getParameterByName('f');
var l_value = getParameterByName('l');
var e_value = getParameterByName('e');
var ph_value = getParameterByName('ph');
var id_value = getParameterByName('id');
(function( $ ) {
    $( "#js-caller" ).on( "click", function( event ){
        const myUrlWithParams = new URL("https://website.com/new-url/");
        myUrlWithParams.searchParams.append("f", f_value);
        myUrlWithParams.searchParams.append("l", l_value);
        myUrlWithParams.searchParams.append("e", e_value);
        myUrlWithParams.searchParams.append("ph", ph_value);
        myUrlWithParams.searchParams.append("id", id_value);
        console.log(myUrlWithParams.href);
        alert(myUrlWithParams);//for testing the new url (and it works!)
        event.preventDefault();//to stop the Divi default event
    });
})( jQuery );

A:

var currentUrl = 'https://website.com/current-url/?f=John&l=Doe';
var newUrl = 'https://website.com/new-url/';
var indexOfQuestionMark = currentUrl.indexOf('?');

console.log(newUrl + currentUrl.slice(indexOfQuestionMark));

You don't need to chunk up the query string if you want to simply copy it to a different url.  Just slice it off and append it to the other url.

A: window.location.search returns the params, so say if the current URL you are on is https://example.com?utm_source=ap&utm_medium=email&utm_campaign=intro&utm_id=eml
And you wanted a link to https://app.example.com in the page that copies over (includes) those query params, you can simply...

const url = `https://app.example.com${window.location.search}`;

Which would return https://app.example.com?utm_source=ap&utm_medium=email&utm_campaign=intro&utm_id=eml


text:
Q: Getting an all blank bar chart with Matplotlib I've run this code in both Jupyter Notebook and PyCharm and get the same blank bar chart in both.
Anyone know why this is happening and how to get the bar coloured?
import pandas as pd
import matplotlib.pyplot as plt

data = {
'Elements' : ['Item_1', 'Item_2', 'Item_3', 'Item_4', 'Item_5'],
'Count' : [300,10,90,100,15],
'Produces': [1,140,10,5, 90]
}

df = pd.DataFrame(data)
df['potential'] = df['Count'] * df['Produces']

plt.figure()
plt.bar(x = df['Elements'], height = ['potential'])
plt.show()

Screenshot

A: I think you forget df in-front of the height = df['potential'].
It should work as expected.
import pandas as pd
import matplotlib.pyplot as plt

data = {
'Elements' : ['Item_1', 'Item_2', 'Item_3', 'Item_4', 'Item_5'],
'Count' : [300,10,90,100,15],
'Produces': [1,140,10,5, 90]
}

df = pd.DataFrame(data)
df['potential'] = df['Count'] * df['Produces']

plt.figure()
plt.bar(x = df['Elements'], height = df['potential'])
plt.show()

A: You for got one df:
plt.bar(x = df['Elements'], height = df['potential'])
#                                    ^ this

Also consider
df.plot.bar(x='Elements', y='potential')


text:
Q: Firebase Google SignIn asks every time for permissions I have implemented a Google SignIn with Firebase in my iOS app, following the Firebase guide. The problem is that every time I test the login, it always asks for permissions.

Here is the code of AppDelegate involved in Google SignIn:
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        // Override point for customization after application launch.
        FIRApp.configure()

        GIDSignIn.sharedInstance().clientID = FIRApp.defaultApp()?.options.clientID
        GIDSignIn.sharedInstance().delegate = self

        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {

        if let error = error {
            print(error.localizedDescription)
            return
        }

        print("Logged in with Google successfull")

        // ... Firebase authentication ...

    }
}

And here the code of View Controller with GIDSignInButton:
import UIKit

class IntroViewController: UIViewController, GIDSignInUIDelegate {

    @IBOutlet weak var signInButton: GIDSignInButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        GIDSignIn.sharedInstance().uiDelegate = self
        signInButton.style = .wide
    }

}

I've searched a lot on the web but found nothing... So, how can I prevent to ask for permission every time?

A: I believe this is working as intended. The issue is that you're signing out the user when you're testing your app, and the Google Sign-in library makes the assumption that if a user has explicitly signed out of your app, it should ask that user for permission again before signing that user in.
If you don't explicitly sign out the user, both signIn() calls and signInSilently() calls should succeed without displaying any kind of sign-in screen.

A: I'm not entirely sure what you're asking.  Do you want to check if the user is already signed in with their Google account?
if (GIDSignIn.sharedInstance().hasAuthInKeychain()) {
    // user is signed in
} else {
    // show login
}

A: You can override the problem in this way: You have to store in your internal database your currentID and when you open your app you get currentID and consequently you get all info for your user.
I had the same problem with the Facebook Login and I solved with this issue.
Good job

A: You can try signing in the user silently, But you will have to make sure wether or not if GIDAuthentication properties are already available to you or not such as - idToken, accessToken..etc
Then just call for
signIn.signInSilently()

assuming that signIn is the parameter of type GIDSignIn
look for - (void) signInSilently in :- Google Docs

A: On successful google sign-in, Authentication firebase user worked for me, I used following code,
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError?) {
    if error != nil {
        return
    }
    let authentication = user.authentication
    let credential = FIRGoogleAuthProvider.credentialWithIDToken(authentication.idToken,
                                                                 accessToken: authentication.accessToken)
    FIRAuth.auth()?.signInWithCredential(credential) { (user, error) in

        }

    }
}

A: According to Firebase official documentation, you should add the following function in AppDelegate:
func application(application: UIApplication,
  openURL url: NSURL, options: [String: AnyObject]) -> Bool {
    return GIDSignIn.sharedInstance().handleURL(url,
        sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
        annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}

And, if you want this to work in iOS 8 and less, you should add the function you already have:
func application(application: UIApplication,
  openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
    var options: [String: AnyObject] = [UIApplicationOpenURLOptionsSourceApplicationKey: sourceApplication,
                                        UIApplicationOpenURLOptionsAnnotationKey: annotation]
    return GIDSignIn.sharedInstance().handleURL(url,
        sourceApplication: sourceApplication,
        annotation: annotation)
}

You can try adding both functions (As suggested by Firebsae), and see if this fixes the error. I'm not sure if this will gonna solve it, but at least is an improvement to the GID feature.
EDIT: Source: https://firebase.google.com/docs/auth/ios/google-signin


text:
Q: How to link account to pricebook I'm working on an application in which it should be possible to link an account to a pricebook. Because for different accounts, different prices may be appropriate. Is there a way to directly link an account to a pricebook?

A: An opportunity is related to a PriceBook via the PriceBook2Id lookup. An Opportunity is tied to an an Account.
You could create a text field on Account, PriceBookId__c and stamp the id of the PriceBook permitted. Then have a validation rule on Opportunity which only permits a PriceBook whose Id matches the value stamped on the Account.
PriceBook2Id != Account.PriceBookId__c


text:
Q: over/in/at some place to describe I'm a non-English speaker and I have a little question.
Let's say I have some paintings and I want to give them a name, what is the most eloquent way of referring to them?

*

*"Night over/in/at/other London" - what is the best way to describe the night at some location?

*"Sunset/sunrise over/in/at/other London" - what is the best way to describe sunset/sunrise at some location?

A: "At London" would be a non-standard usage because cities are areas rather than points (you might say "at Big Ben," which is a single location). "Over" works with "sunset" and "sunrise" because these phenomena are in the sky; it also works poetically with "night" in a way that emphasizes the night sky. "In" is also appropriate for all examples (c.f. "A Night in Tunisia").


text:
Q: What interpolation of a set of points has a rectification where the angles in the rectification change linearly? We seek a function from $\mathbb{R}$ to $\mathbb{R}$ such that the function interpolates some points and the rectifications of $f$ have some special properties
DEFINITION OF RECTIFICATION

For any two continuous functions $f$ and $g$ which map from some real interval to to $\mathbb{R}$ $g$ is a rectification of $f$ if all of the following conditions are met:

*

*$g(x) = f(x)$ wherever rectification $g$ is not differentiable.

*$\forall x_{0} \in \mathbb{R}$ if $g$ is not differentiable at $x = x_{0}$ then $\exists R \in \mathbb{R} : \forall r \in \mathbb{R}$ if $0 < r < R$ then $g$ is differentiable at $x = x_{0} + r$ and $g$ is differentiable at $x = x_{0} - r$

*$\forall x \in \mathbb{R}$ if $g$ is differentiable at $x$ then $\exists C \in \mathbb{R}: g^{\prime}(x) = C$.

Note that a rectification of $f$ will look like a bunch of line-segments glued end-to-end.
DEFINITION OF A LINEARLY-SPACED RECTIFICATION

We say that a rectification is linearly-spaced if at least one of the following two criterion is met:

*

*There exists $a \in \mathbb{R}$ such that for any maximal-length line segment $L$ in the rectification the length of $L$ is equal to $a$

*There exists $a,b \in \mathbb{R}$ such that the set of all x-coordinates of the vertices on the rectification is the set $\begin{Bmatrix}a + k*b:k\in\mathbb{Z}\end{Bmatrix}$

DEFINITION OF A SPIRAL-LIKE RECTIFICATION
When we look at a rectification, we can calculate an angle at each vertex of the rectification. You can form a triangle from the three points:

*

*$(x, \phi(x))$

*$(x-h, \phi(x-h))$

*$(x+h, \phi(x+h))$
Consider the interior angle of that triangle at the point $(x, \phi(x))$.
Our definition of spiral-like will depend heavily on that angle.
Let $f$ be a continuous function from the real-interval $(a, b)$ to $\mathbb{R}$.
Let $n \in \mathbb{N}$.
Let $XS$ be a mapping from the natural numbers $1$ through $n$ to $\mathbb{R}$ such that $\forall k \in \mathbb{N}\,$ if $1 \leq k \leq (n-1)$ then $XS(k) < XS(k+1)$
Let $\phi$ be a linearly-spaced rectification of function $f$ such that $\forall k \in \mathbb{N}$ if $1 \leq k \leq n$ then $\phi(XS(k)) = f(XS(k))$ and $\phi$ is not differentiable at $x$ if and only if $x$ is taken from the set $\{XS(k): k \in \mathbb{N} \text{ and } 1 \leq k \leq n\}$
Then, $\phi$ is defined to be spiral-like if $\exists C_{1},C_{2} \in \mathbb{R}$ such that $\forall k \in \mathbb{N}$ if $1 \leq k \leq n$ then acute angle in rectification $\phi$ seen at $x = XS(k)$ is $C_{1} + k* C_{2}$
THE INTERPOLATION WE WANT
Let $XS$ be a mapping from the natural numbers $1$ through $n$ to $\mathbb{R}$ such that $\forall k \in \mathbb{N}$ if $1 \leq k \leq n-1$ then $XS(k) < XS(k+1)$
Let $YS$ be a mapping from the natural numbers $1$ through $n$ to $\mathbb{R}$.
We seek a function $f$ from $\mathbb{R}$ to $\mathbb{R}$ which has some special properties:

*

*$\forall k \in \mathbb{N}$ if  $1 \leq k \leq n$ then $f\begin{pmatrix} XS(k) \end{pmatrix} = YS(k)$

*$f$ is NOT a rectification of a differentiable function.

*$f$ approaches a straight line as $x$ tends to $- \infty$

*$f$ approaches a straight line as $x$ tends to $+ \infty$

*$\forall k \in \mathbb{N}$ if  $1 \leq k \leq n-1$ then every linearly-spaced rectification of $f$ on the interval $(k, k+1)$ is spiral like.

Alternatively, if you hold the angles seen at rectification vertices constant, then the length of the rectification-segments would change linearly as you move from one end of the rectification to the other end of the rectification. An affine function could be used to compute the length of the next segment from the current segment.


text:
Q: How to create multiple sub-accounts under a single organization in demo site under single organization i want to create multiple accounts in a single organization in DocuSign Dev environment. It is a demo site . I want to add multiple account like hr , finance . But all should come under a single organization

A: First, you need to create the accounts independently.
You need to create an organization for your account.
Then, you can link them together if you're an organization admin for the one account.


text:
Q: Approximation of the number of partitions of n, denoted p(n) I managed to prove that $p(n)\ge \max_{1\le k\le n}{{n-1\choose k-1}\over k!}$,that wasn't hard. Now I need to use this result to prove that there exists a constant c>0 for which $p(n)\ge e^{c\sqrt n}$ for any $n\in \mathbb{N}$. I tried to use Stirling's approximation here, but didn't get the result I want. Any hints?

A: First find for which $k$ the expression
$$a(n,k) = \frac{1}{k!}\binom{n-1}{k-1} = \frac{(n-1)!}{k!(k-1)!(n-k)!}$$
reaches its maximum. Since $a(n,k) > 0$ for $1 \leqslant k \leqslant n$ and
$$\frac{a(n,k+1)}{a(n,k)} = \frac{n-k}{(k+1)k}$$
we see that
$$a(n,k+1) < a(n,k) \iff n - k < (k+1)k \iff n+1 < (k+1)^2,$$
so the maximum is attained for $k = \lfloor \sqrt{n+1}\rfloor$.
Now recall Stirling's approximation
$$\log m! = \bigl(m + \tfrac{1}{2}\bigr)\log m - m + \log \sqrt{2\pi} + O\biggl(\frac{1}{m}\biggr)$$
and the equivalent
$$\log (m-1)! = \bigl(m - \tfrac{1}{2}\bigr)\log m - m + \log \sqrt{2\pi} + O\biggl(\frac{1}{m}\biggr)\,.$$
Plugging these into
$$\log p(n) \geqslant \log (n-1)! - \log (n-k)! - \log (k-1)! - \log k!$$
yields
\begin{align}
\log p(n)
&\geqslant \bigl(n - \tfrac{1}{2}\bigr) \log n - n + \log \sqrt{2\pi} + O\biggl(\frac{1}{n}\biggr) \\
&\qquad - \bigl(n - k + \tfrac{1}{2}\bigr)\log (n-k) + n - k - \log \sqrt{2\pi} + O\biggl(\frac{1}{n-k}\biggr) \\
&\qquad - \bigl(k - \tfrac{1}{2}\bigr)\log k + k - \log \sqrt{2\pi} + O\biggl(\frac{1}{k}\biggr) \\
&\qquad - \bigl(k + \tfrac{1}{2}\bigr)\log k + k - \log \sqrt{2\pi} + O\biggl(\frac{1}{k}\biggr) \\
&= (k-1)\log n - 2k\log k - \bigl(n - k + \tfrac{1}{2}\bigr)\log \biggl(1 - \frac{k}{n}\biggr) + k - \log (2\pi) + O\biggl(\frac{1}{\sqrt{n}}\biggr)
\end{align}
for $k = \lfloor \sqrt{n+1}\rfloor = \sqrt{n} + O(1)$. With $k^2 = n + O(\sqrt{n})$ and a low-order Taylor expansion of the logarithms this leads to
$$\log p(n) \geqslant 2\sqrt{n} + O(\log n)$$
and hence
$$\liminf_{n \to \infty} \frac{\log p(n)}{\sqrt{n}} \geqslant 2\,,$$
from which
$$a := \inf \: \biggl\{ \frac{\log p(n)}{\sqrt{n}} : n \in \mathbb{N}\setminus \{0\}\biggr\} > 0$$
follows. Thus $p(n) \geqslant e^{c\sqrt{n}}$ holds e.g. for $c = a > 0$.


text:
Q: A question about one of Hartshorne's propositions Hartshorne says that for $S_1,S_2\in A[x_1,x_2,\dots,x_n]$, where $A$ is a commutative ring, $Z(S_1)\cup Z(S_2)=Z(S_1S_2)$.
Shouldn't it be $Z(S_1)\cup Z(S_2)=Z(S_1\cap S_2)$?
We know that $S_1S_2\subseteq S_1\cap S_2$.

A: *

*If $I$ and $I'$ are ideals of some commutative ring, then clearly $(I\cap I')^2 \subseteq I I' \subseteq I\cap I'$.  Therefore also $Z((I\cap I')^2) \supseteq Z(I I') \supseteq Z(I\cap I')$.

*If $J$ is an ideal, then $Z(J^2) = Z(J)$.  Well, $Z$ can mean several slightly different things and you didn't exactly state the context so I have to guess, but if $Z(J)$ stands for the set of prime ideals containing $J$, then the key point is that $J^2 \subseteq \mathfrak{p}$ implies $J \subseteq \mathfrak{p}$ for $\mathfrak{p}$ a prime ideal, which is clear; and if $J$ is an ideal of $k[x_1,\ldots,x_n]$ with $k$ a field, and $Z(J)$ stands for the set of $\underline{x}$ such that $f(\underline{x})=0$ for all $f\in J$, then the key point is that if $f g$ vanishes at some $\underline{x}$ then already one of $f$ or $g$ has to vanish.

*Putting these two remarks together, $Z(I\cap I') = Z(I I')$.

A: No. For example take $S_1 = \left\{x_1\right\}$ and $S_2 = \left\{x_2\right\}$. Then $S_1 \cap S_2 = \emptyset$ and $Z(S_1 \cap S_2) = \mathbb{A}^n \neq Z(x_1) \cup Z(x_2)$.


text:
Q: Converting Java Desktop Application to Web using Applet or Java Web Start I know that I can convert a Swing application to an Applet or a Java Web Start application.  Is it possible to do the same with an application that's not Swing, say Qt using Java?
What I'm really looking for is a UI framework using Java that's as cross-platform as possible and also has a rich set of UI functionality.  Being able to run the application as either a desktop or a Web application would be preferable.

A:
What I'm really looking for is a UI framework using Java that's as cross-platform as possible and also has a rich set of UI functionality.

Assuming a desktop deployment, the three major frameworks are Swing, SWT and JavaFX.
Try the JavaFX Ensemble sample to see if that technology would suit your needs.

I know that I can convert a Swing application to an Applet or a Java Web Start application. Is it possible to do the same with an application that's not Swing, say Qt using Java?

QT is native code that doesn't run on the JVM - it is not a Java UI framework.  Applet and Web Start programs require a Java class as their entry point.  Any use of QT is such a scenario would require a Java <=> QT adaption layer and I am not aware of the existence of any such thing - you would probably need to build it yourself based on a technology like JNI.

Being able to run the application as either a desktop or a Web application would be preferable.

See the JavaFX deployment guide for various JavaFX deployment options and the Swing deployment guide for various Swing deployment options.
The definition of Web application is pretty nebulous.  Here are some distinct scenarios:

*

*You are restricted to just html5 => produce the html on a server to
distribute to the client.

*You want html launching a Java
application => then something like WebStart in combination with the
Java Deployment Toolkit can be used.

*You will be rendering a
JavaFX application inside a browser window => then use a browser embedded app.

There are many pitfalls for embedding java applications is web pages (just use google to discover some of them).

A: What I have done in one of my projects is develop the application as a web application and then generate a installable to distribute my application. This has great benefits:

*

*It can be installed in a server and publicly available. Just as a normal web application.

*It can also be installed in a desktop.

I used "Jetty" to embed the web server in my application and be able to run the application as a stand alone in desktop environment. The slogan of Jetty is "Don't deploy your application in Jetty, deploy Jetty in your application."
Also I used "IzPak" to package my application in a executable JAR for installation. If you want to make that JAR easy to install for people who might not have installed Java you can use launch4j which is a tool that wraps the JAR into an EXE. So it can validate first if the computer has already Java and if not inform the user that he needs to have Java installed to proceed. The only drawback of this is that if you wrap your application in an EXE you are limiting the portability to other platforms, but that's your decision according to the requirements.

A: Java Web Start apps can contain native libraries, so yes you should be able to convert an app using Qt (assuming the bindings exist) to a JWS app.
Applets on the other hand are tricky to make work with anything other than AWT/Swing, since you have no control over the creation of the top-level window.

A: If you want to use Qt you would first have to make Qt bindings for Java as they are not currently functional.
If you want to use Qt bindings from a Java Applet you will need to make your bindings an installable extension which would be a potential security risk unless you know what you are doing. You would also have to get the user to install your extension. Also IcedTea-web which are the FOSS plugin shipping with Linux will not load an extension. So if you want your extension to work on Linux you will have to fork IcedTea-web and make your own plugin.
So the short answer: Stick to Swing.


text:
Q: Prediction failed: Error processing input: Expected string, got dict I've completed the starting tutorial for TensorFlow (https://www.tensorflow.org/get_started/get_started_for_beginners) and made some minor changes to the code to adapt it to my application. The feature columns for my case are the following:
transaction_column = tf.feature_column.categorical_column_with_vocabulary_list(key='Transaction', vocabulary_list=["buy", "rent"])
localization_column = tf.feature_column.categorical_column_with_vocabulary_list(key='Localization', vocabulary_list=["barcelona", "girona"])
dimensions_feature_column = tf.feature_column.numeric_column("Dimensions")
buy_price_feature_column = tf.feature_column.numeric_column("BuyPrice")
rent_price_feature_column = tf.feature_column.numeric_column("RentPrice")

my_feature_columns = [
    tf.feature_column.indicator_column(transaction_column),
    tf.feature_column.indicator_column(localization_column),
    tf.feature_column.bucketized_column(source_column = dimensions_feature_column,
                                        boundaries = [50, 75, 100]),
    tf.feature_column.numeric_column(key='Rooms'),
    tf.feature_column.numeric_column(key='Toilets'),
    tf.feature_column.bucketized_column(source_column = buy_price_feature_column,
                                        boundaries = [1, 180000, 200000, 225000, 250000, 275000, 300000]),
    tf.feature_column.bucketized_column(source_column = rent_price_feature_column,
                                        boundaries = [1, 700, 1000, 1300])
]

After that, I've saved the model so that it can be used in Cloud ML Engine to do predictions.
To export the model I've added the following code (after evaluating the model):
feature_spec = tf.feature_column.make_parse_example_spec(my_feature_columns)
export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec)
servable_model_dir = "modeloutput"
servable_model_path = classifier.export_savedmodel(servable_model_dir, export_input_fn)

After running the code I get the proper model files in my "modeloutput" directory and I create the model in the Cloud (as explained in https://cloud.google.com/ml-engine/docs/tensorflow/getting-started-training-prediction#deploy_a_model_to_support_prediction, "Deploy a model to support prediction")
Once the model version is created I simply try to launch an online prediction using this model with the following command on the Cloud Shell:
gcloud ml-engine predict --model $MODEL_NAME --version v1 --json-instances ../prediction.json

Where $MODEL_NAME is my model's name and prediction.json is a JSON file with the following content:
{"inputs":[
  {
     "Transaction":"rent",
     "Localization":"girona",
     "Dimensions":90,
     "Rooms":4,
     "Toilets":2,
     "BuyPrice":0,
     "RentPrice":1100
  }
  ]
}

However, the prediction fails and I get the following error message:

"error": "Prediction failed: Error processing input: Expected string, got {u'BuyPrice': 0, u'Transaction': u'rent', u'Rooms': 4, u'Localization': u'girona', u'Toilets': 2, u'RentPrice': 1100, u'Dimensions': 90} of type 'dict' instead."

The error is clear, a string is expected instead of a dictionary. If I check my SavedModel SignatureDef I get the following information:
The given SavedModel SignatureDef contains the following input(s):
inputs['inputs'] tensor_info:
  dtype: DT_STRING
  shape: (-1)
  name: input_example_tensor:0
The given SavedModel SignatureDef contains the following output(s):
outputs['classes'] tensor_info:
  dtype: DT_STRING
  shape: (-1, 12)
  name: dnn/head/Tile:0
outputs['scores'] tensor_info:
  dtype: DT_FLOAT
  shape: (-1, 12)
  name: dnn/head/predictions/probabilities:0
Method name is: tensorflow/serving/classify

It's clear that the dtype expected for the input is a string (DT_STRING) but I don't know how to format my input data so that the prediction succeeds. I've tried to write the input JSON in many different ways but I keep getting errors.
If I look at how the prediction is performed in the tutorial (https://www.tensorflow.org/get_started/get_started_for_beginners), I think it's clear that the predict input is passed as a dictionary (predict_x in the tutorial code).
So, where am I wrong? How can I make the prediction with this input data?
Thank you for your time.
EDIT BASED ON ANSWER ------
Following the second suggestion by @Lak, I've updated the code to export the model so it now looks like this:
export_input_fn = serving_input_fn
servable_model_dir = "savedmodeloutput"
servable_model_path = classifier.export_savedmodel(servable_model_dir,
 export_input_fn)
...

def serving_input_fn():
feature_placeholders = {
    'Transaction': tf.placeholder(tf.string, [None]),
    'Localization': tf.placeholder(tf.string, [None]),
    'Dimensions': tf.placeholder(tf.float32, [None]),
    'Rooms': tf.placeholder(tf.int32, [None]),
    'Toilets': tf.placeholder(tf.int32, [None]),
    'BuyPrice': tf.placeholder(tf.float32, [None]),
    'RentPrice': tf.placeholder(tf.float32, [None])
    }
features = {
    key: tf.expand_dims(tensor, -1)
    for key, tensor in feature_placeholders.items()
}
return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)

After that, I've created a new model and fed it the following JSON to get the prediction:
{
   "Transaction":"rent",
   "Localization":"girona",
   "Dimensions":90.0,
   "Rooms":4,
   "Toilets":2,
   "BuyPrice":0.0,
   "RentPrice":1100.0
}

Note that I removed "inputs" from the JSON structure as I received the error "Unexpected tensor name: inputs" when doing the prediction. However, now I get a new, and uglier error:

"error": "Prediction failed: Error during model execution: AbortionError(code=StatusCode.INVALID_ARGUMENT, details=\"NodeDef mentions attr 'T' not in Op index:int64>; NodeDef: dnn/input_from_feature_columns/input_layer/Transaction_indicator/to_sparse_input/indices = WhereT=DT_BOOL, _output_shapes=[[?,2]], _device=\"/job:localhost/replica:0/task:0/device:CPU:0\". (Check whether your GraphDef-interpreting binary is up to date with your GraphDef-generating binary.).\n\t [[Node: dnn/input_from_feature_columns/input_layer/Transaction_indicator/to_sparse_input/indices = WhereT=DT_BOOL, _output_shapes=[[?,2]], _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"]]\")"

I've checked again the SignatureDef and I get the following information:
The given SavedModel SignatureDef contains the following input(s):
  inputs['Toilets'] tensor_info:
      dtype: DT_INT32
      shape: (-1)
      name: Placeholder_4:0
  inputs['Rooms'] tensor_info:
      dtype: DT_INT32
      shape: (-1)
      name: Placeholder_3:0
  inputs['Localization'] tensor_info:
      dtype: DT_STRING
      shape: (-1)
      name: Placeholder_1:0
  inputs['RentPrice'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1)
      name: Placeholder_6:0
  inputs['BuyPrice'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1)
      name: Placeholder_5:0
  inputs['Dimensions'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1)
      name: Placeholder_2:0
  inputs['Transaction'] tensor_info:
      dtype: DT_STRING
      shape: (-1)
      name: Placeholder:0
The given SavedModel SignatureDef contains the following output(s):
  outputs['class_ids'] tensor_info:
      dtype: DT_INT64
      shape: (-1, 1)
      name: dnn/head/predictions/ExpandDims:0
  outputs['classes'] tensor_info:
      dtype: DT_STRING
      shape: (-1, 1)
      name: dnn/head/predictions/str_classes:0
  outputs['logits'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 12)
      name: dnn/logits/BiasAdd:0
  outputs['probabilities'] tensor_info:
      dtype: DT_FLOAT
      shape: (-1, 12)
      name: dnn/head/predictions/probabilities:0
Method name is: tensorflow/serving/predict

Have I gone wrong in some of the steps? Thanks!
NEW UPDATE
I've run a local prediction and it has been succesfully executed, receiving the expected prediction result. Command used:
gcloud ml-engine local predict --model-dir $MODEL_DIR --json-instances=../prediction.json

where MODEL_DIR is the directory containing the files generated on the model training.
So the problem seems to be in exporting the model. Somehow the model exported and used later for prediction is not correct. I've read something about TensorFlow versions possibly being the origin of the problem, but I don't understand. Isn't my whole code executed with the same TF version?
Any ideas regarding this point?
Thanks!

A: The problem is in your serving input function. You are using build_parsing_serving_input_receiver_fn and that function should be used if you are going to send in tf.Example strings:
https://www.tensorflow.org/api_docs/python/tf/estimator/export/build_parsing_serving_input_receiver_fn
Two ways to fix this:

*

*Send in a tf.Example

    example = tf.train.Example(features=tf.train.Features(feature=
       {'transaction': tf.train.Feature(bytes_list=tf.train.BytesList(value=['rent'])),
        'rentPrice': tf.train.Feature(float32_list=tf.train.Float32List(value=[1000.0))
    }))

    string_to_send = example.SerializeToString()

*Change the serving input function so that you can send in JSON:

    def serving_input_fn():
       feature_placeholders = {
                'transaction': tf.placeholder(tf.string, [None]),
                ...
                'rentPrice': tf.placeholder(tf.float32, [None]),
            }
            features = {
                key: tf.expand_dims(tensor, -1)
                for key, tensor in feature_placeholders.items()
            }
       return tf.estimator.export.ServingInputReceiver(features, feature_placeholders)

    export_input_fn = serving_input_fn

A: Issue solved :)
After several experiments I've ended up discovering that I had to create the model using the latest runtime version (1.8):
gcloud ml-engine versions create v2 --model $MODEL_NAME --origin $MODEL_BINARIES --runtime-version 1.8


text:
Q: Using Mockito to test abstract classes I'd like to test an abstract class. Sure, I can manually write a mock that inherits from the class.
Can I do this using a mocking framework (I'm using Mockito) instead of hand-crafting my mock? How?

A: Try using a custom answer.
For example:
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class CustomAnswer implements Answer<Object> {

    public Object answer(InvocationOnMock invocation) throws Throwable {

        Answer<Object> answer = null;

        if (isAbstract(invocation.getMethod().getModifiers())) {

            answer = Mockito.RETURNS_DEFAULTS;

        } else {

            answer = Mockito.CALLS_REAL_METHODS;
        }

        return answer.answer(invocation);
    }
}

It will return the mock for abstract methods and will call the real method for concrete methods.

A: If you just need to test some of the concrete methods without touching any of the abstracts, you can use CALLS_REAL_METHODS (see Morten's answer), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."
(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)
The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use doCallRealMethod() to explicitly call out the concrete method under test. E.g.
public abstract class MyClass {
    @SomeDependencyInjectionOrSomething
    public abstract MyDependency getDependency();

    public void myMethod() {
        MyDependency dep = getDependency();
        dep.doSomething();
    }
}

public class MyClassTest {
    @Test
    public void myMethodDoesSomethingWithDependency() {
        MyDependency theDependency = mock(MyDependency.class);

        MyClass myInstance = mock(MyClass.class);

        // can't do this with CALLS_REAL_METHODS
        when(myInstance.getDependency()).thenReturn(theDependency);

        doCallRealMethod().when(myInstance).myMethod();
        myInstance.myMethod();

        verify(theDependency, times(1)).doSomething();
    }
}

Updated to add:
For non-void methods, you'll need to use thenCallRealMethod() instead, e.g.:
when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();

Otherwise Mockito will complain "Unfinished stubbing detected."

A: What really makes me feel bad about mocking abstract classes is the fact, that neither the default constructor YourAbstractClass() gets called (missing super() in mock) nor seems there to be any way in Mockito to default initialize mock properties (e.g List properties with empty ArrayList or LinkedList).
My abstract class (basically the class source code gets generated) does NOT provide a dependency setter injection for list elements, nor a constructor where it initializes the list elements (which I tried to add manually).
Only the class attributes use default initialization:
private List<MyGenType> dep1 = new ArrayList<MyGenType>();
private List<MyGenType> dep2 = new ArrayList<MyGenType>();

So there is NO way to mock an abstract class without using a real object implementation (e.g inner class definition in unit test class, overriding abstract methods) and spying the real object (which does proper field initialization).
Too bad that only PowerMock would help here further.

A: You can extend the abstract class with an anonymous class in your test.
For example (using Junit 4):
private AbstractClassName classToTest;

@Before
public void preTestSetup()
{
    classToTest = new AbstractClassName() { };
}

// Test the AbstractClassName methods.

A: class Dependency{
  public void method(){};
}

public abstract class My {

  private Dependency dependency;
  public abstract boolean myAbstractMethod();

  public void myNonAbstractMethod() {
    // ...
    dependency.method();
  }
}

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

  @InjectMocks
  private My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
  // we can mock dependencies also here
  @Mock
  private Dependency dependency;

  @Test
  private void shouldPass() {
    // can be mock the dependency object here.
    // It will be useful to test non abstract method
    my.myNonAbstractMethod();
  }
}

A: The following suggestion lets you test abstract classes without creating a "real" subclass - the Mock is the subclass and only a partial mock.
Use Mockito.mock(My.class, Answers.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.
Example:
public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Answers.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

Note: The beauty of this solution is that you do not have to implement the abstract methods. CALLS_REAL_METHODS causes all real methods to be run as is, as long as you don't stub them in your test.
In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiable subclass of your abstract class.

A: Mockito allows mocking abstract classes by means of the @Mock annotation:
public abstract class My {

    public abstract boolean myAbstractMethod();

    public void myNonAbstractMethod() {
        // ...
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyTest {

    @Mock(answer = Answers.CALLS_REAL_METHODS)
    private My my;

    @Test
    private void shouldPass() {
        BDDMockito.given(my.myAbstractMethod()).willReturn(true);
        my.myNonAbstractMethod();
        // ...
    }
}

The disadvantage is that it cannot be used if you need constructor parameters.

A: You can achieve this by using a spy (use the latest version of Mockito 1.8+ though).
public abstract class MyAbstract {
  public String concrete() {
    return abstractMethod();
  }
  public abstract String abstractMethod();
}

public class MyAbstractImpl extends MyAbstract {
  public String abstractMethod() {
    return null;
  }
}

// your test code below

MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
doReturn("Blah").when(abstractImpl).abstractMethod();
assertTrue("Blah".equals(abstractImpl.concrete()));

A: Assuming your test classes are in the same package (under a different source root) as your classes under test you can simply create the mock:
YourClass yourObject = mock(YourClass.class);

and call the methods you want to test just as you would any other method.
You need to provide expectations for each method that is called with the expectation on any concrete methods calling the super method - not sure how you'd do that with Mockito, but I believe it's possible with EasyMock.
All this is doing is creating a concrete instance of YouClass and saving you the effort of providing empty implementations of each abstract method.
As an aside, I often find it useful to implement the abstract class in my test, where it serves as an example implementation that I test via its public interface, although this does depend on the functionality provided by the abstract class.

A: Mocking frameworks are designed to make it easier to mock out dependencies of the class you are testing. When you use a mocking framework to mock a class, most frameworks dynamically create a subclass, and replace the method implementation with code for detecting when a method is called and returning a fake value.
When testing an abstract class, you want to execute the non-abstract methods of the Subject Under Test (SUT), so a mocking framework isn't what you want.
Part of the confusion is that the answer to the question you linked to said to hand-craft a mock that extends from your abstract class. I wouldn't call such a class a mock. A mock is a class that is used as a replacement for a dependency, is programmed with expectations, and can be queried to see if those expectations are met.
Instead, I suggest defining a non-abstract subclass of your abstract class in your test. If that results in too much code, than that may be a sign that your class is difficult to extend.
An alternative solution would be to make your test case itself abstract, with an abstract method for creating the SUT (in other words, the test case would use the Template Method design pattern).

A: You can instantiate an anonymous class, inject your mocks and then test that class.
@RunWith(MockitoJUnitRunner.class)
public class ClassUnderTest_Test {

    private ClassUnderTest classUnderTest;

    @Mock
    MyDependencyService myDependencyService;

    @Before
    public void setUp() throws Exception {
        this.classUnderTest = getInstance();
    }

    private ClassUnderTest getInstance() {
        return new ClassUnderTest() {

            private ClassUnderTest init(
                    MyDependencyService myDependencyService
            ) {
                this.myDependencyService = myDependencyService;
                return this;
            }

            @Override
            protected void myMethodToTest() {
                return super.myMethodToTest();
            }
        }.init(myDependencyService);
    }
}

Keep in mind that the visibility must be protected for the property myDependencyService of the abstract class ClassUnderTest.

A: PowerMock's Whitebox.invokeMethod(..) can be handy in this case.


text:
Q: Create Multidimensional Array from MySQL Query using Codeigniter Some background.  I have two MySQL tables derived from PubMed XML files.  The pubauth table has all authors for a given reference and the pubmed table has all the unique pubmed info.  There are n+1 authors for each pubmed record. What I think I need is this:
Array(
    [id]=> Array([id]=>1
        [PMID]=>123456
        Array(
            [pubauth]=>Array(
                [pubauth_id]=>1
                [LastName]=>Chen
            )
        )
    )
)

My model is:
$this->db->select( 'pubmed.id, PMID,  pubauth.id AS pubauth_id, LastName');
$this->db->from( 'pubmed' );
$this->db->join( 'pubauth', 'pubmed_id = pubmed.id', 'left outer' );
$this->db->where( 'idecm',$keyword );
$query = $this->db->get();
$temp_result = array();
foreach ( $query->result_array() as $row ){
    $temp_result[] = array(
           'pubmed_id' => $row['id'],
           'PMID'      => $row['PMID'],
           'LastName'  => $row['LastName'],
           'pubauth_id'=> $row['pubauth_id']
   );
}

This returns each row as an array in $temp_result.  What I am shooting for is similar to this question:  PHP MYSQL multidimensional array.   replacing the foreach in my Model according to the answer, I have:
foreach ( $query->result_array() as $row )
{
     $r_array[$row["id"]]=array();

     $row_st = (string) $row["pubauth_id"];
     $r_array[$row["id"]][] = $row_st;
}

foreach ($r_array as $id => & $data) {
// Start with just ID
$newarray = array(
  "id" => $id
);

if (count($data) == TRUE)
  $newarray["pubauth_id"] = & $data;

$finalarray[] = & $newarray;
print_r( $finalarray);
unset($newarray);
}

This array I get from this is
Array ( [0] => Array ( [id] => 1 [pubauth_id] => Array ( [0] => 7 ) ) ) Array ( [0] => Array ( [id] => 1 [pubauth_id] => Array ( [0] => 7 ) ) [1] => Array ( [id] => 2 [pubauth_id] => Array ( [0] => 17 ) ) )

Data it is only the last row and LastName is missing.  Sorry for rambling but this has me flumoxed.  I can work with 2D arrays but cannot seem to wrap my head around this one.  The output I am shooting for in the View would look like a PubMed reference; Author1...Author_n, Title, Data, Journal, Volume, Issue, Page.  All I can get now is a Title, Data, Journal, Volume, Issue, Page for each Author as a row.  Any help will be greatly appreciated.

A: I have solved my problem.  This probably is not the most efficient way to do this since it requires two sequential MySQL quires to get the data.  The solution was in part from this post: Nested foreach().  My new model:
//Retrieve pubmed record
$this->db->select( 'pubmed.id, PMID);
$this->db->from( 'ecmnote' );
$this->db->join( 'pubmed', 'pubmed.idecm = ecmnote.idecm', 'left' );
$this->db->where( 'ecmnote.idecm',$key );
$query = $this->db->get();

//Retrieve associated authors.
$this->db->select( 'pubmed.id AS pubmed_id, LastName);
$this->db->from( 'ecmnote' );
$this->db->join( 'pubmed', 'pubmed.idecm = ecmnote.idecm', 'left' );
$this->db->join( 'pubauth', 'pubmed_id = pubmed.id');
$this->db->where( 'pubmed.idecm',$key );
$auth_query = $this->db->get();

$pub = array();
$auth = array();

foreach ($auth_query->result_array() as $r){
     $auth[] = array (
               'pubmed_id'=> $r['pubmed_id'],
               'LastName' => $r['LastName']
                );
}

 foreach ( $query->result_array() as $row ){
      $pub[] = array(
               'PMID' => $row["PMID"],
               'authors' => $auth
               );
}
return $pub;

From the controller I pass this to a Smarty template to view it.  My View is this:

        {foreach $data as $apub}

                    {assign var = "title" value = '. '|cat:$apub['ArticleTitle']|cat:' ('|cat:$apub['PubDate']|cat:') '|cat:$apub['Title']|cat:'. '|cat:$apub['Volume']|cat:'('|cat:$apub['Issue']|cat:')'|cat:$apub['MedlinePgn'] }

                    {foreach $apub as $svar=>$sval}
                        {if ($svar === "authors")}
                            {foreach $sval as $apeople}
                                {assign var = "sauthors" value = ' '|cat:$apeople['LastName']|cat:' '|cat:$apeople['Initials'] scope="global"}

                                {$sauthors}

                            {/foreach}
                        {/if}
                    {/foreach}

                {$title}

Is there a way to make this more efficient?  When I combine the MySQL query into one I get a multidimensional array that has each author plus the pubmed table as its own array.  I could never get that to display correctly.

A: I get the result I needed now.  Still not sure this is the most efficient way since I cannot think of a method to use only one DB query.  I had to change my Smarty template slightly.

        {foreach $data as $apub}

                    {assign var = "title" value = '. '|cat:$apub['ArticleTitle']|cat:' ('|cat:$apub['PubDate']|cat:') '|cat:$apub['Title']|cat:'. '|cat:$apub['Volume']|cat:'('|cat:$apub['Issue']|cat:')'|cat:$apub['MedlinePgn'] }

                    {foreach $apub['authors'] as $apeople}
                        {assign var = "sauthors" value = ''}
                        {if $apub["id"] == $apeople["pubmed_id"]}
                            {assign var = "authors" value = ' '|cat:$apeople['LastName']|cat:' '|cat:$apeople['Initials'] scope="global"}
                            {$authors}
                        {/if}
                    {/foreach}
                    {$title}

{/tr}

This displays Author1 ... AuthorN Title Year Journal Volume Issue Pages.


text:
Q: parsing finacle core banking xml response in python I am trying to get the value of status of response and available balance from xml returned from finacle core banking.
xml is at:
https://pastebin.com/8bvpuUGp

I'm trying to get the value as below, but nothing appeared.
xroot = ET.fromstring(xml)
for ab in xroot.findall('AVAIL'):
    bal = ab.find('AVAIL').text
    print(bal)

A: As far as I understand you want to get the balance for this 'AVAIL' query.
You seem to be referring to a tag name, though it's a text contained within tag. Furthermore it does not have any child items, so your search does not work.
I'm not an expert in xml, but here is a working code I've come up with:
import re
import xml.etree.ElementTree as ET

term = 'AVAIL'

xroot = ET.fromstring(xml)
el = [element for element in xroot.iter() for child in element if child.text == term]
for i in [element for element in el[0].iter() if element.text != term]:
    if len(i.text) > 1:
        print(re.sub('{.*}', '', i.tag), i.text)

Otput:
amountValue 16299.37
currencyCode NPR

Here I find a child that contains text "AVAIL", than accesses a parent element and cycle though it's children to find everything except the query. Seems like this is the info you were looking for.
Update

i got value using if(i.text != 'NPR'): print(float(i.text)). Would you please also find if Status == 'SUCCESS'

If you only need the amount we can skip filtering out != text and search for the tag instead.
This and checking for status will result in:
import re
import xml.etree.ElementTree as ET

xroot = ET.fromstring(xml)

statuses = [el for el in xroot.iter() if re.sub('{.*}', '', el.tag) == 'Status']
success = True if any(el.text == 'SUCCESS' for el in statuses) else False

if success:
    bal = [el for el in xroot.iter() for ch in el if ch.text == 'AVAIL']
    for i in [el for el in bal[0].iter() if re.sub('{.*}', '', el.tag) == 'amountValue']:
        print(float(i.text))

Output:
16299.37


text:
Q: Updating href in url redirect htaccess I am trying to show the content of one domain with the url of another. So for example if I go to example1.com I would like to show the content of example2.com without changing the url name.
What I have right now is the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example1.com
RewriteRule ^(.*) example2.com/$1 [P]

This works great, but the next step to this that I would like is for internal hrefs of example2.com to remain as example1.com in the url.
So if on the copied page there would be a link to example2.com/about I would like for it to become example1.com/about instead.
Is this possible with htaccess? if not what would be the best way to approach this.
P.S. This is a WordPress site - so if anyone has a good WP specific way of achieving the above that would be fine too.
Thanks in advance!


text:
Q: Python - pip pywin32 fails Im trying to install pywin32 currently in a venv, but it seems to be failing - at least, pywin32 is not located in site-packages afterwards.
After entering pip install pywin32, i do not get an error - instead, it says Downloading and the URL, and afterwards i return to the shell - no error, no affirmation that the installation succeeds.
HOWEVER... the shell turns red.

Ive never seen such behavior, and the red color doesnt go away without having to restart the shell.
Why does the installation fail AND the shell turns red?

A: The color turns red because it is dying in the middle of running. Entering the command Color 07 will fix this.
Do you have admin access? Is your virtualenv activated?

A: To complete this question ;-)
Try to create a new virtualenv with python 3.6:
$ mkvirtualenv testPyWin32 --python=python3.6
$ pip install pywin32