text:
Q: An example of functional programming in scala I'm studying scala. It's very promising, thanks to Odersky and all the other authors for their great work.
I took a euler problem (http://projecteuler.net/) to have a more-then-minimal example. And I'm trying to go the functional way. So this is not a "please answer me immediatly or my boss will kill me" but a "please if you've got time, can you help a imperative language programmer to take a journey in the functional world?"
Problem: I want a class for poker hands. A poker Hand is composed by a number of Card, from 0 to 5. I'd like to build the list of Cards one and for all, that is: my Hand class will be immutable, if I want to add a card, then I create a new Hand object.
So I need a collection of Card that can be created as "val", not as var.
First step: constructors, one for each number of cards. But Card's collection is handled in each constructor, so I must have it as var!
Here's the code, Card class is simply a Suit and a Value, passed to constructor as a string ("5S" is the 5 of spades):
class Hand(mycards : List[Card]) {
  // this should be val, I guess
  private var cards : List[Card] = {
    if (mycards.length>5)
      throw new IllegalArgumentException(
        "Illegal number of cards: " + mycards.length);
    sortCards(mycards)
  }

  // full hand constructor
  def this(a : String, b : String, c : String, d : String, e : String) = {
      this(Nil)

      // assign cards
      val cardBuffer = new ListBuffer[Card]()
      if ( a!=null ) cardBuffer += new Card(a)
      if ( b!=null ) cardBuffer += new Card(b)
      if ( c!=null ) cardBuffer += new Card(c)
      if ( d!=null ) cardBuffer += new Card(d)
      if ( e!=null ) cardBuffer += new Card(e)
      cards = sortCards(cardBuffer.toList)
  }
  // hand with less then 5 cards
  def this(a : String, b : String, c : String, d : String) = this(a,b,c,d,null)
  def this(a : String, b : String, c : String) = this(a, b, c, null)
  def this(a : String, b : String) = this(a, b, null)
  def this(a : String) = this(a, null)
  def this() = this(Nil)

/* removed */
}

Do you know how to make it the true functional way?
Thanks.
PS: if you really want to know, it's problem 54.

A: My answer is not about functional aspect of scala, but your code is possible to write shortly using scala sugar:
class Hand(val mycards: List[Card]) {
  require (mycards.size <= 5,"can't be more than five cards")
  def this(input: String*) = {
    this(input.map(c => new Card(c)).toList)
  }
}

input: String* in auxiliary constructor says that you can have variable number of arguments (even thousand of strings).
I'm getting input and invoke creation for each new Card with map function, and then pass result to parent constructor which has it's own requirement.
(BTW, mapping from string to Card can be done anonymously, in that manner: this(input.map(new Card(_)).toList))
class Hand(val mycards: List[Card]) {...
Is equable to
class Hand(cards: List[Card]) {
val mycards = cards
...

From now on, if you will try to create more than five cards in hand you'll get java.lang.IllegalArgumentException:
scala> class Card(s: String) {println("Im a :"+s)}
defined class Card

scala> new Hand("one","two","three","four","five","six")
Im a :one
Im a :two
Im a :three
Im a :four
Im a :five
Im a :six
java.lang.IllegalArgumentException: requirement failed: can't be more than five card
    at scala.Predef$.require(Predef.scala:157)
    at Hand.<init>(<console>:9)

A: Well, the the var in the code below comes from you not initializing cards from the main constructor:
// this should be val, I guess
private var cards : List[Card] = {
  if (mycards.length>5)
    throw new IllegalArgumentException(
      "Illegal number of cards: " + mycards.length);
  sortCards(mycards)
}

So what you need to do is fix the secondary constructor:
// full hand constructor
def this(a : String, b : String, c : String, d : String, e : String) = {
    this(Nil)

    // assign cards
    val cardBuffer = new ListBuffer[Card]()
    if ( a!=null ) cardBuffer += new Card(a)
    if ( b!=null ) cardBuffer += new Card(b)
    if ( c!=null ) cardBuffer += new Card(c)
    if ( d!=null ) cardBuffer += new Card(d)
    if ( e!=null ) cardBuffer += new Card(e)
    cards = sortCards(cardBuffer.toList)
}

THe problemn is simple: you want a list of cards formed by non-null Strings. If I were you, I'd just avoid passing nulls, but... Anyway, the best way to handle that is to convert this into options. The conversion is simple: Option(a) will return Some(a) is a is not null, and None if it is. If you compose a list of that, you can then flatten it to remove the None and convert Some(a) back into a. In other words:
def this(a : String, b : String, c : String, d : String, e : String) =
    this(List(a, b, c, d, e).map(Option(_)).flatten.map(Card(_)))

A: Because in this example you are only allowed to use five cards I would check this at compile time with the use of a Tuple5:
type HandType = (ACard, ACard, ACard, ACard, ACard)
case class Hand(h: HandType)

abstract class ACard {
  def exists: Boolean
}
case class Card(value: Int, color: Color) extends ACard {
  def exists = true
}
case object NoCard extends ACard {
  def exists = false
}

abstract class Color(val c: Int)
case object H extends Color(1)
case object C extends Color(2)
case object S extends Color(3)
case object D extends Color(4)
case object NoColor extends Color(0)

implicit def tuple2Card(t: (Int, Color)) = Card(t._1, t._2)

val h1 = Hand((Card(4, H), Card(6, S), Card(2, S), Card(8, D), NoCard))
val h2 = Hand((4 -> H, 6 -> S, 2 -> S, 8 -> D, NoCard))

println(h1)
println(h2)
h1.h.productIterator foreach { c => println(c.asInstanceOf[ACard].exists) }

Of course in another example when there can be an unspecific number of elements you need to check them at runtime. productIterator only returns a Iterator[Any] but when you use your cards directly by the field-identifiers (_1 .. _5) you will get an ACard.

A: Firstly, null is evil, use Option instead. Secondly, Scala supports default parameters. So instead of creating all the constructors, you might just wanna use one of them like this:
def this(a: String = null, ..., e: String = null) = ...

or with Option, which is safer.
def this(a: Option[String] = None, ..., e: Option[String] = None) = {
   this(Nil)

   val cardBuffer = new ListBuffer[Card]()
   a foreach { cardBuffer += new Card(_) }
   b foreach { cardBuffer += new Card(_) }
   c foreach { cardBuffer += new Card(_) }
   d foreach { cardBuffer += new Card(_) }
   e foreach { cardBuffer += new Card(_) }
   cards = sortCards(cardBuffer.toList)
}

So the cards are only added to the buffer if they "exist".

A: First, we need to fix a compile error in your cards field definition.
Note that in Scala you usually don't have to declare fields. Main constructor parameters already are fields! So, this can be written simpler:
class Hand(cards : List[Card]) {
  if (cards.length>5)
      throw new IllegalArgumentException(
        "Illegal number of cards: " + mycards.length);

Now we have mutability problem. If you want to program in functional style, everything should be immutable, so the "full hand constructor" is not functional at all: it has 6 side-effecting operations, last of which does not compile.
In functional setting, an object can't be modified after its constructor has terminated, so all the code after this(Nil) is useless. You already said that cards is Nil, what else do you want?! So, all the computations have to happen before the main constructor call. We'd like to remove this(Nil) from the top and add this(sortCards(cardBuffer.toList)) to the bottom. Unfortunately, Scala does not allow that. Fortunately, it allows more options to achieve the same than java: first, you can use a nested block like this:
this({
  val cardBuffer = ... /* terrible imperativeness */
  sortCards(cardBuffer.toList)
})

second, you can use apply method instead of a constructor:
object Hand {
  def apply(a : String, b : String, c : String, d : String, e : String) = {
    val cardBuffer = ... /* terrible imperativeness */
    new Hand(sortCards(cardBuffer.toList))
  }
}

Now, let's start getting rid of imperative ListBuffer. First improvement would be to use var of type List[Card]. Making mutability more local will help to remove it later:
// assign cards
var cards = Nil
if ( e!=null ) cards = new Card(e) :: cards
if ( d!=null ) cards = new Card(d) :: cards
if ( c!=null ) cards = new Card(c) :: cards
if ( b!=null ) cards = new Card(b) :: cards
if ( a!=null ) cards = new Card(a) :: cards
sortCards(cards)

Okay, now we can see what exactly we are mutating and can easily remove that mutability:
val fromE = if ( e!=null ) new Card(e) :: Nil else Nil
val fromD = if ( d!=null ) new Card(d) :: fromE else fromE
val fromC = if ( c!=null ) new Card(c) :: fromD else fromD
val fromB = if ( b!=null ) new Card(b) :: fromC else fromC
val fromA = if ( a!=null ) new Card(a) :: fromB else fromB
sortCards(fromA)

Now we have a fair amount of code duplication. Let's remove that in a brute-force way (find a long duplicating piece of code and extract function)!
def prependCard(x : String, cards : List[Card]) =
  if ( x!=null ) new Card(x) :: cards else cards
val cards = prependCard(a, prependCard(b,
              prependCard(c, prependCard(d,
                prependCard(e, Nil)
              ))
            ))
sortCards(cards)

Next, very important, transformation would be to replace nullable references with the values of Option type, or remove the empty card concept altogether.
Update:
As requested, I am adding an example of usage of the apply method. Notice that it is declared in object Hand, not class Hand, so it doesn't need an instance of the class (it's similar to static method in java). We just apply the object to parameters: val hand = Hand("5S", "5S", "5S", "5S", "5S").

A: Attempt using varargs, overloaded + operator, repeated addition in constructor, and Set to eliminate duplicate cards.
package poker

class Hand(private val cards:Set[Card] = Set.empty[Card]) {
  def + (card:Card) = {
    val hand = new Hand(cards + card)
    require(hand.length > length, "Card %s duplicated".format(card))
    require(hand.length <= Hand.maxLength, "Hand length > %d".format(Hand.maxLength))
    hand
  }
  def length = cards.size
  override def toString = cards.mkString("(", ",", ")")
}

object Hand {
  val maxLength = 5
  def apply(cards:Card*):Hand = cards.foldLeft(Hand())(_ + _)
  private def apply() = new Hand()
}

//-----------------------------------------------------------------------------------------------//

class Card private (override val toString:String)

object Card {
  def apply(card:String) = {
    require(cardMap.contains(card), "Card %s does not exist".format(card))
    cardMap(card)
  }

  def cards = cardMap.values.toList

  private val cardMap = {
    val ranks = Range(2,9).inclusive.map { _.toString } ++ List("T", "J", "Q", "K", "A")
    val suits = List("c","d","h","s")
    (for(r <- ranks; s <- suits) yield (r + s -> new Card(r + s))).toMap
  }
}

//-----------------------------------------------------------------------------------------------//

object Test extends App {
  Array("1f", "Ac").foreach { s =>
    try {
      printf("Created card %s successfully\n",Card(s))
    } catch {
      case e:Exception => printf("Input string %s - %s \n", s, e.getMessage)
    }
  }
  println

  for(i <- 0 to 6) {
    val cards = Card.cards.slice(0, i)
    makeHand(cards)
  }
  println

  val cards1 = List("Ac","Ad","Ac").map { Card(_) }
  makeHand(cards1)
  println

  val hand1 = Hand(List("Ac","Ad").map { Card(_) }:_* )
  val card = Card("Ah")
  val hand2 = hand1 + card
  printf("%s + %s = %s\n", hand1, card, hand2)

  def makeHand(cards:List[Card]) =
    try {
      val hand = Hand(cards: _*)
      printf("Created hand %s successfully\n",hand)
    } catch {
      case e:Exception => printf("Input %s - %s \n", cards, e.getMessage)
    }
}


text:
Q: How to get sum of rupees of current year and previous year withine single query? I want to select sum of current year rupees and previous year rupees material wise. Following is my table fields:
   |Material_Number|Material_name|Date      |Rupees   |
   |1              |abc          |2014-02-01|1.20,000 |
   |1              |abc          |2014-02-02|50,000   |
   |1              |abc          |2013-05-05|1,50,000 |
   |5              |pqr          |2012-01-05|20,000   |
   |2              |xyz          |2013-05-04|10,000   |
   |2              |xyz          |2014-01-04|10,100   |
   ----------------------------------------------------

I want to to display material wise sum of rupees of current year and previous year. following is my table structure that i want:
  ---------------------------------------------------
  |Previous_Year_sum| Material_name|Current Year_sum|
  ---------------------------------------------------
  |1,20,000         | abc          | 1,50,000       |
  ---------------------------------------------------

A: Try this use SUM() with CASE condtions
SELECT
SUM(CASE WHEN YEAR(`Date`) = YEAR(NOW()) -1 THEN
    REPLACE (Rupees, ',', '')
    ELSE 0 END )
Previous_Year_sum,
Material_name,
SUM(CASE WHEN YEAR(`Date`) = YEAR(NOW()) THEN
REPLACE (Rupees, ',', '')
    ELSE 0 END )current_year
FROM `Table1`
GROUP BY Material_name

See Demo Here

A: select YEAR(Date) as year , SUM(rupees), material_name from test group by material_name, year;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is drawing to an MTKView or CAMetalLayer required to take place on the main thread? It's well known that updating the user interface in AppKit or UIKit is required to take place on the main thread. Does Metal have the same requirement when it comes to presenting a drawable?
In a layer-hosted NSView that I've been playing around with, I've noticed that I can call [CAMetalLayer nextDrawable] from a dispatch_queue that is not the main_queue. I can then update that drawable's texture as usual and present it.
This appears to work properly, but I find that rather suspicious. Unless I've overlooked something in the documentation, I can find no mention of Metal's main thread requirements (either for, or against).
(I'm testing on macOS 10.13, but I would assume the main thread requirements would be the same for iOS as well...?)

A: It is safe to draw on background threads. The docs for -nextDrawable say:

Calling this method blocks the current CPU thread until a new drawable is available.

(Emphasis added.) If it could only be called on the main thread, that would probably not be so generalized. Also, Apple's general advice is to avoid blocking the main thread, so you'd think they would call out that fact in some way here, such as advising you not to call it unless you're pretty sure it won't block.
For how the drawable is used (rather than obtained), note that a typical use case is to call the command buffer's -presentDrawable: method. That method is a convenience for adding a scheduled handler block (as via -addScheduledHandler:) which will then call -present on the drawable. It is unspecified what thread or queue the handler blocks will be called on, which suggests that there's no promise that the -present call on the drawable will happen on the main thread.
And even after that, the actual presentation of the drawable to the screen is not synchronous within the call to -present. The drawable waits until any commands that render or write to its texture are completed and only then presents to the screen. It's not specified how that asynchronicity is achieved, but it further suggests that it doesn't matter what thread -present is called on.
There's a bit of discussion about multi-threading in the Metal Programming Guide, although it's not quite as direct as one might hope. See especially the section on Multiple Threads, Command Buffers, and Command Encoders. Note that there's a discussion of command buffers being filled by background threads and no specific warning about working with drawables. Again, it's sort of argument by lack of evidence, but I think it's clear. They do call out that only a single thread may act on a given command buffer at a time, so they are considering thread safety questions.


text:
Q: How to use TGMCircle? I am having some issues when trying to plot a Marker and for some cases a Circle. The problem itself is about how to do that with the proper manner.
Here is the flow I am using:

*

*set GMap.RequiredProp.Center values

*on the AfterPageLoaded event I will wait the First to be false value so I set my GMMarker and GMCircle (this one as needed). I am using one design time object for the Marker and the Circle, so I only to change it´s values.

*When I get a new information, such Lat/Lon, I set it´s visibility to false, apply the new values and set it again to true.
Also, to ensure that the new position will appear centered in the map, after the first load I set a flag so next time I will use the GMMap1.PanTo() do force center. If I don't use that, the map will no be centered and if I use I have some issues when using the mouse to pan, and sometimes the Circle gets very huge, not respecting the value of Radius...
I will appreciate any reply about that.

A: To center the map on a figure, you can use the CenterMapTo method that have all the figures (for TMarker is CenterMapToMarker).
Regards


text:
Q: Efficient way to find the nearest point from a set of points to the touched point inbetween a range? I have an array of CGPoints which are used to drawn a Catmull-Rom bezierpath using CGPoint interpolation by jnfisher  What I want is to choose the nearest point on the path to the touch point when user touches anywhere inside a range around any point on the path. That range is specified as an imaginary square containing the point on the path with a tolerance before and after every point on the path along X and Y axis. My strategy is to 1. Set a tolerance for each point on the path which will observe if the location of touch is inside the square with these sides on X Axis:(discoveryPoint.x - tolerance to discoveryPoint.x + tolerance) and on Y axis:(discoveryPoint.y - tolerance to discoveryPoint.y + tolerance. 2.Calculate the distance the between the touched point and all the points in my array which contain the touched point inside their square. 3. choose the minimum amount from distances. 4. find the point that has the least distance from the touched point. Is there any easier and more efficient way? I highly appreciate any help.Thanks in advance.
    -(void)drawRect:(CGRect)rect{
           self.modifiablePath = [UIBezierPath interpolateCGPointsWithCatmullRom:self.pointsArray closed:YES alpha:0.9];
           self.modifiablePath.lineWidth = 20.0;
           [[UIColor yellowColor] setStroke];
           [self.modifiablePath stroke];
    }
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
           {

        CGPoint touchedPoint = [[touches anyObject]locationInView:self];
        CGPoint discoveryPoint;
        CGFloat tolerance = 20;
        int numOfPointsWithMinDistance=0;
        NSDictionary* pointsWithMinDistanceWithKeys = [NSDictionary new];
        NSDictionary* minDistancesWithKeys = [NSDictionary new];
        // Had to Create these two arrays because there's no such thing as [NSDictionary objectAtIndex:]
        NSArray *pointsWithMinDistancesArray = [NSArray new];
        NSArray *minDistanceArray = [NSArray new];

        for (NSValue * cgpointVal in self.pointsArray){
            discoveryPoint = cgpointVal.CGPointValue;

            if (fabs(touchedPoint.x - discoveryPoint.x)<tolerance && fabs(touchedPoint.y - discoveryPoint.y)<tolerance) {
                numOfPointsWithMinDistance++;
                //Adding the points which touchedPoint is inside their range(Square).
                [pointsWithMinDistanceWithKeys setValue:[NSValue valueWithCGPoint:discoveryPoint] forKey:[NSString stringWithFormat:@"%d",numOfPointsWithMinDistance]];

                //Calculating the distance between points with touchedPoint in their range(Square) and adding them to an array.
                CGFloat distance = hypotf(touchedPoint.x - discoveryPoint.x, touchedPoint.y - discoveryPoint.y);
                [minDistancesWithKeys setValue:[NSNumber numberWithFloat:distance] forKey:[NSString stringWithFormat:@"%d",numOfPointsWithMinDistance]];
            }
        }
        //Finding the key for minimum distance between all distances to the touchedPoint.
        minDistanceArray = [minDistancesWithKeys allValues];
        pointsWithMinDistancesArray = [pointsWithMinDistanceWithKeys allValues];

        CGFloat k = [[minDistanceArray objectAtIndex:0] floatValue];
        int keyOfPointWithMinDistance =0;
        for (unsigned i = 1; i <[minDistanceArray count]; i++){

            if([[minDistanceArray objectAtIndex:i] floatValue] < k){
                k = [[minDistanceArray objectAtIndex:i] floatValue];
                keyOfPointWithMinDistance=i;
            }else{
                keyOfPointWithMinDistance=0;
            }
        }
        //Getting the nearest CGPoint value with the smallest distance to the touchedPoint.
        NSValue * valueOfNearestPoint =[pointsWithMinDistancesArray objectAtIndex:keyOfPointWithMinDistance];
        CGPoint nearestPointToTouchedPoint =valueOfNearestPoint.CGPointValue;
}

A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    CGPoint touchedPoint = [[touches anyObject]locationInView:self];
    CGPoint discoveryPoint;
    CGFloat tolerance = 20;
    // Had to Create these two arrays because there's no such thing as [NSDictionary objectAtIndex:]
    NSArray *pointsArray;

    CGFloat keyOfPointWithMinDistance = -1;
    CGPoint nearestPointToTouchedPoint = CGPointZero;
    Int index = 0;
    Int keyIndex = NSNotFound;

    for (NSValue * cgpointVal in self.pointsArray){

        discoveryPoint = cgpointVal.CGPointValue;

        if (fabs(touchedPoint.x - discoveryPoint.x)<tolerance && fabs(touchedPoint.y - discoveryPoint.y)<tolerance) {
            //Calculating the distance between points with touchedPoint in their range(Square) and adding them to an array.
            CGFloat distance = hypotf(touchedPoint.x - discoveryPoint.x, touchedPoint.y - discoveryPoint.y);

            if (keyOfPointWithMinDistance == -1 || keyOfPointWithMinDistance < distance) {
                keyOfPointWithMinDistance = distance;
                nearestPointToTouchedPoint = discoveryPoint;
                keyIndex = index;
            }

            index++;
        }
    }

    //Update self.pointsArray using keyIndex

    if keyIndex != NSNotFound {

    }

}


text:
Q: Ubuntu Linux - Permissions - can I have all perm's to another users files? I have www-data (apache) and craig (me) as users on this Ubuntu 9.04 machine.
So I have a bunch of files that belong to the user 'www-data', but I can't write to them without either:

*

*being root

*chmod'ing the files so they are world-writeable

*or chown'ing them so they are in my user group, then chmod'ing them so they are group-writeable.

Is there anything I can do so that my user (craig) by default has access to all of www-data's files as if they were my own files?
Perhaps I'm looking at the problem the wrong way - in which case, how should I be doing this?
Thanks!

A: You can add your user to the group www-data - that would give your access without giving every user on the system access (which is a dangerous thing to do especially in a shared environment). For example: useradd -G www-data your_user_name (there is almost certainly a GUI way of doing this too).
You may still need to chmod the files as they might not be writeable by the group by default. chmod -R g+rw <directory> would do this.

A: You could add yourself to the www-data group (by adding your username at the end of that line in /etc/group), and change apache's umask to 007 by adding the following line in /etc/apache2/envvars.
export umask 007
This means files created by apache will be 770 by default, allowing you to edit them.

A: Personally I would use sudo to gain access. What is the group permissions? You could also add yourself to the group that has access and chmod g+w on the files. Whatever you do DO NOT make it world write.

A: I'm trying to do something similar to this.  Though i want to make the directories accessible by a group.  So i can add users to the group and they can edit their webpages.  I've been searching for help on this with google for about 2 hours now.


text:
Q: How do I get my pandas dataframe to display the data in multiple columns across the page? I have a pandas dataframe that looks like this:

year
number

1950
7

1951
0

1952
0

1953
4

---
---

2017
268

As the result is very long and not very wide, what I would like to do is repeat these columns across the page, so that the result looks something like this:

year
number
year
number
year
number
year
number
year
number
year
number

1950
7
1955
28
---
---
---
---
---
---
---
---

1951
0
1956
12
---
---
---
---
---
---
---
---

1952
0
1957
21
---
---
---
---
---
---
---
---

1953
4
1958
42
---
---
---
---
---
---
---
---

1954
14
1959
4
---
---
---
---
---
---
2017
268

I have looked at the documentation and can't find any way to do this. Is there a way to do this in pandas?

A: Check this and see if it works:
groups = df.groupby(df.index // 5)  # Split the df every 5 rows

new_df = pd.DataFrame() # Create new df
for _, df_group in groups: # Iterate through the groups of the original df
    new_df = pd.concat([new_df.reset_index(drop=True), df_group.reset_index(drop=True)], axis=1) # concat the new df with the group


text:
Q: Clicking HTML Button and Create a File Can someone helps me, i need to make a button when it Clicked, will creating a file in my storage
<!DOCTYPE html>

            Create Your First Account

    Name:<input type="text" id="username" value="Jack">

        Password:<input type="password" id="password" value="some password">

    <button type="button" onclick="createNow()">Create Your First Account</button>

      <button>Admin Mode</button>

i've put a fs.writeFileSync there and when someone click the button, its not creating the file and contents

A: You should use a.href="home.html"
   function createNow() {
        var userinput = document.getElementById("username").value;
        var passwordinput = document.getElementById("password").value;
        var content = `{ "username": "${userinput}, "password": "${passwordinput} "}`
       //Create user acc
        fs.writeFileSync(`./database/registeredUser/${userinput}.json`, content);
        a.href="home.html";
    }


text:
Q: Naive Bayes Classifier in R (e1071) does not behave as expected (simple example) I don't understand why the following simple example:
genre <- c('ROMANCE', 'ROMANCE','ROMANCE', 'ACTION', 'ACTION', 'ACTION')
explosions <- c('NO', 'NO', 'NO', 'YES', 'YES', 'YES')
likeit <- c('DISLIKE', 'DISLIKE', 'DISLIKE', 'LIKE', 'LIKE', 'LIKE')

df <- data.frame(genre, explosions)
df[] <- lapply(df, factor)
df

model <- naiveBayes(df, as.factor(likeit))
model

p_genre <- factor('ACTION')
p_explosions <- factor('YES')
pred <- data.frame(genre=p_genre, explosions=p_explosions)
pred
model
predict(model, pred, type='raw')

With the following probabilities:
A-priori probabilities:
as.factor(likeit)
DISLIKE    LIKE
    0.5     0.5

Conditional probabilities:
                 genre
as.factor(likeit) ACTION ROMANCE
          DISLIKE      0       1
          LIKE         1       0

                 explosions
as.factor(likeit) NO YES
          DISLIKE  1   0
          LIKE     0   1

> predict(model, pred, type='raw')
     DISLIKE LIKE
[1,]     0.5  0.5

Doesn't give LIKE with prob 1 for an Action movie which has explosions.

A: It is your factors that are incorrectly handled.
It works as expected if you do:
p_genre <- factor('ACTION', c('ACTION','ROMANCE'))
p_explosions <- factor('YES', c('NO', 'YES'))
pred <- data.frame(genre=p_genre, explosions=p_explosions)
predict(model, pred, type='raw')

you get:
         DISLIKE     LIKE
[1,] 9.99999e-07 0.999999


text:
Q: How to visualize the graph using d3Network in R I'm trying to use a package called d3Network in R to visualize some network and I used the example in R :
# Load data
data(MisLinks)
data(MisNodes)

# Create graph
d3ForceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
               Target = "target", Value = "value", NodeID = "name",
               Group = "group", opacity = 0.4)

It only gives me a bunch of scripts rather than a plot. I saw this example on the internet and it seems the others have never come cross this kind of issue. So am I doing something wrong or something is missing? And also I would like to know how to specify the colour of Source nodes and Target nodes.
Thanks in advance

A: It seems you are using d3Network package which is old and not supported anymore. Try using networkD3 package.
The function name is: forceNetwork
Try this:
library(networkD3)
data(MisLinks)
data(MisNodes)
forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source",
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 1)


text:
Q: Is there a GUI tool that can provide the functionality of the Windows Device Manager? There's some thing's I'd like to do with the devices on my system, such as stopping, starting and rebooting and I was wondering if there's a tool, either in Ubuntu or the software centre, that can replicate the functionality of the Windows Device Manager.

A: There is no graphical tool to do those things that I can find. Although some of the things like stopping are hard to do even from the command line since the kernel really isn't friendly to being poked by userspace about what should be turned on.
If you want it could be a project to get involved with:
https://wiki.ubuntu.com/UbuntuDevelopment

A: Check out indicator-usb. It's a small indicator displayed when devices are plugged. With it, you can unmount them easily.
http://www.omgubuntu.co.uk/2010/08/safely-remove-usb-drives-using-a-nifty-application-indicator-updated-with-new-icon/


text:
Q: get height of UIScrollView contentView I have a UIViewController which has the following hierarchy (with their NSLayoutConstraints):
UIView
-UIScrollView
--UIView-ContentView (zero margins to the UIScrollview and equal height to UIScrollVIew's parent; mentioned in the code as self.contentView)
---UIView (fixed height, 0 top margin to Content View)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIWebView (fixed height & linked to IBOutlet in the class; gets expanded)
---UILabel (top margin to UIWebView)
---UIView (fixed height, top margin to above label)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIView (fixed height, 0 top margin to above view)
---UIButton (fixed height, top margin to above view)

Scenario:
1. On viewDidLoad() I'm adding the HTML text by appending the JavaScript code that returns the height of the UIWebView
2. on UIWebViewDelegate method (shouldStartLoadWithRequest) I'm setting the following things:
- webViewHeight.constant (NSLayoutConstraint, linked from IB)
- self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))

override func viewDidLoad() {
    self.webView.scrollView.scrollEnabled = false

    let heightHackScript = "<script type='text/javascript'>window.onload = function() { window.location.href = 'ready://' + document.body.offsetHeight; }</script>"

        if let cBody:NSData = self.model?.text_content {

          self.webView.loadHTMLString(heightHackScript + String(data: cBody, encoding: NSUTF8StringEncoding)!, baseURL: nil)
        }
  }

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

  let url = request.URL

  if navigationType == .Other {
    if url?.scheme == "ready" {
      webViewHeight.constant = (url?.host?.floatValue)!
      self.scrollView.contentSize = CGSizeMake(self.view.frame.width, CGRectGetHeight(self.contentView.frame))
      return false
    }
  }
  return true
}

The issue is that CGRectGetHeight(self.contentView.frame) doesn't gets the desired height. Any ideas?
So I'd like to get the height with constraints of the view after the HTML was loaded to UIWebView.

A: The difficult problem when trying to resize a web view to fit it's content is the fact that the web view itself does not have any idea how tall the content of the DOM being displayed inside of it might be. What you have to do is ask the DOM how tall it's content is through JavaScript. In our code we do it something like this:
[webView stringByEvaluatingJavaScriptFromString: @"document.height"]

or in Swift:
webView.stringByEvaluatingJavaScriptFromString("document.height")

And use the resulting value to select a size for our UIWebView.


text:
Q: tcblisting: two listings side by side can anybody tell me, how to place two source doe listings side by side within a tcblisting?
Something like:
  \begin{tcolorbox}[colback=red!5!white,colframe=red!75!black,sidebyside, listing only,mathescape=true]
  Listing A some code

  \tcblower

  Listing B more code
  \end{tcolorbox}

But with real listings...

A: You cannot use two source listings within a tcblisting, but you can put two listings side by side into a tcolorbox:
\documentclass{article}
\usepackage[skins,listings]{tcolorbox}

\begin{document}

\begin{tcolorbox}[colback=red!5!white,colframe=red!75!black,sidebyside]
\begin{lstlisting}[style=tcblatex]
Listing A some code
\end{lstlisting}
\tcblower%-----------------------------------------
\begin{lstlisting}[style=tcblatex]
Listing B more code
\end{lstlisting}
\end{tcolorbox}

\end{document}


text:
Q: Recuperar valor de un array Buen día, estoy haciendo una función que recupera una fecha que está dentro de un array, pero no logro obtenerla, la función es la siguiente:
 public function getProximoPago()
    {
        $recibo_pago = $this->entity->getJSONOperacion($this->id_caja_operacion);
        $datos_ticket = json_decode($recibo_pago['datos_ticket']);

        return mb_strtoupper($datos_ticket->pagos[4]);
    }

La variable datos_ticker ya recibe el array con toda la información, el cual es:
{
    "nombre_empresa": ,
    "fecha_operacion": "20/02/2020",
    "hora_operacion": "13:06:39",
    "fecha_valor": "2020-02-20",
    "pagos": [{
        "id_credito": 120,
        "dirigido": "Credito",
        "saldo_vencido": 766,
        "saldo_proxima_cuota": "1350.00",
        "fecha_proxima_cuota": "2020-01-31",
        "capital": 1,
        "interes": 0,
        "otros": 0,
        "iva": 0
    }]
}

Yo quiero imprimir fecha_proxima_cuota que se encuentra dentro de pagos.
agradecería mucho su ayuda

A: La variable pagos es un array con un objeto JSON dentro.  Como hay un solo objeto en el array, puedes accesar el primer indice, o sea 0, y luego accesas la propiedad que quieres.  Quedaria asi:
return mb_strtoupper($datos_ticket->pagos[0]->fecha_proxima_cuota);


text:
Q: Umlauts are displayed as ? in my MySQL database? this is my local scenario:
I have an application which reads some CSV files and writers the content to my local MYSQL database. The content contains umlauts, such as "ß" or "Ä". Locally everything works fine, the umlauts are written to the db and also displayed correclty inside the app which reads the db.
Now I moved this scenario to the amazon cloud and suddenly "ß" becomes "?" in the db. I checked what the program reads from the CSV files and there it is still a "ß". So it must be the writing to the database I guess, question is, why was this working locally but not on my cloud server? Is this a db problem, or a PHP problem?
Thanks! :)

A: Did you check the encoding on both databases? Most likely there might be the problem.

A: You need to have your database UTF-8 encoded.
Here is an excellent overview article that explains how encoding works in MySQL, and multiple ways to fix it:
http://www.bluebox.net/news/2009/07/mysql_encoding/

A: you can use:
iconv("UTF-8", "ISO-8859-1", $stringhere);
this will convert the string for you

A: it all depends on how you upload the CSV file.
Before writing the data to the MySQL server, this code might help:
$Notes = $_POST['Notes']; // or contents of the CSV file- but split the data first according to newline etc.

$charset = mysqli_character_set_name($DBConnect);
printf ("To check your character set but not necessary %s\n",$charset);

$Notes = str_replace('"', '"', $Notes);  //double quotes for mailto: emails.
$von = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é");  //to correct double whitepaces as well
$zu  = array("ä","ö","ü","ß","Ä","Ö","Ü"," ","é");
$Notes = str_replace($von, $zu, $Notes);
echo " Notes:".$Notes."<br>" ;
$Notes = mysqli_real_escape_string($link, $Notes); //for mysqli DB connection.

echo " Notes:".$Notes ;


text:
Q: Amount of repeating numbers in a special sequence Suggest we have the sequence of sequences that is constructed according to these rules:

*

*First sequence is filled with 1.

*Second sequence copies the first one, but puts 2 into every position that is a multiple of 2.

*Third sequence copies the second one, but puts 3 into every position that is a multiple of 3.

*(...)

1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2
1 2 3 2 1 3 1 2 3 2
1 2 3 4 1 3 1 4 3 2
1 2 3 4 5 3 1 4 3 5

Does this sequence has special name? Are there any formulas to estimate the count of number M in i-th sequence of length N?
For example:
func count(M int, i int, length int) int { //... }

count(1, 1, 10) == 10
count(1, 2, 10) == 5
count(1, 3, 10) == 3
count(5, 1, 10) == 0
count(5, 5, 10) == 2

A: There's no simple formula for count(1, i, length).
Reduction to known task
Observation 1
The process described is the well known Sieve of Eratosphenes algorithm for prime numbers lookup, where we have 1-s on places what belong to prime numbers. And we have these facts:

*

*There's always 1 at the first column

*Numbers on columns 2…M-1 on (M-1)-th row are not 1-s.

*Number on M-th column of (M-1)-th row is equal to 1 then and only then when M is a prime number.

Observation 2
Amount of 1-s within the first M-th cells of the M-1 row is equal to
U(M) = count(1, M-1, M) - count(1, M-2, M)

if count is a cheap to compute formula then U is cheap too.
Consequence
U(M) equals 2 if M is prime and 1 if M is not prime.
So, and the original count for 1 is not cheaper than U and that is not particularly cheap. I mean, U(M) shows if M is either prime or not. This is not cheap.


text:
Q: Embedded Service API scripting help for Salesforce Chat
*

*I have setup Embedded Chats for Sales flow

*So new chats will be linked to Leads

*I am using Embedded Service API for overriding this behavior to implement my usecase

*My use case -

*

*When a new request is coming first lookup to existing Contacts if found then link it with chat

*If existing Contacts not found then lookup to existing Leads

*If no existing records are found then create new Lead

*SF implements this usecase by default when Contacts are created by converting Leads

*My client org is having Contacts which are not converted from Leads

*So following script I am using to achieve my use case -

         embedded_svc.settings.extraPrechatInfo = [

                {
                    "entityName": "Contact" ,
                    "saveToTranscript " : "ContactId",
                    "entityFieldMaps": [
                        {"isExactMatch": true , "fieldName": "FirstName" , "doCreate": false , "doFind": true , "label": "First Name"} ,
                        {"isExactMatch": true , "fieldName": "Email" , "doCreate": false , "doFind": true , "label": "Email"} ,
                        {"isExactMatch": true , "fieldName": "LastName" , "doCreate": false , "doFind": true , "label": "Last Name"}
                    ]
                } ,

                {
                    "entityName": "Lead" ,
                    "saveToTranscript " : "LeadId",
                    "entityFieldMaps": [
                        {"isExactMatch": true , "fieldName": "FirstName" , "doCreate": true , "doFind": true , "label": "First Name"} ,
                        {"isExactMatch": true , "fieldName": "Email" , "doCreate": true , "doFind": true , "label": "Email"} ,
                        {"isExactMatch": true , "fieldName": "LastName" , "doCreate": true , "doFind": true , "label": "Last Name"}
                    ]
                }

            ];

*

*This script work fine for Existing Leads and new Leads, but when existing Contacts are coming from Chats then it creates a new Lead (a extra record)

I am not sure this approach will implement my requirement, open for any suggestion / help
Thanks in advance

A: I came across the exact situation in my own org.  By default, it appears that the lead record will be searched for or created in the Sales Embedded chat flow.  To stop the duplicate creation, I used matching and duplicate rules to prevent the lead from creating. For my situation, I am only matching on email address since it is unique, however, you can make your matching rules as complicated as needed.  In my duplicate rule, I also added a condition so this rule only applies to the Automated Process user that will create the lead from chat.  If the rule will apply to the entire org, then you will not need to add the condition.

Lastly, you will not need the additional lead items in your extraPrechatInfo code since the find and create actions on Lead are native the Sales embedded flow.
I hope that helps.
All the best,
Ben


text:
Q: How to put space in columns while using select in c# i want to use space columns while selecting in c# code.in oracle sql developer i can use select firstname as "first name" but in c# code i used like select firstname as [first name]  but no luck .how to correct it

A: You have to use the double-quotes for it to be valid SQL.
In your C# code you need to escape them, like so:
string cmd = "SELECT firstname AS \"first name\" FROM ...";


text:
Q: Can't select an option I have this html code
<select id="stuff" name="stuff_name">
<option value="10002">Team_01</option>
<option value="10001">Team_02</option>
<option value="10000">Team_03</option>
<option value="0">[default]</option></select>

I'm trying to select "Team_02" by using css_selector in selenium with python.
Why this works: element = driver.find_element_by_css_selector('#stuff > option:nth-child(2)')
And this doesn't : element = driver.find_element_by_css_selector('#stuff > option[value="Team_02"').click()
The point is that i want to select with 2nd method, because the value constanly changes.
Important:
Can't use value, because it always changes

A: From your question I understand you want to use CSS (since you can also use Xpath or the Select-class of Selenium)
Using CSS you can either search via the value-attribute, but then you need to ask for the value-number
driver.find_element_by_css_selector('#stuff > option[value="10001"]').click()

or you search via the text:
driver.find_element_by_css_selector('#stuff > option[text="Team_02"]').click()

another way would be the innertext
driver.find_element_by_css_selector('#stuff > option[innertext="Team_02"]').click()

A: try if want to use xpath.
driver.find_element_by_xpath("//select[@id='stuff']/option[contains(text(),'Team_02')").click()

or you can try like brute-force.
for option1 in driver.find_elements_by_xpath("//select[@id='stuff']/option"):
    if option1.text == 'Team_02':
        option1.click()
        time.sleep(100)

A: I would suggest using selenium.webdriver.support.ui.Select as below.
select = Select(driver.find_element_by_id("stuff"))
select.select_by_visible_text("Team_02")


text:
Q: TFS 2013 build - Files copied using Post Build Event are not found This is a winform application.
All dlls, exe and some other extension files are copied to the StartupProject\bin through the post build events(VS post-build).
On TFS Server, the project has 2 subfolders: bin and src.(bin contains required dlls, but other extensions are missing -.png, .dat, .xslx).
On the server, the post build copied files appear under the StartupProject\bin, but they are not copied to TFSFolder\bin.
How can I force copy all the StartupProj/bin to the TFSFolder\bin?

A: Team Build use a different directory layouts from Visual Studio builds. All Binaries go in a single folder for any project built, so references are automatically solved and it is easy to copy the DLL to the final Drop folder.
You should use $(OutDir) MSBuild variable to properly reference the binaries directory in VS and TFS builds. See Is there a single MSBuild and TFSBuild variable that will point to where the binaries are? for some details.
If you need to use different scripts for desktop (VS) and server (TFS) builds, use the $(BuildingInsideVisualStudio) variable as explained in TFS 2010 Build Automation and post-build event.


text:
Q: Mysql slave out of sync after crash We have a "1 master, 1 slave" MySQL setup.  We had a sudden power outage that took down the slave.  After getting the machine back up, I found that the slave was out of sync with the master:
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: 10.0.0.1
                  Master_User: slave
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: mysql-log.001576
          Read_Master_Log_Pos: 412565824
               Relay_Log_File: mysqld-relay-bin.002671
                Relay_Log_Pos: 6930
        Relay_Master_Log_File: mysql-log.001573
             Slave_IO_Running: Yes
            Slave_SQL_Running: No
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table: blah.table2
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 1032
                   Last_Error: Could not execute Update_rows event on table blah.info; Can't find record in 'info', Error_code: 1032; handler error HA_ERR_KEY_NOT_FOUND; the event's master log mysql-log.001573, end_log_pos 689031225
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 689030864
              Relay_Log_Space: 2944772417
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 0
                Last_IO_Error:
               Last_SQL_Errno: 1032
               Last_SQL_Error: Could not execute Update_rows event on table blah.info; Can't find record in 'info', Error_code: 1032; handler error HA_ERR_KEY_NOT_FOUND; the event's master log mysql-log.001573, end_log_pos 689031225
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 1
1 row in set (0.00 sec)

We're using a binlog format of "ROW", so when I try to use mysqlbinlog to look at the offending row, I don't see anything of use.  I don't want to simply set the skip counter, because I think that would throw my table even further out of sync.
Is there anything I can do on the slave that would essentially "roll back" to a given point in time, where I could then reset the master log number, poition, etc?  If not, is there anything at all that I can do to get back in sync?

A: One can usually recover from small discrepancies using pt-table-checksum and pt-table-sync.
It looks to me like your slave lost its place in the binary log sequence when it crashes.  The slave continually writes its last processed binlog event into datadir/relay-log.info, but this file uses buffered writes, so it is susceptible to losing data in a crash.
That's why Percona Server created a crash-resistant replication feature to store the same replica info in an InnoDB table, to recover from this scenario.
MySQL 5.6 has implemented a similar feature: you can set relay_log_info_repository=TABLE so the replica saves its state in a crash-resistant way.

Re your comment:
Yes, in theory pt-table-sync can fix any amount of replication drift, but it's not necessarily the most efficient way to correct large discrepancies.  At some point, it's quicker and more efficient to trash the outdated replica and reinitialize it using a new backup from the master.
Check out How to setup a slave for replication in 6 simple steps with Percona Xtrabackup.


text:
Q: Chromium / puppeteer on github actions and azure static web apps libX11-xcb.so.1 failure I'm building a vue/gridsome app that uses a critical css extract plugin.
It all runs fine locally but I'm struggling with github action builds.
Extract critical CSS (1 pages)
Error: Failed to launch the browser process!
/github/workspace/node_modules/puppeteer/.local-chromium/linux-722234/chrome-linux/chrome: error while
loading shared libraries: libX11-xcb.so.1: cannot open shared object file: No such file or directory

I've searched for solutions and it seems there are linux / unbuntu dependencies missing so I tried to add them to my yml workflow following this:https://medium.com/@cloverinks/how-to-fix-puppetteer-error-ibx11-xcb-so-1-on-ubuntu-152c336368
 steps:
  - uses: actions/checkout@v2
    with:
      submodules: true
  - name: Req
    run: sudo apt install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget
  - name: Build And Deploy
    id: builddeploy
    uses: Azure/static-web-apps-deploy@v0.0.1-preview
    with:

It still fails, am I missing a step or is there a limitation with azure static web apps and github actions?
Thanks

A: Did you try this
sudo apt-get install ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils

A: This is a known issue and the following discussion thread has a workaround suggested: https://github.com/Azure/static-web-apps/issues/99
"Our product engineering team is aware of the issue, but unfortunately there is no ETA for a permanent fix. As Static Web Apps moves closer to General Availability (GA), a lot of these issues should be resolved as they are currently maturing the product out of public preview and trying to get it ready for GA."
To benefit the community:
Copied the discussion that you had with my colleague Bryan on the Microsoft Q&A thread -  Thanks for the follow-up and update, Michael. It's much appreciated.


text:
Q: bare infinitive Today I come across this sentence:

I recommend having customer service agents end their emails a variety of ways.

*

*Can you explain why to is not added before end?

*Why is having used before an Object?
It seems to me it should be like this:

I recommend Customer service agents having to stop it.

thank you

A: You are confusing two very different English idioms using HAVE† + VERBinfinitive

*

*In the construction with the marked infinitive (to VERB), HAVE has a modal sense, approximately equivalent to must.

My car has to be fixed. = My car must be fixed.
  Don has to fix my car. = Don must fix my car.
  My car has to be fixed. = My car must be fixed.
  Customer service agents have to end their emails this way. = Customer service agents must end their emails this way.
  Emails have to be ended this way. = Emails must be ended this way.

Note that English idiom doesn't much like using propositions like this as complements of recommend.

? I recommend that customer service agents have to end their emails this way.
  okI recommend that customer service agents be required to end their emails this way.

*In the construction with the unmarked infinitive and an intervening subject, HAVE has a causative sense, equivalent to something in the range compel–cause–make arrangements for.

I will have Don fix my car. = I will pay Don to fix my car.
  I will have customer service agents end their emails this way. = I will institute a new policy calling for customer service agents to end their emails this way.

In uses of this idiom where VERB is cast in the passive (be VERBen‡), the be is deleted, leaving HAVE ... VERBen

I will have my car be fixed. = I will cause my car to be fixed.
  I will have emails be ended this way. = I will institute a new policy calling for emails to be ended this way.

† A word in capitalized italics (like this: WORD) means all inflections of the word; if the word is a verb, this includes grammaticalized constructions in which the word acts as the lexical verb. So HAVE = {have, has, had, having, is having, has had, am had, are had ...} and so forth.
‡ The -en suffix, borrowed from strong-verb forms like broken, given, designates the past/passive participle form of the verb, distinguished from the past form designated with -ed.

A: The bare infinitive is used because the construction used is: have [someone] do [something]. This is a special use of the verb have, which means something like "order or cause someone to do something".

She had me copy the documents.
They had her remove the lens cap.

The verb recommend can be constructed with a noun as an object:

I recommend surrender.
They recommended expansion.

In this case, a gerund is used instead of a noun: having... A gerund is a word on -ing that functions like a noun externally (it can be object or subject or whatever), but internally in functions like a verb (it can have its own object etc.).

I recommend leaving the city.
She recommended having a baby.
I recommend having them end their e-mails with "poopie pants".

A: *

*Sometimes, the infinitive is 'to-less', meaning the 'to' is omitted.  This is usual when the infinitive is used as an object complement to the previous verb.  "Let's go to the mall and shop."  In this sentence 'to the mall' is an adverbial prepositional phrase answering where to go, but 'shop' is a to-less infinitive. It's similar to how one would say, "Let's go shop!"  'go' is the verb and shop is the to-less infinitive.  It's not the same as "Let's go AND shop!"  Here, shop would be the second action verb: going and shopping.  "Let's go shop" means 'let's go and do some shopping.'  Pretty much, it's sort of a convenience to drop the 'to' from the infinitive sometimes, but not always.

*'agents' is the object to 'having'.  (having what? having agents ...) (having agents do/be what? having agents (to) end their emails ...)

*The sentence is missing an adverbial preposition: 'in' before 'a variety of ways'.  (end their emails how?) (in a variety of ways).
Correction:  "I recommend having customer service agents end their emails in a variety of ways."  It's still a bit stiff, even for the way that I speak and write.
I prefer:  "I recommend that customer service agents should end their emails in a variety of ways."  (A recommendations is a suggestion for what someone thinks should happen, etc.)


text:
Q: Python: Add elements to dictionary attribute of class not works I' trying to create a class containing a dictionary as attribute, and methods to add elements to the dictionary and to show all the elements that the dictionary contains.
So I tried this:
class Catalogue:
    def __init__(self):
        self.dictionary = dict()

    def addElement(self,name,price):
       if(self.dictionary.has_key(name)):
            print "This item is already in the catalogue. "
       else:
            print "The item ", name , "was added to the catalogue"
            self.dictionary[name] = price

    def showElements(self):
        print "CATALOGUE: "
        print self.dictionary

And then when used this class inside main function, addElements() doesn't work properly
catalogue = Catalogue

item  = raw_input("Name of the item: ")
price = raw_input("Price: ")

catalogue().addElement(item, price)

catalogue().showElements()

For example if I put as item= "CD" , and price = "1"
The outputs of those methods are:
From catalogue().addElements(item,price)
 The item CD was added to the catalogue
 {'CD', '1'}

But then when I used catalogue().showElements()
 CATALOGUE:
 {}

It seems that dictionary is not passed by reference in the method addElements.
Thanks

A: Your class definition is fine, it is just the way you are using it. Each time you write catalogue(), you are creating and accessing a new Catalogue instance, so each line is acting on a completely separate object.
This line:
catalogue = Catalogue

assigns the Catalogue class to the name catalogue, it doesn't create an instance. Instead, use:
catalogue = Catalogue()
                   # ^ important!

to create a new instance of the class Catalogue, and assign that instance to the name catalogue.
Now you can use that instance, e.g.:
catalogue.addElement(item, price)
       # ^ no parentheses here
catalogue.showElements()
       # ^ or here

A: This is because you are not creating or calling methods the class correctly
If you add in a print statement right after you call this
catalogue = Catalogue
print catalogue

You will see this
__main__.Catalogue

This is because you actually made catalogue a reference to your class Catalogue. You need to change it to this to call your constructor instead so that you create an instance of a Catalogue object.
catalogue = Catalogue()

Calling the class name with the parantheses calls the default constructor.
And then when you call the methods, you are creating new Catalogue objects each time because you're using the parentheses again
catalogue().addElement(item, price)

You need to call methods on your object like this (no parentheses)
catalogue.addElement(item, price)

If any of this is unclear, I recommend the following reading
Python docs on Classes
Intro to Modules, Classes, and Objects
Guide to Speaking Object Oriented
Is-A, Has-A, Objects, and Classes

A: You are misunderstanding how classes and instances work. Every time you call catalogue() you get a new instance: that's what the parentheses do, they call the class which constructs a new instance.
Instead of doing catalogue = Catalogue and then catalogue().addElement you should be doing:
catalogue = Catalogue()
catalogue.addElement(item, price)
catalogue.showElements()

A: When you create the catalogue variable:
catalogue = Catalogue

You don't construct a catalogue object, you just create a variable catalogue that is a reference to the Catalogue class, so when you try to access your functions, you're really creating two new catalogue objects that don't share any values:
catalogue().addElement(item, price) # this constructs a catalogue object

catalogue().showElements() # so does this

To fix this, just change your assignment to a constructor
catalogue = Catalogue()

catalogue.addElement(item, price) # this is now reference to above object
catalogue.showElements() # so is this


text:
Q: "git checkout " is changing branch to "no branch" I am working on a branch in git. When I do
git checkout <commit id>

(commit id obtained from git log ), it is getting committed to that particular change but branch is changed to <No-branch>.
Why is this happening? How do you resolve this?

A: If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.
If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:
git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:
# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

A: By checking out to one of the commits in the history you are moving your git into so called 'detached state', which looks like is not what you want. Use this single command to create a new branch on one of the commits from the history:
git checkout -b <new_branch_name> <SHA1>

A: Is that commit in the other branch? Git checkout <commitid> will just switch over to the other branch if the commit has happened in the other branch. You will want to merge the changes to your first branch if you want the code there.

A: If you are branch master and you do a git checkout <SHA>
I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.
If you want to make changes you can and then you can do a git checkout -b <mynewbranch> to create a new branch based off that commit and any changes you have made.

A: Other answers have explained what 'detached HEAD' means. I try to answer why I want to do that. There are some cases I prefer checkout a commit than checkout a temporary branch.

*

*To compile/build at some specific commit (maybe for your daily build or
just to release some specific version to test team), I used to
checkout a tmp branch for that, but then I need to remember to
delete the tmp branch after build. So I found checkout a commit is
more convenient, after the build I just checkout to the original branch.

*To check what codes look like at that commit, maybe to debug an issue. The case is not much different from my case #1, I can also checkout a tmp branch for that but then I need to remember delete it. So I choose to checkout a commit more often.

*This is probably just me being paranoid, so I prepare to merge another branch but I already suspect I would get some merge conflict and I want to see them first before merge. So I checkout the head commit then do the merge, see the merge result. Then I git checkout -f to switch back to my branch, using -f to discard any merge conflict. Again I found it more convenient than checkout a tmp branch.

A: This worked best for me when I wanted to check out the code, given the commit ID <commit_id_SHA1>
git fetch origin <commit_id_SHA1>
git checkout -b new_branch FETCH_HEAD


text:
Q: Maximum Modulus of Complex Function here's a question I'm working on that I'm a bit stuck on.
Let:
$f(z) = \frac{z^2}{z + 2}$
Find the maximum value of $|f(z)|$ as $z$ varies over the unit disc.
Since $f(z)$ is analytic $\forall z$ in the region,and $f(z)$ is non-constant, the maximum of this function will be on the boundary of the unit disc (Is this the correct application of the theorem?)
If we let $z = e^{it}$ then
$|f(e^{it})| = \frac{|e^{it}|^2}{|e^{it} + 2|}$
$|f(e^{it})| = \frac{1}{|e^{it} + 2|}$
However, I'm stuck here.
The answer given is $1$, but I'm not quite sure how to figure that out. There's quite a bit of confusion on my end as well, as I'm not fully certain if I'm on the right track.
Any help would be appreciated.
Thanks.

A: Hint: do this by common sense: you want to maximize $\frac{1}{|e^{it} + 2|}$, which means minimizing $|e^{it} + 2|$, so draw the picture, and find a complex number on the unit circle whose distance from $z=-2$ is minimum.

A: The minimum of $\mid e^{it}+2\mid$ pretty clearly occurs when $t=\pi$.  That is,  the maximum modulus is $1$.
You did the problem correctly (up to there).


text:
Q: Can't scroll properly when using 2 ListView.builder I can't scroll properly when using 2 ListView.builder
I am new to flutter and can't scroll properly. I am using 2 listView.builders and I don't know what I am doing wrong. I have tried to change physics form NeverScrollableScrollPhysics to AlwaysScrollableScrollPhysics but still not scrolling properly
Here is the code.
import 'package:flutter/material.dart';
import 'package:map/containerWidget.dart';

class Body extends StatefulWidget {
  const Body({Key? key}) : super(key: key);

  @override
  _BodyState createState() => _BodyState();
}

class _BodyState extends State<Body> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: 3,
            itemBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 10000,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5, top: 5),
                  child: Scaffold(
                    appBar: AppBar(),
                    body: DefaultTabController(
                      length: 4,
                      child: NestedScrollView(
                        headerSliverBuilder: (context, _) {
                          return [
                            SliverList(
                              delegate: SliverChildListDelegate(
                                [
                                  ListView.builder(
                                      shrinkWrap: true,
                                      physics:
                                          const AlwaysScrollableScrollPhysics(),
                                      itemCount: 3,
                                      itemBuilder:
                                          (BuildContext context, int index) {
                                        return Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment
                                                    .center,
                                            children: const [
                                          SizedBox(
                                              width: 300,
                                              height: 300,
                                              child: Card(
                                                color: Colors.blue,
                                              )),
                                        ]);
                                      })
                                ],
                              ),
                            ),
                          ];
                        },
                        body: Column(
                          children: <Widget>[
                            Material(
                              color: Colors.white,
                              child: TabBar(
                                isScrollable: true,
                                labelColor: Colors.black,
                                unselectedLabelColor: Colors.grey[400],
                                indicatorWeight: 1.5,
                                indicatorColor: Colors.black,
                                tabs: const [
                                  Tab(
                                    text: "1",
                                  ),
                                  Tab(
                                    text: "2",
                                  ),
                                  Tab(
                                    text: "3",
                                  ),
                                  Tab(
                                    text: "4",
                                  ),
                                ],
                              ),
                            ),
                            const Expanded(
                              child: TabBarView(
                                children: [
                                  ContainerWidget(),
                                  ContainerWidget(),
                                  ContainerWidget(),
                                  ContainerWidget(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              );
            }));
  }
}

A: You should not nest two ListView widgets to achieve multiple lists.
This creates a Conflict.
To add Two Lists without any scrolling glitch. Use CustomScrollView widget.
Example
https://api.flutter.dev/flutter/widgets/CustomScrollView-class.html
follow above link it has detailed explanation on the usage.


text:
Q: android- How to impaneled a searchview for map with String and Lat lang? I want to have a searchview for my map that is based on the name of and the Latlang of the location.
I have a Hashmap();
but this line:
  map.put(BaseColumns._ID, "rowid AS " +
                BaseColumns._ID);
gives the error: Wrong 2nd argument type, required String, Found Latlang.
I tried to change the   BaseColumns._ID to Latlang but I couldn't.
How can I fix this?
private static final String TAG = "DictionaryDatabase";

//The columns we'll include in the dictionary table
public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final Latlang KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2;

private static final String DATABASE_NAME = "dictionary";
private static final String FTS_VIRTUAL_TABLE = "FTSdictionary";
private static final int DATABASE_VERSION = 2;

private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,Latlang> mColumnMap = buildColumnMap();

/**
 * Constructor
 * @param context The Context within which to work, used to create the DB
 */
public DictionaryDatabase(Context context) {
    mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}

private static HashMap<String,Latlang> buildColumnMap() {
    HashMap<String,Latlang> map = new HashMap<String,Latlang>();
    map.put(KEY_WORD, KEY_DEFINITION);
    map.put(KEY_WORD, KEY_DEFINITION);
    map.put(BaseColumns._ID, "rowid AS " +
            BaseColumns._ID);
    map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
    map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
    return map;
}

A: You are declaring the map as:
HashMap<String,Latlang> map = new HashMap<String,Latlang>();

However, your data are strings:
map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);

I suggest you declare the map like this:
HashMap<String, String> map = new HashMap<String, String>();

Or make sure your values are actually LatLng:
map.put(BaseColumns._ID, new LatLng(latitude, longitude));


text:
Q: I Request Help on Implementing a General Tree in Java I've come up with the following as an attempt to create a general tree in java:
import java.util.*;

public class GeneralNode<T>{

    private T data = null;
    private Vector<GeneralNode<T>> children =
            new Vector<GeneralNode<T>>();

    public GeneralNode(){
        this(null);
    }

    public GeneralNode(T d){
        data = d;
    }

    public Vector<GeneralNode<T>> getChildren(){
        return children;
    }

    public void addChild(T d){
        GeneralNode<T> c = new GeneralNode<T>(d);
        this.children.add(c);
    }

    public void addChild(GeneralNode<T> c){
        this.children.add(c);
    }

    public T getData(){
        return data;
    }

    public void setData(T newData){
        data = newData;
    }

    public boolean isLeaf(){
        return(children.isEmpty());
    }

    public Vector getChildrenData(){
        Vector<T> result = new Vector<T>();
        for(int i = 0; i < children.size(); i++)
            result.add(children.elementAt(i).getData());
    return result;
    }
}

This works great for storing information. It allows me to create a node and insert more nodes in that node, along with having one type of information in each node. Unfortunately, it seems like I can't reference a "parent" node with this class. Essentially, I'm nesting vectors within vectors, so I can't actually reference the node holding the node.
I'm sure I have to make a separate GeneralTree class in order to get this done, but I'm not sure how I'd go about doing so. I had the idea of assigning the root as a GeneralNode, and having a "previous" and "next" node as being the parent and children respectively. This is what I've come up with so far:
import java.util.*;

public class GeneralTree<T>{

    private GeneralNode<T> root;
    private GeneralNode<T> parent;
    private GeneralNode<T> children;

    public GeneralTree(){
        this(null);
    }

    public GeneralTree(T d){
        this(d, null);
    }

    /* I don't know what to do here. I want
     * to assign a parent node to every
     * tree I make, but if I keep the
     * second parameter as GeneralNode<T>, wouldn't
     * that mean I could only ever have one GeneralTree?
     */
    public GeneralTree(T d, GeneralNode<T> p){
        root = new GeneralNode<T>(d);
        parent = p;
    }
}

I've written comments on the constructor I'm confused on. I hope I've explained my problem well enough. If anyone can help me with this that'd be great.

A: As @JohnBollinger said, you can keep a reference of parent node inside each nodes. If you do that you must set parent nodes inside addChild methods.
import java.util.Vector;

public class GeneralNode<T>{

    private T data = null;
    private Vector<GeneralNode<T>> children =
            new Vector<GeneralNode<T>>();

    private GeneralNode<T> parentNode;

    //constructors

    private void setParent(GeneralNode<T> parentNode) {
        this.parentNode = parentNode;
    }

    public void addChild(T d){
        GeneralNode<T> c = new GeneralNode<T>(d);
        c.setParent(this);
        this.children.add(c);
    }

    public void addChild(GeneralNode<T> c){
        c.setParent(this);
        this.children.add(c);
    }

    //other methods
}


text:
Q: Liquibase fails with MongoDB I want to get an example of liquibase, Spring and MongoDB all together. In order to do so, I created a Spring project using Spring Initializr with Spring Data MongoDB as dependency. The project already connects to the database and now I would like to use liquibase. I followed the instructions from liquibase using the maven approach but if I run the maven command mvn liquibase:status I will get the following error:
Unexpected error running Liquibase: Cannot find database driver: com.mongodb.client.MongoClients.<init>()

It looks like this problem has been already reported to liquibase but if there is a solution it hasn't been posted in the issue.
I tried as well to use the CLI option by adding the jars to the lib folder of the liquibase installation. I got the same error if I run liquibase status
I have created a repo in GitHub to show the problem. Here there is some relevant configuration of the code:
pom.xml
<project>
...
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.3</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
...
<properties>
    <liquibase-mongo-ext.version>4.14.0</liquibase-mongo-ext.version>
    <liquibase-maven-plugin.version>4.2.0</liquibase-maven-plugin.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.liquibase.ext</groupId>
        <artifactId>liquibase-mongodb</artifactId>
        <version>${liquibase-mongo-ext.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase-maven-plugin.version}</version>
            <configuration>
                <propertyFile>liquibase.properties</propertyFile>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.liquibase.ext</groupId>
                    <artifactId>liquibase-mongodb</artifactId>
                    <version>${liquibase-mongo-ext.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.mongodb</groupId>
                    <artifactId>mongodb-driver-sync</artifactId>
                    <version>4.6.1</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>
</project>

liquibase.properties
changeLogFile=./mongo/changelog/changelog.sql
url=jdbc:mongodb://127.0.0.1:27017/local
driver=com.mongodb.client.MongoClients

How can I get liquibase running with maven? Any suggestions?
EDIT 1:
As Andrey suggested:

*

*Driver was updated to: driver=liquibase.ext.mongodb.database.MongoClientDriver

*Url was updated to:
url=mongodb://127.0.0.1:27017/local

*plugin from liquibase was updated with new dependency

<dependency>
  <groupId>org.liquibase</groupId>
  <artifactId>liquibase-core</artifactId>
  <version>4.9.1</version>
</dependency>

mvn liquibase:update now trhows the following error. Since the other error seems to be unrelated to this one. I'll solve this answer and create a new thread.
[ERROR] Failed to execute goal org.liquibase:liquibase-maven-plugin:4.2.0:update (default-cli) on project mongo: Execution default-cli of goal org.liquibase:liquibase-maven-plugin:4.2.0:update failed: A required class was missing while executing org.liquibase:liquibase-maven-plugin:4.2.0:update: liquibase/configuration/HubConfiguration

EDIT 2:
As mentioned in the answer, there was a mismatch between the version from Spring and the version of the plugin, which failed to find the class because HubConfiguration class is now under liquibase.hub.HubConfiguration This set up could have led to a CastException as well. So I updated the version liquibase-maven-plugin to 4.9.1
Also the use of the local database is not compatible with validators. The URI was updated to url=mongodb://127.0.0.1:27017/test in the liquibase.properties file.
Now it works like a charm! :D

A: I have found following mistakes in your configuration:
1.
changeLogFile=./mongo/changelog/changelog.sql
url=jdbc:mongodb://127.0.0.1:27017/local
driver=com.mongodb.client.MongoClients

while liquibase-mongodb expects something like (no jdbc prefix, another driver class):
changeLogFile=./mongo/changelog/changelog.sql
url=mongodb://127.0.0.1:27017/local
driver=liquibase.ext.mongodb.database.MongoClientDriver

*liquibase version:

<liquibase-maven-plugin.version>4.2.0</liquibase-maven-plugin.version>

*

*4.2.0 liquibase version seems to be incompatible with NoSQL DB extensions

*spring boot 2.7.3 uses liquibase 4.9.1 - you need somehow choose the correct liquibase version

Finally I get the following on liquibase:update:

[ERROR] Failed to execute goal
org.liquibase:liquibase-maven-plugin:4.14.0:update (default-cli) on
project mongo:  [ERROR] Error setting up or running Liquibase: [ERROR]
liquibase.exception.DatabaseException: Could not execute: Command
failed with error 72 (InvalidOptions): 'Document validators are not
allowed on collection local.DATABASECHANGELOGLOCK with UUID
31bd40b8-3e1c-45c8-9d03-77b91c67a1a9 in the local internal database'
on server 127.0.0.1:27017. The full response is {"ok": 0.0, "errmsg":
"Document validators are not allowed on collection
local.DATABASECHANGELOGLOCK with UUID
31bd40b8-3e1c-45c8-9d03-77b91c67a1a9 in the local internal database",
"code": 72, "codeName": "InvalidOptions"}

no idea what does it mean - something related to mongodb and extension I believe

UPD.
The root cause of last error is described in documentation:
Restrictions
You cannot specify a validator for collections in the admin, local, and config databases.
You cannot specify a validator for system.* collections.
So, url (jdbc:mongodb://127.0.0.1:27017/local) should point to another db.


text:
Q: Do I have to change my location in every profile? I see that the locations were standardized (Location in profile was changed without edit or knowing).  Mine is another where the default is wrong, although I am willing to use the suggested option.  Do I have to go change every profile or is there some way to change one and have it refresh all the others too?  All profiles are linked and use the same OpenID.

A: There's a "copy profile to related accounts" button on the accounts tab of your profile. Note that this obviously copies the whole profile, not just the location.


text:
Q: Spring security Always redirecting to login when accessing to public pages When trying to accessing for first time my webpage in Spring, by some reason (I think not from the configuration class) Spring Security is always redirecting me to the login page, even if I tried to make it public.
Here's what the configuration sheet look like, just in case:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    RepositoryUserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10, new SecureRandom());
    }
    //Method that allow us to configure access to webpages.
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //Validating user...
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

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

        //Public pages
        http
                .authorizeRequests()
                .antMatchers("/",
                             "/login",
                             "/register",
                             "/locale",
                             "/games",
                             "/js/*",
                             "/css/*")
                .permitAll();
//        http.authorizeRequests().antMatchers("/").permitAll();
        //        http.authorizeRequests().antMatchers("login").permitAll();
//        http.authorizeRequests().antMatchers("/register").permitAll();
//        http.authorizeRequests().antMatchers("/locale").permitAll();
//        http.authorizeRequests().antMatchers("/bets").permitAll();

         // http.authorizeRequests().antMatchers("/register").permitAll();

        //http.authorizeRequests().antMatchers("/games").permitAll();

        //Public endpoints
        http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/locale/**","/api/game").permitAll();
        //http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/game").permitAll();
        http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/user").permitAll();

        //Authenticated pages
        http.authorizeRequests().antMatchers("/locale").hasAnyRole("USER","ADMIN");
        //Authenticated endpoints
        http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/user/**").hasAnyRole("USER","ADMIN");
        http.authorizeRequests().antMatchers(HttpMethod.GET, "/api/bet").hasAnyRole("USER","ADMIN");
        http.authorizeRequests().antMatchers(HttpMethod.POST, "/api/bet").hasAnyRole("USER","ADMIN");
        http.authorizeRequests().antMatchers(HttpMethod.PUT, "/api/user/**").hasAnyRole("USER","ADMIN");
        http.authorizeRequests().antMatchers(HttpMethod.DELETE, "/api/user/**").hasAnyRole("USER","ADMIN");
        http.authorizeRequests().antMatchers(HttpMethod.DELETE, "/api/bet").hasAnyRole("USER","ADMIN");

        //Private pages and endpoints (the rest of them)
        http.authorizeRequests().anyRequest().hasRole("ADMIN");

        // Login form
        http.formLogin().loginPage("/login");
        http.formLogin().usernameParameter("username");
        http.formLogin().passwordParameter("password");
        http.formLogin().failureUrl("/loginerror");
        http.formLogin().defaultSuccessUrl("/logged");
         // Logout
        http.logout().logoutUrl("/logout");
        http.logout().logoutSuccessUrl("/");

        // Disable CSRF at the moment
        http.csrf().disable();

    }

Here the RestSecurityConfig:
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    RepositoryUserDetailsService userDetailsService;
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10, new SecureRandom());
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}

And here's the UserDetailsService:
@Service
public class RepositoryUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByName(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found"));
        List<GrantedAuthority> roles = new ArrayList<>();
        for (String role : user.getRoles()) {
            roles.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
        return new org.springframework.security.core.userdetails.User(user.getName(),
                user.getPass(), roles);
    }
}

Any sugestion? thank you


text:
Q: Flask OAuth 2.0 Authorization Code Flow Invalid Authorization Token with Fitbit API I've been trying to use Flask-dance's OAuth2ConsumerBlueprint to make requests to the Fitbit API. So far, I've managed to get the authorization page to come up on my Flask app but I haven't been able to route to a page where I can view the data yet.
In browser, when I try to make a request I get the output of the CURL response {"errors":[{"errorType":"system","fieldName":"n/a","message":"Authorization Error: Invalid authorization token type"}],"success":false}
My goal right now is just to be able to view the user's fitbit dashboard in my app through the API by making a request through the app to "https://api.fitbit.com/1/user/-/profile.json"
This is my code so far. If anyone could offer some guidance as to where I'm going wrong with the Oauth2.0 authorization code flow, flask, or the fitbit api I would greatly appreciate it.

from flask import Flask, redirect, url_for, render_template
from flask_dance import OAuth2ConsumerBlueprint

import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

CLIENT_ID = 'CLIENT_ID'  # OAuth 2.0 Client ID
CLIENT_SECRET = CLIENT_SECRET'
scope = ["activity",
         "nutrition",
         "heartrate",
         "location",
         "nutrition",
         "profile",
         "settings",
         "sleep",
         "social",
         "weight",
         ]

# Flask OAuth2 Custom Blueprint for Fitbit API
app = Flask(__name__)
fitbit_blueprint = OAuth2ConsumerBlueprint(
    "fitbit-api", __name__,
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    base_url="https://www.fitbit.com",
    token_url="https://api.fitbit.com/oauth2/token",
    authorization_url="https://www.fitbit.com/oauth2/authorize",
    scope=scope
)
app.register_blueprint(fitbit_blueprint, url_prefix="/login")
app.secret_key = "supersecret"  # Replace this

app.token = fitbit_blueprint.token
print(app.token)

@app.route("/")
def index():
    #return redirect(url_for("fitbit-api.login"))
    return render_template('index.html')

@app.route("/success")
def access():
    return "Success"

@app.route('/login')
def login():
    return redirect(url_for("fitbit-api.login"))

# Redirect URI = http://127.0.0.1:
if __name__ == '__main__':
    app.run(host="localhost", port=5000, debug=True)

A: You can not access the (user profile) resource before you get authorized from fitbit. Once you got authorized, you will need to exchange your authorization code with a Token Pair and save the tokens - namely Access Token and Refresh Token - somewhere in your code.
Solely being able to reach and pass the authorization page does not mean that you've been authorized. You can check if your authorization is completed within your fitbit profile:
Open your Fitbit profile -> My Dashboard -> Settings. From the left panel choose Applications. There you should be able to see a list of authorized apps: If you don't, you haven't changed your authorization code with a token pair yet!
You can only then be able to make requests to the user-profile endpoint in which case you have to build up an http post with your valid saved Access Token in its header as in https://dev.fitbit.com/build/reference/web-api/oauth2/#making-requests.


text:
Q: Trying to speed up finding solutions of quadratic form related to the weight of a matrix Say I have an integer matrix of size $5 \times 5$ - I am trying to find the solutions to the equation $n^4 wtM = n w^2 + x1^2 + x2^2 +x3^2 +x4^2 + x5^2$ subject to the constraints $x1+x2+x3+x4+x5 = 0$ and $w>0$ where, in this case $n=5$ and $wtM$ is the weight of the matrix i.e.  $n^4 wtM$ is just some integer - typically with values in the range one thousand to five thousand.
Now I am using the Mathematica function PowersRepresentations to solve $n^4 wtM - n w^2$    for w ranging from 1 until $n^4 wtM - n w^2$ is still positive.
This gives me a list of lists $w,x1,x2,x3,x4,x5$  for each w. I then combine all these solutions together which I call $reps$ in the following code.
Now PowersRepresentations only gives positive values. I need to allow the $x1,x2,x3,x4,x5$ to be positive or negative subject to the constraint $x1+x2+x3+x4+x5 = 0$
So I take each list $w,x1,x2,x3,x4,x5$ and multiply it by vectors of permutations of plus and minus 1 (always having the first element in the vector 1 so as to keep w positive). I don't bother with vectors of all 1's or all -1's as this would automatically violate my summation constraint.
I then select the cases using a compiled function $cf1$ that makes sure I still obey the constraint $x1+x2+x3+x4+x5 = 0$. I also have some other constraints that I apply (via some other compiled functions) such as $x1\le x2 \le x3 \le x4$ and $x1 \ge 0 \space x2 \ge 0 \space x3 \ge 0 \space x4 \ge 0$.
Now the code I have written tries to make use of parallelisation but for anything above $7 \times 7$ takes a very long time to run.
I have perused many articles on here but I am still unsure of the various methods I have employed. The code works but I am concerned I am missing some tricks that would allow much faster execution. I have used Mathematica quite a bit in the past but primarily in using NDSolve and the like but not parallelising and compiling to C.
Any recommendations and pointing out speed increases (and memory usage reduction) would be much appreciated. As I said the code takes a long time and uses a lot of memory for $n \ge 7$. Notice I am not even saving the solutions but just counting them.
The example used below was for $n = 7$ and $wtM = 54/49$ giving $n^4 wtM = 2646$
One that runs in about 12 seconds is $n = 6$ and $wtM = 4/3$ giving $n^4 wtM = 1728$

n = 7;
wtM = 54/49;

progressreporting = True

ClearAll[results1, results2, results3, results4, data1, data2, data3,
  data4];

ordering1 = "";
Do[ordering1 =
  StringJoin[ordering1, "#[[" <> ToString[i] <> "]]+"], {i, 2,
  n + 1}]; ordering1 =
 ToExpression[StringJoin[StringDrop[ordering1, -1], "==0 &"]];

cf1 = With[{ordering = ordering1},
   Compile[{{triples, _Integer, 2}},
    DeleteDuplicates[Select[triples, ordering]],
    RuntimeAttributes -> {Listable}, Parallelization -> True,
    CompilationTarget -> "C", RuntimeOptions -> "Speed"]];

ordering2 = "";
Do[ordering2 =
   StringJoin[ordering2, "#[[" <> ToString[i] <> "]]<= "], {i, 2,
   n}];
ordering2 =
  ToExpression[StringJoin[StringDrop[ordering2, -3], " &"]];
If[n == 2, ordering2 = ordering1];

cf2 = With[{ordering = ordering2},
   Compile[{{triples, _Integer, 2}}, Select[triples, ordering],
    RuntimeAttributes -> {Listable}, Parallelization -> True,
    CompilationTarget -> "C", RuntimeOptions -> "Speed"]];

ordering3 = "";
Do[ordering3 =
  StringJoin[ordering3, "#[[" <> ToString[i] <> "]]>=0 &&"], {i, 2,
  n}]; ordering3 =
 ToExpression[StringJoin[StringDrop[ordering3, -2], " &"]];

cf3 = With[{ordering = ordering3},
   Compile[{{triples, _Integer, 2}}, Select[triples, ordering],
    RuntimeAttributes -> {Listable}, Parallelization -> True,
    CompilationTarget -> "C", RuntimeOptions -> "Speed"]];

DistributeDefinitions[cf1, cf2, cf3];
AbsoluteTiming[
 reps = Join @@
   Table[
    Map[Prepend[#, i] &,
     PowersRepresentations[n^4 wtM - n i^2, n, 2]], {i, 1,
     IntegerPart[Sqrt[(n^4 wtM)/n]]}];
 vc = Map[Insert[#, 1, 1] &, Take[Tuples[{-1, 1}, n], {2, 2^n - 1}]];

 ParallelEvaluate[foo1 = {}]; ParallelEvaluate[foo2 = {}];
 ParallelEvaluate[foo3 = {}]; ParallelEvaluate[foo4 = {}];

 sow[x_] := (foo1 = {foo1, x};); sow2[x_] := (foo2 = {foo2, x};);
 sow3[x_] := (foo3 = {foo3, x};); sow4[x_] := (foo4 = {foo4, x};);

 ParallelDo[

  temp = Extract[reps[[j]], 1]; temp2 = Drop[reps[[j]], 1];
  test0 = Permutations[temp2];
  test1 = Map[Prepend[#, temp] &, test0];
  lst = {};
  lst = Table[
    Map[Times[#, test1[[i]]] &, vc], {i, 1, Length[test1]}];
  test2 = Join @@ lst;

  test3 = cf1[test2];
  test32 = cf2[test3];
  test33 = cf3[test3];
  test34 = cf3[test32];

  sow[Length@test3]; sow2[Length@test32]; sow3[Length@test33];
  sow4[Length@test34];

  , {j, 1, Length[reps]},
  ProgressReporting -> progressreporting,
  Method -> "ItemsPerEvaluation" -> 1000];

 results1 = Join @@ ParallelEvaluate[Flatten@foo1];
 results2 = Join @@ ParallelEvaluate[Flatten@foo2];
 results3 = Join @@ ParallelEvaluate[Flatten@foo3];
 results4 = Join @@ ParallelEvaluate[Flatten@foo4];

Print["\!\(\*SuperscriptBox[\(n\), \(4\)]\)wtM = ", n^4 wtM];

  data1 = Total[results1];
  Print[data1, " solutions in Z with no ordering"];
  If[n > 2, data2 = Total[results2];
    Print[data2, " solutions in Z with ordering"]];
  data3 = Total[results3];
  Print[data3,
    " solutions in \!\(\*SubscriptBox[\(N\), \(0\)]\) with no \
ordering"];
  If[n > 2, data4 = Total[results4];
    Print[data4,
     " solutions in \!\(\*SubscriptBox[\(N\), \(0\)]\) with \
ordering"]];] // First

n^4wtM = 2646

342611822 solutions in Z with no ordering

584282 solutions in Z with ordering

169915 solutions in Subscript[N, 0] with no ordering

556 solutions in Subscript[N, 0] with ordering

1688.18

A:
It's not an answer but a long comment.

Without understanding your code, these are some improvements just by using built-in functions:

*

*ordering1
You'd used string concatenation to build your expression, which could be improved in both readability and performance?

(* use *)
Plus @@ Take[#, {2, n+1}] == 0 &
(* or *)
Total[Take[#, {2, n+1}]] == 0 &

(* instead of *)

ordering1 = "";
Do[ordering1 =
  StringJoin[ordering1, "#[[" <> ToString[i] <> "]]+"], {i, 2,
  n + 1}]; ordering1 =
 ToExpression[StringJoin[StringDrop[ordering1, -1], "==0 &"]];

(* example: #[[2]]+#[[3]]+#[[4]]+#[[5]]+#[[6]]==0 & *)

*

*ordering2
like ordering1, just use the power of built-ins

OrderedQ[Take[#, {2, n}]]&

(* instead of *)

ordering2 = "";
Do[ordering2 =
   StringJoin[ordering2, "#[[" <> ToString[i] <> "]]<= "], {i, 2,
   n}];
ordering2 =
  ToExpression[StringJoin[StringDrop[ordering2, -3], " &"]];

(* example: #[[2]]<= #[[3]]<= #[[4]]<= #[[5]]<= #[[6]] & *)

*

*ordering3
AllTrue needs version 10

AllTrue[NonNegative[Take[#, {2, n}]], TrueQ] &;

(* instead of *)

ordering3 = "";
Do[ordering3 =
  StringJoin[ordering3, "#[[" <> ToString[i] <> "]]>=0 &&"], {i, 2,
  n}]; ordering3 =
 ToExpression[StringJoin[StringDrop[ordering3, -2], " &"]];

(* example: #1[[2]] >= 0 && #1[[3]] >= 0 && #1[[4]] >= 0 && #1[[5]] >= 0 && #1[[6]] >= 0 & *)

*

*lst
Outer[Times, test1, vc]

(* instead of *)

Table[Map[Times[#, test1[[i]]] &, vc], {i, 1, Length[test1]}]

*

*Also, you can use PadLeft instead of Map[Prepend.../Map[Insert[...,1,1] ...


text:
Q: Tensorflow: Get the same tensor after a series of convolution and deconvolution I am wondering whether it is possible to end up with the same tensor after propagating it through a convolutional and then deconvolutional filter. For example:
random_image = np.random.rand(1, 6, 6, 3)
input_image = tf.placeholder(shape=[1, 6, 6, 3], dtype=tf.float32)
conv = tf.layers.conv2d(input_image, filters=6, kernel_size=[3, 3], strides=(1, 1), data_format="channels_last")
deconv = tf.layers.conv2d_transpose(conv, filters=3, kernel_size=[3, 3], strides=(1, 1), data_format="channels_last")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(random_image)
# Get an output which will be same as:
print(sess.run(deconv, feed_dict={input_image: random_image}))

In other words, if the generated random_image vector is for example: [1,2,3,4,5], after convolution and deconvolution the deconv vector to be [1,2,3,4,5].
However, I am not able to get it to work.
Looking forward to you answers!

A: It's possible to get some degree of visual similarity, by using VarianceScaling initialization for example. Or even with completely custom initializer. But transposed convolution isn't mathematically deconvolution. So you can't get math equality with conv2d_transpose.
Take a look Why isn't this Conv2d_Transpose / deconv2d returning the original input in tensorflow?


text:
Q: How to make PRs from a fork default to targeting the fork instead of the original? Say there is an origin repo called original/repo of which I forked off to my/repo.  If I create a branch in my/repo and then create a PR from that branch, the PR defaults to merge to original/repo.  How can I make it default to merging to my/repo?

A: That (changing the default PR target) is a known request
But it is not supported yet by GitHub, which means you would need to

*

*duplicate your fork into its own GitHub independent repository, in which you can  do your internal PRs, before being able to

*push to your fork, where you can do regular PR to the upstream original repository.


text:
Q: Using expected value to find a variable inside a Probability Density Function If you have $$f_{x}(x)= \begin{cases} \alpha \sqrt{x} +\beta x^{2}, &\text{if } \; 0<x<4\\ 0, &\text{otherwise} \end{cases}$$
How would you find the $\alpha$ and the $\beta$, knowing that $E{[X^2]}=\frac{48}{5}$. Granted that integral of P.D.F. equals to 1 but not sure what to get from it

A: You have two equations. Using the known property of p.d.f, we have
$$
\int_0^4 \left ( \alpha \sqrt{x} +\beta x^{2} \right ) dx = 1
$$
and using the known second moment, we have
$$
\int_0^4 x^2 \left ( \alpha \sqrt{x} +\beta x^{2} \right ) dx = 48/5
$$
If you solve these two integrals, you get two linear equations involving $\alpha$ and $\beta$. Solve this system for your parameters.