text:
Q: What is the series $ \dfrac{1}{\left( x-{y}^{2} \right) \left(1- yx \right) \left( {x}^{2}-y \right)} $ expansion? Consider the series expansion
$$
\frac{1}{\left( x-{y}^{2} \right)  \left(1- yx \right)  \left( {x}^{2}-y \right)}=P_0(y)+P_1(y)x+P_2(y)x^2+\cdots+P_n(y) x^n+\cdots.
$$
For small $n$ we have
\begin{gather*}
P_0(y)=\frac{1}{y^3},\\
P_1(y)={\frac {{y}^{3}+1}{{y}^{5}}},\\
P_2(y)={\frac {{y}^{6}+2\,{y}^{3}+1}{{y}^{7}}},\\
P_3(y)={\frac {{y}^{9}+2\,{y}^{6}+2\,{y}^{3}+1}{{y}^{9}}},\\
P_4(y)=\frac{{y}^{12}+2\,{y}^{9}+3\,{y}^{6}+2\,{y}^{3}+1}{y^{11}},\\
P_5(y)={\frac {{y}^{15}+2\,{y}^{12}+3\,{y}^{9}+3\,{y}^{6}+2\,{y}^{3}+1}{{y}^{
13}}}.
\end{gather*}
Question: What is a close expression for $P_n(y)$?
My attempt.  The $P_n(y)$  has  a form
$$
 P_n(y)=\frac{1}{y^{2n+3}}(c_{n,1}+c_{n,2}y^3+c_{n,3}y^{6}+\cdots+с_{n,k} y^{3(k-1)}+\cdots+c_{n,n+1}y^{3n})
$$
for some  unknown sequence $c_{n,k}.$
By empirical way I have found that
$$
c(n,k)= \left \{
\begin{array}{l}
\min(n{-}k+2,k) , 1 \leq    k \leq n+1, \\
\\
0,  \text{ otherwise, }
\end{array}
\right.
$$
but I can't find a rigorous proof.
Any help?

A: Your expression is a product of three geometric series (first two multiplied by $-1$ which does not affect the final product):
$$
\frac{1}{y-x^2}=\frac{1}{y}\frac{1}{1-\frac{x^2}{y}}=\frac{1}{y}+\frac{1}{y^2}x^2+\dots+\frac{1}{y^{n+1}}x^{2n}+\dots\\
\frac{1}{y^2-x}=\frac{1}{y^2}\frac{1}{1-\frac{x}{y^2}}=\frac{1}{y^2}+\frac{1}{y^4}x+\dots+\frac{1}{y^{2n+2}}x^{n}+\dots\\
\frac{1}{1-xy}=1+xy+x^2y^2+\dots+x^{n}y^n+\dots\\
$$
The product of the first two is
\begin{align}
\sum_{n=0}^{\infty}(\sum_{k=0}^{\lfloor n/2 \rfloor}\frac{1}{y^{k+1}}\frac{1}{y^{2(n-2k)+2}})x^n
&=\sum_{n=0}^{\infty}(\sum_{k=0}^{\lfloor n/2 \rfloor}\frac{1}{y^{2n-3k+3}})x^n
\end{align}
Multiplying with the third one we get
\begin{align}
\frac{1}{y-x^2}\frac{1}{y^2-x}\frac{1}{1-xy}
&=\sum_{n=0}^{\infty}\sum_{i=0}^{n}\sum_{k=0}^{\lfloor i/2 \rfloor}\frac{1}{y^{2i-3k+3}}y^{n-i} x^n\\
\end{align}
So the value you want is
\begin{align}
P_n(y)=\sum_{i=0}^{n}\sum_{k=0}^{\lfloor i/2 \rfloor}\frac{1}{y^{2i-3k+3}}y^{n-i}
&=y^{n-3}\sum_{i=0}^{n}\sum_{k=0}^{\lfloor i/2 \rfloor}\frac{1}{y^{3i-3k}}.
\end{align}
For fixed $t$, how many ways we can choose $i,k$ to get $t=i-k$, subject to $0\leq i \leq n$, $0 \leq k \leq i/2$? Since $k=i-t$ we have $0 \leq i-t \leq i/2$ we get $i/2 \leq t \leq i \leq n$. This works in the other direction as well, for any $i$ with $i/2 \leq t \leq i$ we set $k=i-t$ and the original conditions are satisfied. So the question reduces to how many $i$ exist such that $i/2 \leq t \leq i \leq n$? We can see that if $t \geq n/2$, then any $t \leq i \leq n$ will work, hence there is $n-t+1$ of these. If on the other hand $t < n/2$, then any $i/2 \leq t \leq i$ will work, so $t\leq i \leq 2t$ and hence we have $t+1$ possibilities. We can combine these as $\min(t+1,n-t+1)=\min(t,n-t)+1$. So the value simplifies to
\begin{align}
\boxed{P_n(y)=\sum_{t=0}^{n}\frac{\min(t,n-t)+1}{y^{3t-n+3}}}
\end{align}


text:
Q: Call function from argument of another function I need to call a function in different function from its arguments.
class LST {
public:
  char *value;
  LST *Next;
};
bool Is_Even(LST *el) {
  return true;
}
void For_Each_el(LST *&el, bool f) {
  LST *H = el;
  while (H) {
    if (f(H)) //this line causes the error
      Current = H;
    H = H->Next;
  }
}

Here is the error:
error C2064: the result of evaluating the fragment is not a function that takes one argument

(translated from russian)
So, this code doesn't work.
Here is how I call it in the main() function:
int main() {
  Head = new LST;
  Head->value = "4";
  For_Each_el(Head, Is_Even(Head));
  _getch();
}

A: First, create a typedef to a function pointer:
typedef bool(*test_LST)(LST*);

Then change the signature of your for each function:
void For_Each_el(LST *&el, test_LST f)

finally change how you call it in main:
For_Each_el(Head, Is_Even);

You can also use a typedef std::function<bool(LST*)> test_LST; instead of the above typedef to allow for function object for-each iteration, or write For_Each_el as a template function.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can my client submit app to the app store I have developed an app for a client and am trying to help them submit to the app store.  I am struggling with the process.  When they try to submit they are asked to specify the bundle ID.  This to me implies that they need to create the app id, request a distro certificate and then create the distro provisioning files. I assume then I need to build the app using their provisioning profile.  The problem is when I try to import the provisioning files I get an error indicating "a valid signing identity could not be found in your keychain'.
Does anyone have a link to instructiona outlining the correct process for this?

A: First of all, make sure to get the Keychain stuff on your machine. On the Provisioning Profile Portal download the WWDR certificate and install it on your machine. Then, get a distribution certificate by going the tab "Distribution". You will have to generate a Certification Request on Keychain and upload it.
The next part is to generate an AppID. To do this, go to the App IDs section and click on the "New app ID" button. Enter the domain for your application(i.e. com.apple.ichat).
Now go to the provisioning section and on the Distribution tab click on New Profile. On the Distribution Method select "App Store". On the profile name enter the name for you profile. Don't forget to select the App ID you've just created and click on "Submit".
Download and install the Provisioning Profile by double clicking on it. On your Xcode project window, expand the targets(it's located on  "Groups and Folders"). A property window will open. First go to the Properties tab and on the field identifier enter the domain you entered on your app ID. On the build tab you will see an item called "Configuration", click on it then click on edit configurations. Duplicate the "Release" configuration and name it to "Distribution". Now on the build tab select "Distribution" as the configuration. Type "code sign" on the search field. Expand "Code Signing Identity" and on the first field select "Any iPhone OS Device". On the second field select "iPhone Distribution". Now compile it using this configuration and it will be ready to submit to the App Store.


text:
Q: CMake finds Boost but the imported targets not available for Boost version I use CMake to find Boost. Boost is found, but CMake errors out with

Imported targets not available for Boost version

See the complete error (from macOS) below. What am I doing wrong?
CMake Warning at /Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:743 (message):
  Imported targets not available for Boost version 106300
Call Stack (most recent call first):
  /Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:842 (_Boost_COMPONENT_DEPENDENCIES)
/Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:1395 (_Boost_MISSING_DEPENDENCIES)
CMakeLists.txt:6 (find_package)

Boost version: 1.63.0
Found the following Boost libraries:
  thread
CMake Warning at /Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:743 (message):
  Imported targets not available for Boost version 106300
Call Stack (most recent call first):
  /Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:842 (_Boost_COMPONENT_DEPENDENCIES)
  /Applications/CMake.app/Contents/share/cmake-3.6/Modules/FindBoost.cmake:1395 (_Boost_MISSING_DEPENDENCIES)
  CMakeLists.txt:7 (find_package)

A: Your CMake version is too old. Update CMake and it will work.
CMake cannot detect the dependencies between the different Boost libraries. They have explicitly implemented in FindBoost.
For every Boost release this information is added by the CMake maintainers and it gets part of the next CMake release. So you have to make sure, that your CMake version was released after the Boost version you try to find.
Boost 1.63 requires CMake 3.7 or newer.
Boost 1.64 requires CMake 3.8 or newer.
Boost 1.65 and 1.65.1 require CMake 3.9.3 or newer.
Boost 1.66 requires CMake 3.11 or newer.
Boost 1.67 requires CMake 3.12 or newer.
Boost 1.68, 1.69 require CMake 3.13 or newer.
Boost 1.70 requires CMake 3.14 or newer.
Boost 1.71 requires CMake 3.15.3 or newer.
Boost 1.72 requires CMake 3.16.2 or newer.
Boost 1.73 requires CMake 3.17.2 or newer.
Boost 1.74 requires CMake 3.19 or newer.
Boost 1.75 requires CMake 3.19.5 or newer.
Boost 1.76 requires CMake 3.20.3 or newer.
Boost 1.77 requires CMake 3.21.3 or newer.
Boost 1.78 requires CMake 3.22.2 or newer.
Boost 1.79 requires CMake 3.23.2 or newer.
Boost 1.80 requires CMake 3.24.2 or newer.
Boost 1.81 requires CMake 3.25.2 or newer.
Without FindBoost
Starting with version 1.77, Boost provides a BoostConfig.cmake that obsoletes FindBoost and the required changes. Using
find_package(Boost CONFIG)

does exclude the FindBoost file and searches only for the config file.
For compatibility CMake will remain providing FindBoost.

A: I just wanted to post the following work around, as it's far easier than upgrading CMake on the systems I'm working on where I do not have root/sudo access. Set BOOST_INCLUDEDIR and BOOST_LIBRARYDIR directly when invoking CMake.
cmake  -DBOOST_INCLUDEDIR=... -DBOOST_LIBRARYDIR=... ...

This may not work if Boost changed dependencies between the list hard coded in the module that ships with CMake and the boost version that you are using. It will take you 30 sec to try vs 30 min to install cmake from source.


text:
Q: No self parameter passed in overrided python class' method Take a look at this code:
class SomeClass:
    def __init__(self):
        self._value = 'Hello, World!'

    def func(self):
        return self._value

instance = SomeClass()

print(instance.func())

def new_func(self):
    return self._value + '!!!!!'

instance.func = new_func

print(instance.func())

This code creates an instance of SomeClass, calls original func, then overrides this function and calls it again.
I want to override a function in a single instance of a class, but not in the entire class so all the instances got the function overrided.
I expect this code to print:
Hello, World!
Hello, World!!!!!

But it prints:
Hello, World!
Traceback (most recent call last):
  File "test.py", line 17, in <module>
    print(instance.func())
TypeError: new_func() missing 1 required positional argument: 'self'

The self argument is not passed to the overrided function. Why? Aren't SomeClass.func(instance) and instance.func() the same?
How to override the function correctly so I can access the self argument in the overrided function?

A: Well let's see
The func of the original instance has type bound method
SomeClass().func

# <bound method SomeClass.func of <__main__.SomeClass object at 0x7f293e1cb3d0>>

and your func has type function
instance.func

# <function __main__.new_func(self)>

The idea is to get a new method of some new class like this:
class SomeNewClass:
    def new_func(self):
        return self._value + '!!!!!'

instance.func = SomeNewClass().new_func
instance.func

# <bound method SomeNewClass.new_func of <__main__.SomeNewClass object at 0x7f293e2825d0>>

But as you see, this is a method of the new class :(
By the way, if you don't initialize the class, the type will change to function:
class SomeNewClass:
    def new_func(self):
        return self._value + '!!!!!'

instance.func = SomeNewClass.new_func
instance.func

# <function __main__.SomeNewClass.new_func(self)>

So the next idea is to change the method before the initialization of a class:
SomeClass.func = new_func
instance = SomeClass()
instance.func

# <bound method new_func of <__main__.SomeClass object at 0x7f29441e4350>>

Seems good. The result based on your code:
class SomeClass:
    def __init__(self):
        self._value = 'Hello, World!'

    def func(self):
        return self._value

instance = SomeClass()

print(instance.func())

def new_func(self):
    return self._value + '!!!!!'

SomeClass.func = new_func
instance = SomeClass()

print(instance.func())

# Hello, World!
# Hello, World!!!!!!

If you need to change the method of an instance and not of the class. There is also a way to do that using types.MethodType:
import types

class SomeClass:
    def __init__(self):
        self._value = 'Hello, World!'

    def func(self):
        return self._value

instance = SomeClass()

print(instance.func())

def new_func(self):
    return self._value + '!!!!!'

instance.func = types.MethodType(new_func, instance)

print(instance.func())

# Hello, World!
# Hello, World!!!!!!


text:
Q: Typescript Generic List Type Narrowing I'm struggling to understand why I'm getting an error with this code.
type Foo = "foo" | "FOO";
type Bar = "bar" | "Bar";

type FooBar = Foo | Bar;

function isFoo(f: FooBar): f is Foo {
  return f === "foo";
}

function isBar(b: FooBar): b is Bar {
  return b === "bar";
}

function convertToUpperCaseForm<T extends FooBar>(i: T): T {
  if (isFoo(i)) return "FOO";
  else return "bar";
}

function doSomething<T extends FooBar>(items: T[]): T[] {
  if (items.length === 0) return [];
  else if (items.length === 1 && isFoo(items[0])) return ["FOO"];
  else return items.map(convertToUpperCaseForm)
  /**
    * Return a list of the same type. If I put a list of Foo
    * in I want a list of Foo out.
    */
}

Basically I'm saying I have a list that takes a generic which is a type union. If the first item in that list is one of the types, return another object of that same type. However, this is giving me the error:
Type '"foo"' is not assignable to type 'T'.
'"foo"' is assignable to the constraint of type 'T', but 'T' could
be instantiated with a different subtype of constraint 'FooBar'.

Now, the reason I think this should work is that with the (isFoo(items[0])) check we have confirmed that a list of type T[]'s first elemnt is of type Foo, ergo, T must be at least of type Foo, so returning "foo" is a legal return of type T.
Is this a bug in Typescript? Is there a way I can work around this without type assertions? I believe it's typesafe, but I know with these kinds of errors there's usually a good explanation.
EDIT1: This isn't a perfect example of what I have in my codebase. A few people have pointed out things that aren't issues in my codebase. Just know that this is the error I'm getting, I do need the generic, and I do need to return an object of the same type I put in.
Edit2: Updated code snippet to reflect my codebase. I'm getting the same error in the convertToUpperCaseForm function.
Type '"FOO"' is not assignable to type 'T'.
'"FOO"' is assignable to the constraint of type 'T', but 'T' could
be instantiated with a different subtype of constraint 'FooBar'.

I find this really odd because I was under the impression that this was a result of the Array index. if convertToUpperCaseForm receives an object of type Foo, it should allow me to return an object of type Foo.

A: why you need the genric if you already know the type?
type Foo = "foo";
type Bar = "bar";

declare type FooBar = Foo | Bar;

function isFoo(f: FooBar): f is Foo {
  return f === "foo";
}

function isBar(b: FooBar): b is Bar {
  return b === "bar";
}

function doSomething(items: FooBar[]): FooBar {
  if (isFoo(items[0])) return "foo";
  if (isBar(items[0])) return "bar";
  return items[0];
}

console.log(doSomething(["foo", "bar"]));

// bar

A: There is a flaw in your logic (the signature is wrong):
function convertToUpperCaseForm<T extends FooBar>(i: T): T {
  if (isFoo(i)) return "FOO";
  else return "bar";
}

Let's say i is of type "foo", meaning that T is "foo". The function is supposed to return something of the same type, T, so "foo" but you returned "FOO" which is different from "foo".
const i = "foo" // i: "foo"
convertToUpperCaseForm(i) // (i: "foo"): "foo"

function convertToUpperCaseForm<T extends FooBar>(i: "foo"): "FOO" {

So you cannot say it takes T and returns T because as you can see, there is a case where it doesn't work.


text:
Q: JavaFX : Button never sets a graphic EDIT :
A MCVE version of my code has been made to help debug it. It reproduces my bug. The purpose of my code is doing a Memory game. Which means that when it is your turn, you "open" a card, then another one. If they form a pair, they don't get turned over, they stay open. Otherwise, you turn them back over and try to find a pair on the next turn.
Simply put, the bug is : when you are opening the second card of your turn and both cards don't form a pair, the second one never gets opened!
Hopefully, this version of my code will help you to find the bug, which will help me a lot!
I have put the code on Github : https://gist.github.com/anonymous/e866671d80384ae53b53
(And you will find it attached at the end of the question)

Explanation of the issue
I am having fun on doing a little Memory game in JavaFX and I came across this strange behavior where the card I click on (represented by a custom class that extends the Button class) never changes the image displayed.
Normally, when I click on the card, it "opens" itself by changing the graphic it displays.
The strange and annoying thing is that it only happens in a specific case.
The behavior of my card is correct when I "open" the first card of the turn of the player. It also works when I "open" a second one and both cards are a pair. Sadly, it doesn't work only in the case where I want to open a second card and it doesn't match as a pair with the first one.
I modified the Button class by adding openCard() and closeCard() methods. Those methods will set a specific graphic on the button-card.
I will now show some code but it is hard to tell what might be the part that is making this behavior happen. Even more so that I am using Eclipse but can't possibly figure out how to debug a JavaFX app with breakpoints (I am using console prints) because the app will eventually crash when I reach my breakpoints and start crawling through the lines of code.

The code
Firstly, the modified Button class :
public class Card extends Button{
private String cardDesign;

public Card(int row, int column){
  this.setGraphic(new ImageView("/resources/card_back.png"));
  this.setBackground(new Background(new BackgroundFill(Color.SLATEGRAY,
      new CornerRadii(6), null)));
}

public void setOpenCardDesign(String design){ cardDesign = design; }

public void openCard(){ this.setGraphic(new ImageView(cardDesign)); }

public void closeCard(){
  this.setGraphic(new ImageView("/resources/card_back.png"));
}

}
Now the controller class, the event is set on a MouseEvent. There is more code in this controller (like checking if there is a pair), but this isn't an issue here I think as the problem is already at the line where I call the method to open the card.
I use the  getSource() method here because my cards are arranged in a gridPane and I need to know which one has been clicked on.
@Override
public void handle(MouseEvent event) {
  //Get the card that was clicked on
  Card card = (Card) event.getSource();
  //Open the card
  card.openCard();
  //Do some more after this...

}

That's pretty much it as from what I could figure out.
As already stated, I tried to check if the method openCard() is being called. It is as some comment printed in my console showed up. I even added some console printing just before and just after the line where I set the graphic and they both are showing up. I can't know for sure what happens when my app reaches the setGraphic() line as nothing is showing up in my app (the card remains closed).
Any hint would help because I am slowly sinking in madness right now.
Thank you in advance.

The MCVE version of my code
The card object : Card.java
package memory;

import javafx.scene.control.Button;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.paint.Color;

public class Card extends Button{
//-------------------------------------------------
  //Store the position of the card
  private int row;
  private int column;
//-------------------------------------------------
  //Constructor
  public Card(int row, int column){
    //Give the cards a specific color at init
    this.setBackground(new Background(new BackgroundFill(Color.DEEPSKYBLUE,
        new CornerRadii(6), null)));
    this.setText("CLOSED");
    this.row = row;
    this.column = column;
  }
//-------------------------------------------------
  //Open the card
  public void openCard(){
    System.out.println("OPEN");
    //Cards are red when open
    this.setBackground(new Background(new BackgroundFill(Color.RED,
      new CornerRadii(6), null)));
    this.setText("OPEN");
  }
//-------------------------------------------------
  //Close the card
  public void closeCard(){
    System.out.println("CLOSE");
    //Cards are blue when closed
    this.setBackground(new Background(new BackgroundFill(Color.DEEPSKYBLUE,
        new CornerRadii(6), null)));
    this.setText("CLOSED");
  }
//-------------------------------------------------
  //Getters for row and column info
  public int getRow() { return row; }
  public int getColumn() { return column; }
}

The main (includes the view and start point of the app) : Main.java
package memory;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {

//-------------------------------------------------
  //The layout and the cards
  GridPane gridCard = new GridPane();
  static Card [][] cardArray;
  //The event handler
  private static EventHandler<MouseEvent> handler;
  //The array which remembers the pairs and the reminder of last open card
  static int[][] indexArray;
  static int index;
  //Boolean array to check if the card is already open
  static boolean[][] isOpen;
  //Number of pairs to find
  static int pairs = 5;
//-------------------------------------------------
  //Cheap main
  public static void main(String[] args) {
    Application.launch(args);
  }
//-------------------------------------------------
  @Override
  public void start(Stage primaryStage) throws Exception {

    //Init the event handler
    handler = new Controller();

    //Some formatting for the grid pane
    gridCard.setHgap(10);
    gridCard.setVgap(10);
    gridCard.setPadding(new Insets(0, 10, 0, 10));
    gridCard.setAlignment(Pos.CENTER);

    //Creating our card board, index array and bool array
    cardArray = new Card [2][5];
    indexArray = new int [2][5];
    isOpen = new boolean [2][5];
    //Adding the cards to our card array
    for(int i = 0; i < 2; i++){
      for(int j = 0; j < 5; j++){
        cardArray[i][j] = new Card(i, j);
        //Make those buttons look like cards
        cardArray[i][j].setPrefHeight(100);
        cardArray[i][j].setPrefWidth(70);
        //Register the event
        cardArray[i][j].addEventHandler(MouseEvent.MOUSE_CLICKED, gameController());
        //Add those cards
        gridCard.add(cardArray[i][j], j, i);
        //Set the pairs (no randomness here)
        indexArray[i][j] = j+1;
      }
    }
    //Print out the indexes of all the cards
    System.out.println("----------------");
    System.out.println("Card indexes :");
    for (int i = 0; i < indexArray.length; i++) {
      System.out.println();
      for (int j = 0; j < indexArray[0].length; j++) {
        System.out.print(indexArray[i][j]+ " | ");
      }
      System.out.println();
    }
    System.out.println("----------------");

    //Set BorderPane
    BorderPane root = new BorderPane();
    root.setBackground(new Background(new BackgroundFill(Color.BLACK,
        CornerRadii.EMPTY, null)));
    root.setCenter(gridCard);

    //Set the stage
    primaryStage.setScene(new Scene(root));
    primaryStage.setTitle("Memory Test");
    primaryStage.show();

  }
//-------------------------------------------------
  //Getter for the event handler
  public static EventHandler<MouseEvent> gameController() {
    return handler;
  }
//-------------------------------------------------
  //Getter, Setter and "resetter" for the index
  public static void resetIndex() { index = 0; }
  public static int getIndex() { return index; }
  public static void setIndex(int i) {
    index = i;
  }
//-------------------------------------------------
}

The controller : Controller.java
package memory;

import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.MouseEvent;

public class Controller implements EventHandler<MouseEvent>{

//-------------------------------------------------
  @Override
  public void handle(MouseEvent event) {
    //Get the card which cas clicked on
    Card card = (Card) event.getSource();

    //If the card was already open, don't do anything
    if (!Main.isOpen[card.getRow()][card.getColumn()]) {
      //Open the card
      card.openCard();

      //We opened the first card of the turn
      if (Main.getIndex() == 0) {

        //Set the card as open
        Main.isOpen[card.getRow()][card.getColumn()] = true;
        //Remember the index
        Main.setIndex(Main.indexArray[card.getRow()][card.getColumn()]);
        System.out.println("index: "+Main.getIndex());

      //We opened the second card
      }else if (Main.getIndex() != 0) {

        //Check if it is a pair
        if (Main.getIndex() == Main.indexArray[card.getRow()][card.getColumn()]) {

          //Decrement the number of pairs
          Main.pairs--;
          //Open the second card
          Main.isOpen[card.getRow()][card.getColumn()] = true;
          //Reset the index
          Main.resetIndex();

        }else{ //Close both cards if it isn't a pair
          //Wait 0.7 second to let the player remember the cards
          try {
            Thread.sleep(700);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          //Close the current card
          card.closeCard();
          System.out.println("index : " + Main.indexArray[card.getRow()][card.getColumn()]);
          Main.isOpen[card.getRow()][card.getColumn()] = false;
          //Close the first opened card by looking at the index
          //It closes both cards with the same index, but it doesn't matter
          //as the pair hasn't been found anyway
          for (int i = 0; i < Main.indexArray.length; i++) {
            for (int j = 0; j < Main.indexArray[0].length; j++) {
              if (Main.getIndex() == Main.indexArray[i][j]) {
                Main.cardArray[i][j].closeCard();
                System.out.println("index: " + Main.indexArray[i][j]);
                Main.isOpen[i][j] = false;
              }
            }
          }
          //Reset the index of last opened card
          Main.resetIndex();
        }
      }
    }

    //Check endgame
    if (Main.pairs == 0) {
      //Show a dialog box
      Alert incorrectPairs = new Alert(AlertType.INFORMATION);
      incorrectPairs.setTitle("GAME OVER");
      incorrectPairs.setHeaderText("The game is over");
      incorrectPairs.setContentText("You found all the pairs, congrats!");
      incorrectPairs.showAndWait();
    }
  }
//-------------------------------------------------
}

A: You're blocking the UI thread with Thread.sleep(...). That prevents any pending changes from being repainted, so you don't see the first update at all; you only see the subsequent updates after the pause is complete.
The simplest way to implement a pause on the UI thread is to use a PauseTransition from the JavaFX animation API. Basically, you do
PauseTransition pause = new PauseTransition(Duration.millis(700));
pause.setOnFinished(e -> {
    // code to execute after pause...
});
pause.play();

In your case, you probably want to disable the user interface, so the user cannot click on anything during the pause, so you could do something like
PauseTransition pause = new PauseTransition(Duration.millis(700));
pause.setOnFinished(e -> {
    card.closeCard();

    // ... etc...

    card.getParent().setDisable(false);
});

card.getParent().setDisable(true);
pause.play();


text:
Q: Usage of apostrophe within the words to distinguish substantives from verbs Consider the following statements:

*

*There has been a 10% decrease in the value.

*The value may decrease 10% next month.
In the first sentence, decrease is a substantive while it's a verb in the second one. There's no way to distinguish their class other than by the context.
That's what I thought until a friend insisted that, in these cases, susbtantives must be written as 'decrease and verbs de'crease, which, in over 8 years of study, I've never seen before. He just won't accept it doesn't exist. Therefore, is it even right? If not (I'm confident it's not!), how can I prove him it's not a thing?

A: I think your friend is talking about pronunciation rather than writing.
In speech, when "decrease" is a noun, the stress goes on the first syllable: "decrease". When "decrease" is a verb, the stress goes on the second syllable: "decrease". The writing does not distinguish them.
Many English verbs follow this pattern. There is a tendency in English to put the accent of a noun on the first syllable, and a countertendency to put the accent of a multisyllable verb on the second syllable. This is a tendency, not a rule (like most things in English).
Here are some more examples:

The suspect is in custody. The police suspect that he robbed a bank.
If you don't object, I'll just throw that object into the garbage can.
George rejected my screenplay. He threw it into pile with all the other rejects.
There's a new book coming out under this publisher's imprint. It's about how geese are imprinted with their mother's appearance shortly after birth.


text:
Q: Is there an application that moves menulets from the menu bar, and shows them in a little window? Is there a utility that shows the menulets in a window in the style of the old Control Strip (which means a window that automatically shows and hides)?

A: It's not exactly the style used by the old Control Strip, but Bartender hides the menu extra icons, and show them in a little window that appears when clicking on its menu extra icon.

*

*Lets you tidy your menu bar apps how you want.

*See your menu bar apps when you want.

*Hide the apps you need to run, but do not need to see.

*Have the clean looking menu bar you want.

*Rearrange your menu bar items as you wish.

For each icon shown in the Menu Bar, it let you decide where the icon should be shown (Bartender Bar versus Manu Bar), and how long the item should be shown when it is updated.

A: Short answer is no.
The menulets are controlled by SystemUIServer, a system application in charge of a number of things one of them being the right side of the menu bar. Unfortunately SystemUIServer is not replaceable, and its behavior cannot be changed.
Note that there are multiple kinds of 'menulets':

*

*System provided menus (the clock, airport signal, time machine...). These do use a private API as they run code inside SystemUIServer and Apple doesn't like people loading code in this sensitive piece of software. Those are present on disk with a '.menu' extension. Those are sitting on the right of the menu bar.

*Third party menus using the private API without Apple blessing. Those usually use a hack to bypass Apple protection (most common hack is MenuCracker, code is on SourceForge). Some of those menus are good and respectful of their environment, some of them are not. Those menulets are freely mixable with the system ones, you can ⌘-drag and drop them to reorder them.

*Applications deciding to provide a quick access menu on the menubar. Those do run in their own process and use a public API to place themselves on the menubar. You cannot reorder them and they always sit on the left of the system menus. SystemUIServer control those icons placement.
It could be possible to write an application capable of loading menulets by emulating the private API, but a number of things will not work as expected (toggle in preferences will not toggle in this app, I'm not sure that some menulets do not use some of SystemUIServer internals...). And anyway, no matter what you do there is no way to control the application positions.

A: A quick Google search landed me on this: Return of Control Strip [macworld.com]
I am not really sure whether this will help you because I have never used Mac OS Classic.

A: Although I do not know of any utility that shows the menulets in a little window, I do know how to move the menulets.
Holding command while pressing down on any of the menulets will allow you to move them.
You can try it on any Apple-made menulet products except Spotlight.


text:
Q: how to convert a string to a bool I have a string that can be either "0" or "1", and it is guaranteed that it won't be anything else.
So the question is: what's the best, simplest and most elegant way to convert this to a bool?

A: Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:
bool val =  Convert.ToBoolean("true");
or an extension method to do whatever weird mapping you're doing:
public static class StringExtensions
{
    public static bool ToBoolean(this string value)
    {
        switch (value.ToLower())
        {
            case  "true":
                return true;
            case "t":
                return true;
            case "1":
                return true;
            case "0":
                return false;
            case "false":
                return false;
            case "f":
                return false;
            default:
                throw new InvalidCastException("You can't cast that value to a bool!");
        }
    }
}

A: I made something a little bit more extensible, Piggybacking on Mohammad Sepahvand's concept:
    public static bool ToBoolean(this string s)
    {
        string[] trueStrings = { "1", "y" , "yes" , "true" };
        string[] falseStrings = { "0", "n", "no", "false" };

        if (trueStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return true;
        if (falseStrings.Contains(s, StringComparer.OrdinalIgnoreCase))
            return false;

        throw new InvalidCastException("only the following are supported for converting strings to boolean: "
            + string.Join(",", trueStrings)
            + " and "
            + string.Join(",", falseStrings));
    }

A: I know this doesn't answer your question, but just to help other people. If you are trying to convert "true" or "false" strings to boolean:
Try Boolean.Parse
bool val = Boolean.Parse("true"); ==> true
bool val = Boolean.Parse("True"); ==> true
bool val = Boolean.Parse("TRUE"); ==> true
bool val = Boolean.Parse("False"); ==> false
bool val = Boolean.Parse("1"); ==> Exception!
bool val = Boolean.Parse("diffstring"); ==> Exception!

A: I used the below code to convert a string to boolean.
Convert.ToBoolean(Convert.ToInt32(myString));

A: Here's my attempt at the most forgiving string to bool conversion that is still useful, basically keying off only the first character.
public static class StringHelpers
{
    /// <summary>
    /// Convert string to boolean, in a forgiving way.
    /// </summary>
    /// <param name="stringVal">String that should either be "True", "False", "Yes", "No", "T", "F", "Y", "N", "1", "0"</param>
    /// <returns>If the trimmed string is any of the legal values that can be construed as "true", it returns true; False otherwise;</returns>
    public static bool ToBoolFuzzy(this string stringVal)
    {
        string normalizedString = (stringVal?.Trim() ?? "false").ToLowerInvariant();
        bool result = (normalizedString.StartsWith("y")
            || normalizedString.StartsWith("t")
            || normalizedString.StartsWith("1"));
        return result;
    }
}

A:     private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };

public static bool ToBoolean(this string input)
{
                return input != null && PositiveList.Any(λ => λ.Equals(input, StringComparison.OrdinalIgnoreCase));
}

A: bool b = str.Equals("1")? true : false;

Or even better, as suggested in a comment below:
bool b = str.Equals("1");

A: Quite simple indeed:
bool b = str == "1";

A: I use this:
public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }

A: I love extension methods and this is the one I use...
static class StringHelpers
{
    public static bool ToBoolean(this String input, out bool output)
    {
        //Set the default return value
        output = false;

        //Account for a string that does not need to be processed
        if (input == null || input.Length < 1)
            return false;

        if ((input.Trim().ToLower() == "true") || (input.Trim() == "1"))
            output = true;
        else if ((input.Trim().ToLower() == "false") || (input.Trim() == "0"))
            output = false;
        else
            return false;

        //Return success
        return true;
    }
}

Then to use it just do something like...
bool b;
bool myValue;
data = "1";
if (!data.ToBoolean(out b))
  throw new InvalidCastException("Could not cast to bool value from data '" + data + "'.");
else
  myValue = b;  //myValue is True

A: string sample = "";

bool myBool = Convert.ToBoolean(sample);

A: If you want to test if a string is a valid Boolean without any thrown exceptions you can try this :
    string stringToBool1 = "true";
    string stringToBool2 = "1";
    bool value1;
    if(bool.TryParse(stringToBool1, out value1))
    {
        MessageBox.Show(stringToBool1 + " is Boolean");
    }
    else
    {
        MessageBox.Show(stringToBool1 + " is not Boolean");
    }

outputis Boolean
and the output for stringToBool2 is : 'is not Boolean'


text:
Q: Simplex Method Problem We consider the constraint equation is $Ax=b$ where $A$ is a $m \times n$ matrix.
I know that in phase one of the Simplex method, we should find a vertex/corner of feasible set.
I'm confused that why the corner must have $m$ nonzero components and $n-m$ zero components?
How to understand VERTEX/CORNER from the perspective of geometry and algebra?

A: Each equation in the constraint is one hyperplane that represents one face of the constraint set polytope.
When you are on one face, the corresponding equation is solved to equality (because all points on the hyperplane solve the equation of the hyperplane itself).
If you are on a corner of two faces, you can think of each face individually as a hyperplane, then the point is on both hyperplanes, and you see that two equations must be solved to equality.
You can generalize this to $m$ hyperplanes and you see that all the equations of all the hyperplanes that create the corner or vertex your point is in have to be solved to equality, so they have to be zero.


text:
Q: Webkit Keyframes not working I want to use keyframes to make a client's site logo (just text using @font-face) fade in and out of different colors. Somehow, I can't get this to work at all!
@-webkit-keyframes colorPulse { 0% {color: rgba(236, 250, 42, 0.6);}
50% {color: rgba(253, 149, 223, 0.6);} 100% {color: rgba(1, 218, 213, 0.6);} }

#site-logo {
font-family: KaBlamo;
font-size: 90px;
text-align: center;
width: 100%;
position: absolute;
top: 30px;
margin: 20px 0 .4em;
-webkit-animation: colorPulse 15s infinite alternate;
}

A: For me your code works pretty good:
https://jsfiddle.net/3frdpw4h/
Which browser are you using? Maybe you have to supply the unprefixed animation property + keyframes rule?
@-webkit-keyframes colorPulse {
    0% {color: rgba(236, 250, 42, 0.6);}
    50% {color: rgba(253, 149, 223, 0.6);}
    100% {color: rgba(1, 218, 213, 0.6);}
}
@keyframes colorPulse {
    0% {color: rgba(236, 250, 42, 0.6);}
    50% {color: rgba(253, 149, 223, 0.6);}
    100% {color: rgba(1, 218, 213, 0.6);}
}

#site-logo {
    font-family: KaBlamo;
    font-size: 90px;
    text-align: center;
    width: 100%;
    position: absolute;
    top: 30px;
    margin: 20px 0 .4em;
    -webkit-animation: colorPulse 15s infinite alternate;
    animation: colorPulse 15s infinite alternate;
}


text:
Q: p-group with abelian centralizer I will be so thankful if someone helps me with the following question. There exists  finite non-abelian p-groups G (except non-abelian groups of order $p^3$) with the following properties:

*

*all non-central elements have abelian centralizer.

*cs(G) has exactly two integers, where cs(G) is the set of all sizes of conjugacy classes of G.

A: Let be $G=F/F^p[F,F,F]$, with $F$ denotes the free group on $n$ generators. Then $G$ satisfies $Z(G) = \Phi (G)=G'$.
If $x \in G-Z(G)$ then  $C_G(x)= \langle x, Z(G) \rangle$ which is abelian as $C_G(x)/Z(G)$ is cyclic.  Now we have your condition (1).  For (2) observe that $C_G(x)$ has index $p^{n-1}$ in $G$, whenever $x \notin Z(G)$.
You can also consider any non-abelian $p$-groups (of order $>p^3$) with a center of index $p^2$. Clearly, for such a group the centralizer of any non-central element $x$ is a maximal subgroup, so has index $p$.

A: Any nonabelian $p$-group with center of index $p^2$  satisfies conditions 1 and 2.
Such groups were studied by Isaacs-Passman.


text:
Q: Python argparse: Combine optional parameters with nargs=argparse.REMAINDER I must be missing something obvious. The goal is to use argparse with the first parameter required, a second optional and any other remaining parameters optional.
To show the issue I made two test parsers; the only difference between them is using nargs=argparse.REMAINDER in one and nargs='*' in the other.
def doParser1(argsin):
    parser = argparse.ArgumentParser(description='Parser demo.')
    parser.add_argument('req1', help='first required parameter')
    parser.add_argument('--opt1', help='first optional parameter')
    parser.add_argument('leftovers', nargs=argparse.REMAINDER,
                    help='all the other parameters')
    argsout = parser.parse_args(args=argsin)
    print argsout
    return argsout

def doParser2(argsin):
    parser = argparse.ArgumentParser(description='Parser demo.')
    parser.add_argument('req1', help='first required parameter')
    parser.add_argument('--opt1', help='first optional parameter')
    parser.add_argument('leftovers', nargs='*',
                    help='all the other parameters')
    argsout = parser.parse_args(args=argsin)
    print argsout
    return argsout

If there are no extra parameters, parser2 works. This is the input followed by parser1 and parser 1:
input: ['req1value', '--opt1', 'opt1value']
Namespace(leftovers=['--opt1', 'opt1value'], opt1=None, req1='req1value')
Namespace(leftovers=None, opt1='opt1value', req1='req1value')

If there are extra parameters, the opt1 value is missed in parser1 and parser2 just gets confused:
input: ['req1value', '--opt1', 'opt1value', 'r1', 'r2']
Namespace(leftovers=['--opt1', 'opt1value', 'r1', 'r2'], opt1=None, req1='req1value')
usage: py-argparse.py [-h] [--opt1 OPT1]
                  [-leftovers [LEFTOVERS [LEFTOVERS ...]]]
                  req1
py-argparse.py: error: unrecognized arguments: r1 r2

The expected output should be:
Namespace(leftovers=['r1', 'r2'], opt1='opt1value', req1='req1value')

It seems this should be a simple case and what is here is simplified from what I'm really trying to do. I've tried making leftovers optional, adding a variety of other options, but nothing works any better.
Any help would be appreciated.

A: You could use parse_known_args:
import argparse
parser = argparse.ArgumentParser(description='Parser demo.')
parser.add_argument('req1', help='first required parameter')
parser.add_argument('--opt1', help='first optional parameter')

args, leftovers = parser.parse_known_args(['req1value', '--opt1', 'opt1value'])
print(args, leftovers)
# (Namespace(opt1='opt1value', req1='req1value'), [])

args, leftovers = parser.parse_known_args(['req1value', '--opt1', 'opt1value', 'r1', 'r2'])
print(args, leftovers)
# (Namespace(opt1='opt1value', req1='req1value'), ['r1', 'r2'])

A: --opt1 needs to come before "unnamed" arguments.  Your real test cases should be:
    ['--opt1', 'opt1value', 'req1value']

and
    ['--opt1', 'opt1value', 'req1value', 'r1', 'r2']

A: The inter mixing of positionals and optionals is tricky when one or more of the positionals is of the 'zero or more' type (? * REMAINDER).   The simple solution is to not mix them - give the optionals first, then all the positionals afterwards.
Here's what's going on:
input: ['req1value', '--opt1', 'opt1value']
Namespace(leftovers=['--opt1', 'opt1value'], opt1=None, req1='req1value')

Because of the req1value string the parser first parses for positionals.  req1 wants 1 string, leftovers grabs everything else including --opt1.
Namespace(leftovers=None, opt1='opt1value', req1='req1value')

With * leftovers is satisfied with [], no string, hence None (actually I get []).  --opt1 is parsed as an optional.
input: ['req1value', '--opt1', 'opt1value', 'r1', 'r2']
...
py-argparse.py: error: unrecognized arguments: r1 r2

As before * leftovers is set to [].  -opt1 is processed.  But now there are 2 strings with no place to put them.  You intended them to go into leftovers, but that was already used.  If leftovers was + it would have taken them  as you intended.
The key is that when it tries to parse the 1st positional, it also tries to parse all the positionals that it can.   At one level parse_args is doing re.match('(A)(A*)','AOA') producing groups ('A', '').
There are 2 proposed patches that deal with this issue.  One uses the 2 step parse_known_args to allow a complete mixing of optionals and positionals.  This is the kind of behavior that users of optparse might have come to expect.
The other patch tries to delay the handling of positionals that can accept 0 argument strings http://bugs.python.org/issue15112 .


text:
Q: How to configure webpack for implementing CSP I currently have a Web Application with Django and React. Started implementing CSP from django and everything going well untill now, added all sources of external scripts. Im currently bumping to this webpack problem:
First we weren't using devtools options, and in that way, the code was build using eval(). eg;
/***/ (function(module, exports) {

eval("function _arrayLikeToArray(arr, len) {
  if (len == null || len > arr.length) len = arr.length;\n\n  for (var i = 0, arr2 = new Array(len); i < len; i++) ...
and evals like that

methods everywhere on the production code. Since CSP doesn't allow to safelly use eval expressions (and I dont want to use unsafe-eval option because damages the security), I saw this github thread to use devtool: source-map for bundling without the eval expressions.
When I rebuild my code, the problem is still occuring. The rebuild code:
"build:dev": "cross-env NODE_ENV=production INDEX_FILE=dev webpack --mode production --progress --colors --config webpack/webpack.config.prod.js"
The devtool config is inside this webpack.config.prod.js file.
What should I do?


text:
Q: best way to compare items inside a loop i have a collection of objects.  i need to loop through the collection and generate another collection.  each item in the second collection is a function of two items in the first collections.  So to simplify the problem.
Lets assume the collection is a set of ints.
 List<int> myIntCollection = new List<int>() {1, 4, 6, 8, 7};

i need to generate a second collection in which each item is the sum of 2 of the items in the first collection. so the second collection would have these elements after the conversion.
 List<int> generatedCollection = new List<int>() {5, 10, 14, 15};

as you can see the first element is 5 (which is the sum of the first two items in the top collection), the second elemtn is 10, which is hte sum of the second and third item in the first collection and so on . .

A: You can use a for loop:
List<int> result = new List<int>(source.Count - 1);

for (int i = 0; i < source.Count - 1; i++)
    result.Add(source[i] + source[i + 1]);

That wasn't hard!

A: int i = 0;
generatedCollection.AddRange(
            myIntCollection.Where(j => i < myIntCollection.Count - 1).Select(
                j => myIntCollection[i] + myIntCollection[i++ + 1]));

A: You can use the Enumerable.Range method to create a collection on the fly, and get the sum of two items for each index:
List<int> generatedCollection =
  Enumerable.Range(0, myIntCollection.Length - 1)
  .Select(i => myIntCollection[i] + myIntCollection[i + 1])
  .ToList();


text:
Q: PUT Ajax request returning 404 not found asp.net MVC I am new to asp.net MVC, I am making one project just like stack overflow. In this, I just want to use the ajax system to upvote or down-vote the answer. So, I can show the counter increase and decrease without refreshing the page.
I have default scaffolding one controller of Question in the controller and in which I have QuitionDetails method which is responsible for the QuitionDetailsView and in this view I am making ajax request to my API controller VotesController when the user clicks on the up-vote or down-vote.
But I am getting this error
jquery-3.3.1.js:9600 PUT https://localhost:44389/Question/QuestionDetails/api/votes/3 404 not found
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
(anonymous) @ 2:230
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991

here is my first default scaffolding controller Question
public ActionResult QuestionDetails(int Id)
        {
            QuestionDetailViewModel questionDetailViewModel = new QuestionDetailViewModel
            {
                Question = QBL.GetQuestions(Id),
                UserId = User.Identity.GetUserId(),
                QuestionId = Id,
            };
            return View(questionDetailViewModel);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult QuestionDetails(QuestionDetailViewModel questionDetailViewModel)
        {
            QBL.CreateAnswer(questionDetailViewModel);
            return RedirectToAction("QuestionDetails", new { Id = questionDetailViewModel.QuestionId });
        }

View Code is  as Below
@model AskMe.Models.ViewModel.QuestionDetailViewModel

@{
    ViewBag.Title = "QuestionDetails";
}

Question Details:

@Model.Question.Post.Title

@Html.Raw(Model.Question.Post.Content)

Answers:

@foreach (var answer in Model.Question.Answers)
{

Answered by: @answer.Post.CreatedBy.UserName

            @Html.Raw(answer.Post.Content)

                <button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-up" href=""></button>

                <button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-down" href=""></button>

}
@using (Html.BeginForm())
{

    @Html.AntiForgeryToken()

Contribute your answer:

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(m => m.AnswerContent, new { @class = "col-md-2 control-label" })

                @Html.TextAreaFor(m => m.AnswerContent, new { @class = "form-control" })

                @Html.HiddenFor(m => m.UserId)
                @Html.HiddenFor(m => m.QuestionId)
                <input type="submit" value="Contribute now" class="btn btn-outline-primary" />

}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval");

}

And here is my votes API controller code
using AskMe.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AskMe.API
{
    public class VotesController : ApiController
    {
        ApplicationDbContext _context = new ApplicationDbContext();

        [HttpPut]
        public IHttpActionResult UpVote(int postId)
        {
            var userId = User.Identity.GetUserId();
            var user = _context.Users.Find(userId);
            var post = _context.Posts.Find(postId);
            var votes = post.Votes.ToList();
            if (votes.FindAll(u => u.UserId == userId).Count == 0)
            {
                Votes vote = new Votes
                {
                    VotedDateTime = DateTime.Now,
                    UserId = userId,
                    User = user,
                    Post = post,
                    PostId = postId,
                };
                post.Votes.Add(vote);
                _context.SaveChanges();
                return Ok();
            }
            return BadRequest();
        }
    }
}

I am not sure my api link should be like this https://localhost:44389/Question/QuestionDetails/api/votes/3
or
https://localhost:44389/api/votes/3
and my route config is routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );

A: If you haven't changed the standard routing, you need to include the action/method name in your ajax call.
Try:
url: "api/vote/upvote/" + $(this).attr("data-vote-id")
Your route configuration should look like this:
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

If you are using MVC5 with WebApi, which is my guess, you have to be careful. See this post for further information on how to do it.

A: Actually your error telling everything. When you requesting for 'UpVote' action it's looking into "basepath(localhost)/controller/action/Api/etc." and it does not exits. You must create request for https://localhost:44389/API/Votes/UpVote/3


text:
Q: Increase a variable number by 1 I have code in which I have a large number of characters all declared as being 1 higher than the other.
e.g. m1, m2, m3...
is there any way to increase the number I'm searching for by 1 in a for loop?
I have a long string of letters that I need to check to see if any of them match to the individual, but I cannot use strings due to situational limitations.
a1 is the particular character I'm looking for, m1 is the first in a long string of characters I am having to store as individuals
My attempt that wouldn't run:
for (a1 != m["%d"], &check, check++)

Unfortunately due to the limits of my application I can only use stdio.h and stdlib.h in my solution. Any help would be greatly appreciated

A: Variable names are used by the compiler, but are not part of the generated executable and therefore not accessible at runtime. You can simulate something like that by an array initialized with the addresses of the respective variables:
#include <stdio.h>
int main() {
    int a0=0,a1=10,a2=15;
    int *a[3] = { &a0, &a1, &a2 };
    for (int i=0; i<3; i++) {
      int val = *(a[i]);
      printf("a%d:%d\n",i,val);
    }
}

Output:
a0:0
a1:10
a2:15


text:
Q: TSQL: Subconsulta para calcular un % Me encuentro con dos problemas.
En primer lugar, la subconsulta ya me genera un error que no soy capaz de solucionar.
En segundo lugar, una vez solucionado el primer punto, tampoco tengo muy claro cómo calcular el porcentaje.
Tabla [InParts].[Web].[Request]
Id  RequestDate
1   2022-08-02 07:36:20.000
2   2022-08-02 07:36:21.000
3   2022-08-02 07:44:05.000
4   2022-08-02 08:07:21.000
5   2022-08-02 08:07:22.000

Tabla [InParts].[Web].[RequestArticle]
Id  RequestId   ManufacturerCode    ManufacturerName
1   1           340                 PRASCO
2   1           340                 PRASCO
3   1           4965                JUMASA
4   1           4965                JUMASA
5   2           340                 PRASCO

Tabla [InParts].[Web].[ResponseArticle]
Id  RequestId   ManufacturerCode    ManufacturerName    Status
1   1           340                 PRASCO              Available
2   1           340                 PRASCO              Available
3   1           4965                JUMASA              Unavailable
4   1           4965                JUMASA              Available
5   2           340                 PRASCO              Unavailable

Estas son las dos consultas por separado que tengo y que devuelven resultados correctos
-- CANTIDAD DE PIEZAS NO ENCONTRADAS AGRUPADAS POR FABRICANTE
select resp.[ManufacturerName], COUNT(resp.[ManufacturerName]) as 'TotalPiezasPorFabricante'
from [InParts].[Web].[ResponseArticle] as resp
JOIN [InParts].[Web].[Request] as req on req.[Id] = resp.[RequestId]
where   resp.[Status] <> 'Available' and
        req.[RequestDate] between '2022-08-01' and '2022-08-30'

group by resp.[ManufacturerName]

order by TotalPiezasPorFabricante desc

Resultado:

--PIEZAS AGRUPADAS POR FABRICANTE
select ra.[ManufacturerCode], ra.[ManufacturerName], COUNT(ra.Id) as "total"
from [InParts].[Web].[RequestArticle] as ra
join [InParts].[Web].[Request] as req
  on req.Id = ra.RequestId
where req.RequestDate between '2022-08-01' and '2022-08-30'
group by ra.[ManufacturerCode], ra.[ManufacturerName]
order by total desc

Resultado:

Lo que se busca es que la segunda consulta sea subconsulta de la primera para poder añadir una columna indicando el % de piezas no encontradas sobre el total de piezas solicitadas.

A: Me parece que usando CTE ya podrías resolverlo:
with query1 as (
            select ra.[ManufacturerCode],
                   ra.[ManufacturerName],
                   COUNT(ra.Id) as "total"
            from [InParts].[Web].[RequestArticle] as ra
                 join [InParts].[Web].[Request] as req on req.Id = ra.RequestId
            where req.RequestDate between '2022-08-01' and '2022-09-01'
            group by ra.[ManufacturerCode], ra.[ManufacturerName]
),

query2 as (
            select resp.[ManufacturerName],
                   COUNT(resp.[ManufacturerName]) as "Solicitudes sin respuesta"
            from [InParts].[Web].[ResponseArticle] as resp
                 JOIN [InParts].[Web].[Request] as req on req.[Id] = resp.[RequestId]
            where resp.[Status] <> 'Available'
                  and req.[RequestDate] between '2022-08-01' and '2022-09-01'
            group by resp.[ManufacturerName]
)

SELECT query2.ManufacturerName as "Fabricante",
       query2."Solicitudes sin respuesta",
       query1.total as "Total peticiones",
       ((query2."Solicitudes sin respuesta"*100)/query1.total) as "% sin respuesta"
FROM query1
     JOIN query2 ON query1.ManufacturerName = query2.ManufacturerName

     order by "% sin respuesta" desc, "Solicitudes sin respuesta" desc;


text:
Q: Best practice for deleting many-to-many relationships with SQL Server and ASP.NET MVC I'm working on a project in ASP.NET MVC using Entity Framework linked to a SQL Server database, to which I use SQL Server Management Studio to manage.
I have some many-to-many relationships that I handle with an intermediate table that links the two other tables. Let's say I have table A, table B and table A_B that links the A and B in a many to many relationship.
If I want to delete a row in table A, I must delete all rows in table B that links with it, therefore deleting the rows in A_B.
My question is:
What's the best practice in this case? Should I handle those deletes in the controller in MVC ASP.NET or must I handle this with a SQL Server trigger?
To me it would look cleaner to just use a trigger and abstracting all this logic from the controller itself, so I would only need to delete the row in table A and the lower lever (SQL Server) would take care of the rest.
But, I've heard people saying that we should avoid triggers in SQL Server, so in a commercial project, which approach would you recommend as being the best practice?
Thanks.
EDIT:
[TABLE A [id]] -> [ TABLE A_B [id_A, id_B, position] ] <- [TABLE B [id]]
That's the situation I have (I can't post images yet). I've tried to put Cascade on Delete on every relationship, but when I delete a row in A, the corresponding row in A_B get's deleted but not the corresponding table in B. Is there a way to do this? Or in this case I have to use triggers?

A: If you really want to force SQL Server to delete references you should use CASCADE DELETE not triggers, just because it's more obvious way to do it. You should switch on it on FOREIGN KEY creation.
If you already created the FOREIGN KEY then drop it first.
ALTER TABLE dbo.B
ADD CONSTRAINT FK_A_B_Cascade
FOREIGN KEY (AId) REFERENCES dbo.A(Id) ON DELETE CASCADE

But it's much better set your deletion logic in code. Because not in all cases you want to delete references. Sometimes it's better just set some flag like IsDeleted to true.
Moreover it's better not doing this in Controller, but create separate DAL (Data Access Layer) project and place it there. And can be that you want to use one of ORM like Entity Framework to access your DB.


text:
Q: fwrite writes NUL I'm trying to write to a file with PHP and this is the code I'm using (taken from this answer to my previous question):
$fp = fopen("counter.txt", "r+");

while(!flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    // waiting to lock the file
}

$counter = intval(fread($fp, filesize("counter.txt")));
$counter++;

ftruncate($fp, 0);      // truncate file
fwrite($fp, $counter);  // set your data
fflush($fp);            // flush output before releasing the lock
flock($fp, LOCK_UN);    // release the lock

fclose($fp);

The read part works fine, if the file gets read, it's content is read well, i.e. if the file contains 2289, then 2289 is read.
The problem is that when it increments and rewrites the value to that file, [NUL][NUL][NUL][NUL][NUL][NUL][NUL][NUL]1 gets written.
What am I missing? Why do null characters get written?

A: The thing you are missing is rewind(). Without it, after you truncate to 0 bytes, the pointer is still not at the beginning (reference). So when you write your new value, it pads it with NULL in your file.
This script will read a file (or create if it doesn't exist) for a current count, increments, and writes it back to the same file every time the page loads.
$filename = date('Y-m-d').".txt";

$fp = fopen($filename, "c+");
if (flock($fp, LOCK_EX)) {
    $number = intval(fread($fp, filesize($filename)));
    $number++;

    ftruncate($fp, 0);    // Clear the file
    rewind($fp);          // Move pointer to the beginning
    fwrite($fp, $number); // Write incremented number
    fflush($fp);          // Write any buffered output
    flock($fp, LOCK_UN);  // Unlock the file
}
fclose($fp);

A: EDIT #2:
Try this with flock (tested)
If file is not locked, it will throw an Exception (see added line) if(...
I borrowed the Exception snippet from this accepted answer.
<?php

$filename = "numbers.txt";
$filename = fopen($filename, 'a') or die("can't open file");

if (!flock($filename, LOCK_EX)) {
    throw new Exception(sprintf('Unable to obtain lock on file: %s', $filename));
}

file_put_contents('numbers.txt', ((int)file_get_contents('numbers.txt'))+1);

// To show the contents of the file, you
// include("numbers.txt");

    fflush($filename);            // flush output before releasing the lock
    flock($filename, LOCK_UN);    // release the lock

fclose($filename);
echo file_get_contents('numbers.txt');

?>

A: You can use this code, a simplified version, but am not sure if it's the best:
<?php
$fr = fopen("count.txt", "r");
$text = fread($fr, filesize("count.txt"));
$fw = fopen("count.txt", "w");
$text++;
fwrite($fw, $text);
?>


text:
Q: Magento 2 override css of specific tag I want to override the css for  tag globally, it is not enclosed so I want to apply word-wrap property on it. Any help?

A: I'm going to presume you're using the default workflow and using blank as a parent.

*

*Overwrite vendor/magento/theme-frontend-blank/Magento_Theme/web/css/source/_module.less in to your theme.

*Add your changes

*Compile how you normally would, if you aren't sure how then run php bin/magento setup:static-content:deploy from the root of your Magento installation.


text:
Q: internet explorer wont read object attributes The commented out section does not work in IE, But does work in the other browsers.
IE errors on [query.outFields[1]] claiming it needs a string or a number.
Any ideas why? Any ideas to how get IE to work with those commented lines?
                             var attS =
                            {
                                //[query.outFields[1]]: pin,
                                //[query.outFields[0]]: vars[0],
                                //[query.outFields[2]]: vars[5],
                                //[query.outFields[3]]: vars[6],
                                PIN: pin,
                                APN: vars[0],
                                PARCELAREA: vars[5],
                                AREATYPE: vars[6],
                                PARCELVER:working[0],
                                PERMITNUM:working[1],
                                ADDRESSID:working[2]
                            }

Here is the whole code block if you think it'll help..
                for(j =0;j<multiPermit.length;j++)
                {
                    var vars = multiPermit[j];
                    console.log(vars);
                    //center X
                    var x = vars[2];
                    //center Y
                    var y = vars[3];
                    var pin = vars[4];
                    //console.log(pin);

                    //Delete source geometry for multi point from final data to ensure it's not represented twice.
                    for(l=0;l<inputInfo.data.length;l++)
                    {
                        temp = inputInfo.data[l];
                        if(temp.attributes[query.outFields[0]]==vars[0] && temp.x == x && temp.y==y)
                        {
                            inputInfo.data.splice(l,1);
                        }
                    }

                    //var Test=query.outFields[1];
                    //console.log(Test);
                    for(var i=0; i<zipArray.length;i++)
                    {
                        var working = zipArray[i];
                        if(working[0]==vars[0])
                        {
                            var quickPush=inputInfo.data

                            var newX = x;
                            var newY = y;

                             var attS =
                            {
                                //[query.outFields[1]]: pin,
                                //[query.outFields[0]]: vars[0],
                                //[query.outFields[2]]: vars[5],
                                //[query.outFields[3]]: vars[6],
                                PIN: pin,
                                APN: vars[0],
                                PARCELAREA: vars[5],
                                AREATYPE: vars[6],
                                PARCELVER:working[0],
                                PERMITNUM:working[1],
                                ADDRESSID:working[2]
                            }

                            //console.log(attS);
                            quickPush.push({"x": newX,"y": newY,"attributes": attS})
                        }
                    }
                }

A: Computed property names ({ [likeThis]: "here" }) are a new feature in EcmaScript 6 and are not supported by Internet Explorer yet.
You'll need to create your object and then add your variable fields afterwards.
 var attS = {
   PIN: pin,
   APN: vars[0],
   PARCELAREA: vars[5],
   AREATYPE: vars[6],
   PARCELVER: working[0],
   PERMITNUM: working[1],
   ADDRESSID: working[2]
 };
 attS[query.outFields[1]] = pin;
 // etc

A: I'm not 100% if I get your problem, but I think you're mixing 2 ways of defining properties of an object in javascript.
You are trying
var myObject = {
   prop1 : value,
   prop2 : value,
   [prop3nameWhichIsPartOfOtherVar]: value
}

This is not possible (yet) on Internet explorer. A way to go around this is simply adding:
myObject[prop3nameWhichIsPartOfOtherVar] = value;

After your definition.
More information about what works or doesn't work (and the browser compatibilities): here


text:
Q: using trim in jquery instead of using trim all the time i want use once as common for the below code... pls help me
if ("Company Profile" == $.trim(selectedValue)) {
    actionClass = "locationImportCompany.do?";
} else if ("Oppty Locations" == $.trim(selectedValue)) {
    actionClass = "locationImport.do?";
} else if ("Different Oppty" == $.trim(selectedValue)) {
    actionClass = "locationImportDiffOppty.do?";
} else if ("Loop TrackId Profile" == $.trim(selectedValue)) {
    actionClass = "locationImportLoopTrkId.do?";
} else if ("Inventory" == $.trim(selectedValue)) {
    isOrdering = "Y";
    actionClass = "inventoryLaunch.do?";
} else if ("Data Center List" == $.trim(selectedValue)) {
    actionClass = "locationImportDataCenter.do?";
} else if ("Customer AccountId" == $.trim(selectedValue)) {
    actionClass = "inventoryLaunch.do?";
} else if ("Customer Name" == $.trim(selectedValue)) {
    actionClass = "locationImportDataCenter.do?";
}

A: Store it in a variable:
 var selectedValue = $.trim(selectedValue);

Then do:
if (selectedValue == "Oppty Locations") {

}

etc...

A: var selectedValue = $.trim(selectedValue);
if ("Company Profile" == selectedValue) {
    actionClass = "locationImportCompany.do?";
} else if ("Oppty Locations" == selectedValue) {
    actionClass = "locationImport.do?";
} else if ("Different Oppty" == selectedValue) {
    actionClass = "locationImportDiffOppty.do?";
} else if ("Loop TrackId Profile" == selectedValue) {
    actionClass = "locationImportLoopTrkId.do?";
} else if ("Inventory" == selectedValue) {
    isOrdering = "Y";
    actionClass = "inventoryLaunch.do?";
} else if ("Data Center List" == selectedValue) {
    actionClass = "locationImportDataCenter.do?";
} else if ("Customer AccountId" == selectedValue) {
    actionClass = "inventoryLaunch.do?";
} else if ("Customer Name" == selectedValue) {
    actionClass = "locationImportDataCenter.do?";
}

A: Over write selectedValue with trimmed value and use afterwards, or assign it to some variable and use that.
selectedValueTrimmed = $.trim(selectedValue)
if("Company Profile"==selectedValueTrimmed ){

A: Make it to Switch Statement instead of Else If Statement.
switch ($.trim(selectedValue)) {
    case: "Company Profile"
        actionClass = "locationImportCompany.do?";
        break;
    case: "Oppty Locations"
        actionClass = "locationImport.do?";
        break;
   // So on ...
}


text:
Q: Can I prevent get_the_post_thumbnail from falling back to the global post ID? I have a post type that contains meta boxes. These metaboxes allow a user to select an item from a dropdown menu. All these items are IDs for other posts.
So in the theme, I am using get_the_post_thumbnail to retrieve the featured image from the post ID retrieved from these metaboxes. It works.
What doesn't work is that if a metabox is empty, get_the_post_thumbnail will automatically retrieve the thumbnail for the global post ID.
This is from the codex for its first parameter:

Post ID or WP_Post object. Default is global $post. Default value:
  null

How do I prevent this OR what is another way to solve this? I don't want to load the image from the default post. I want it to be empty if nothing specific is selected.

A: As you are storing posts IDs in meta fields of another post (let's call this post "the main post"), you can get that meta field and if it is empty, just avoid the use of get_the_post_thumbnail().
(For the next examples, I suppose that you are stroing one post ID in one meta field of the main post; if this is not the case, just say it and explain what data format you are using).
For example, if you are in the Loop of the main post:
while( have_posts() ) {
    the_post();

    // used inside the loop, get_the_ID() returns current post ID in the loop
    // replace meta_field_that_stores_post_ID with the key of your meta field
    // last param is set to true, so get_post_meta() retuns empty string if the meta field doesn't exists
    $thumb_post_ID = get_post_meta( get_the_ID(), 'meta_field_that_stores_post_ID', true );
    if( ! empty( $thumb_post_ID ) ) {
        echo get_the_post_thumbnail( $thumb_post_ID );
    }

}

You could separated that logic from the template, for example using a template tag:
function cyb_get_the_post_thumbnail() {

    $thumb_post_ID = get_post_meta( get_the_ID(), 'meta_field_that_stores_post_ID', true );

    if( ! empty( $thumb_post_ID ) {
        echo get_the_post_thumbnail( $thumb_post_ID );
    }
}

And then use cyb_get_the_post_thumbnail() wherever you need it within the loop of the main post.
If you are not within the loop of the main post, you need to know, at least, the ID of the main post and do something like this:
$thumb_post_ID = get_post_meta( 254, 'meta_field_that_stores_post_ID', true );
if( ! empty( $thumb_post_ID ) {
    echo get_the_post_thumbnail( $thumb_post_ID );
}


text:
Q: How to sort terms with diacritical signs? I have list of terms which happens to be the Polish Alphabet.
Here's how I list these terms:

<?php
   $terms = get_terms("taxonomy", array('orderby' => 'title', 'hide_empty' => 0));
   foreach ( $terms as $term ) {
      echo "
slug, $term->taxonomy ) ."'>" . $term->name . "
";
   } ?>

Everything works like a charm excepting one thing - the letter that is supposed to be after "L" ("Ł") is always the last element o that list (so it's after "Ż", not "L"). Is there any way to fix it? I've been trying multiple WP versions including Polish builds.
Any ideas? I can always do two foreach loops for A-L and M-Ż and add that one between them, but would love to do that with more class.

A: You need to set the database collation to utf8_polish_ci in your wp-config.php to get correct sorting.


text:
Q: Why is this JS code working most places but not on my machine? I wrote some code which works fine in the Node env provided by repl.it (https://repl.it/repls/LimpingCharmingGravity), in the code snippet here (see below), and on codepen.io (https://codepen.io/tjfwalker/pen/OERXry?editors=0012#0). It's not working, however, with Node on my machine. Trying to run in produces the following error message:
ReferenceError: Entity is not defined
    at Entity.eval [as addSub] (eval at <anonymous> (/Users/…pathtofile…/app.js:18:69), <anonymous>:3:11)
    at Object.<anonymous> (/Users/…pathtofile…/app.js:60:20)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

My local node is 10.4.0 via nvm on macOS... though, I imagine it's not about that.
What gives?

let activeUserMock = 'someUserName'

const Entity = (function() {
    let lastID     = 0
      , entityList = []

    function Entity(userFields, userMethods) {
        this.meta = {id: ++lastID, dob: new Date, creator: activeUserMock}

        userFields.forEach(
            function(field) {
                this[field.key] = field.value
            }
        ,this)

        userMethods.forEach(
            function(method) {
                this[method.name] = Function(...method.args, method.body)
            }
        ,this)

        entityList.push(this)
    }

    Entity.findByID = function(id) {
        return entityList.find(function(entity) {
            return entity.meta.id === id
        })
    }

    return Entity
})();

// ======= SIMULATE AN END USER —FROM SOME CLIENT UI— MODELING THEIR OWN DOMAIN ==========

new Entity([ //stuff from the user ↴
    {key: 'type', value: 'feature'}
   ,{key: 'name', value: 'LMS'}
   ,{key: 'subs', value: []}
   ,{key: 'sups', value: []}
   ,{key: 'desc', value: 'a module to facilitate learning.'}
],[
    {name: 'addSub', args: ['subID'], body: 'let sub = Entity.findByID(subID); this.subs.push(sub); sub.sups.push(this); return this'}
   ,{name: 'addSup', args: ['supID'], body: 'let sup = Entity.findByID(supID); this.sups.push(sup); sup.subs.push(this); return this'}
])

new Entity([ //stuff from the user ↴
    {key: 'type', value: 'feature'}
   ,{key: 'name', value: 'SRS'}
   ,{key: 'subs', value: []}
   ,{key: 'sups', value: []}
   ,{key: 'desc', value: 'a module that implements the spaced repetition learning technique.'}
],[
    {name: 'addSub', args: ['subID'], body: 'let sub = Entity.findByID(subID); this.subs.push(sub); sub.sups.push(this); return this'}
   ,{name: 'addSup', args: ['supID'], body: 'let sup = Entity.findByID(supID); this.sups.push(sup); sup.subs.push(this); return this'}
])

Entity.findByID(1).addSub(2)

// ==========================================================

console.log(Entity.findByID(1))

A: Unlike eval(), Function() constructor does not have access to the calling scope, it only have access to the global scope.
That script will fail in node, because every module has it's own scope, and Entity is not on the global namespace.
To check this, just wrap your code inside an IIFEE, and you will see that it will fail on the browser too. (See snippet below)
To "fix" your code in node, you will need to do:
global.Entity = (function() {
 /* ... */
})():

But you should probably rethink your approach, and use bind instead, and access Entity using this.
The following will fail in the browser too:

(function() {
  let activeUserMock = 'someUserName'

  const Entity = (function() {
      let lastID     = 0
        , entityList = []

      function Entity(userFields, userMethods) {
          this.meta = {id: ++lastID, dob: new Date, creator: activeUserMock}

          userFields.forEach(
              function(field) {
                  this[field.key] = field.value
              }
          ,this)

          userMethods.forEach(
              function(method) {
                  this[method.name] = Function(...method.args, method.body)
              }
          ,this)

          entityList.push(this)
      }

      Entity.findByID = function(id) {
          return entityList.find(function(entity) {
              return entity.meta.id === id
          })
      }

      return Entity
  })();

  // ======= SIMULATE AN END USER —FROM SOME CLIENT UI— MODELING THEIR OWN DOMAIN ==========

  new Entity([ //stuff from the user ↴
      {key: 'type', value: 'feature'}
     ,{key: 'name', value: 'LMS'}
     ,{key: 'subs', value: []}
     ,{key: 'sups', value: []}
     ,{key: 'desc', value: 'a module to facilitate learning.'}
  ],[
      {name: 'addSub', args: ['subID'], body: 'let sub = Entity.findByID(subID); this.subs.push(sub); sub.sups.push(this); return this'}
     ,{name: 'addSup', args: ['supID'], body: 'let sup = Entity.findByID(supID); this.sups.push(sup); sup.subs.push(this); return this'}
  ])

  new Entity([ //stuff from the user ↴
      {key: 'type', value: 'feature'}
     ,{key: 'name', value: 'SRS'}
     ,{key: 'subs', value: []}
     ,{key: 'sups', value: []}
     ,{key: 'desc', value: 'a module that implements the spaced repetition learning technique.'}
  ],[
      {name: 'addSub', args: ['subID'], body: 'let sub = Entity.findByID(subID); this.subs.push(sub); sub.sups.push(this); return this'}
     ,{name: 'addSup', args: ['supID'], body: 'let sup = Entity.findByID(supID); this.sups.push(sup); sup.subs.push(this); return this'}
  ])

  Entity.findByID(1).addSub(2)

  // ==========================================================

  console.log(Entity.findByID(1))
})();

UPDATE

what concretely does code look like that follows your recommendation
  to "use bind instead, and access Entity using this

this[method.name] = Function(...method.args, method.body).bind(this)

And then use:
body: 'let sub = this.constructor.findByID(subID) ...'

Instead of:
body: 'let sub = Entity.findByID(subID) ...'


text:
Q: How to count the number of review comments from a specific author in Word? I have a large MS Word document with a high number of review comments (track changes feature). I'd now like to get a list of authors and the number of review comments. The number of authors is not too long, so if I can get the information for one author at a time, that's fine.
I'm using Word 2013. If it's possible to find out in OpenOffice / LibreOffice or any other tool, that's also fine.

A: I think I managed to get accurate results like this:

*

*Go to the Review ribbon

*In the Tracking section, open the dropdown Show markup

*Deselect everything except comments

*Open dropdown Show markup again

*Under Specific people, mark only one person

*Click on Reviewing Pane
In the reviewing pane, it now shows xx Revisions. As far as I could see, these are all comments now, so we have the number of comments for one author.
From now on it is much easier to do the same for other authors, because you just need to change the person under Specific people.

A: This method may look cumbersome but it can be useful in certain situations:
If you save the document as .txt it will contain the main text of the document at first, and the comment list at the end, in this format:
[MG1]The whole table needs to be reviewed and updated.
[MG2]Remove section 2.2.4
[MG3]Insert correct reference.
...

You can then filter by the commenter's initials i.e. [MG and count the rows.

A: Put document to :
Print preview
in Settings select print markup
scroll to bottom and you will see initials with #'s


text:
Q: Why code is not printing anything as output? After pressing Ctrl+D, i am expecting this code to print array, but its doing nothing.
#include<stdio.h>

int main(){
    int k,i=0,a;
    int b[10];
    while(scanf("%d",&a)!=EOF){
        if(a>(a/4+a/3+a/2))
        b[i]=a;
        else
        b[i]=(a/4+a/3+a/2);
        i++;
    }
    for(k=0;k<=i;k++){
        printf("%d\n",b[k]);
    }
    return 0;
}

A: You're using the wrong key combination to generate an EOF on your operating system (Windows 8). Ctrl+D is common on unix-like systems, but Windows systems generally use Ctrl+Z.
Note that you might have to use Ctrl+Z twice if you're not on an empty line (once to flush the current line of input, and once to generate the EOF).

A: Best guess -- you're entering something that is not a number, so scanf returns 0 and your program enters an infinite loop.  As you don't show your input, it's impossible to tell.
If you want it to stop on a non-number input, change the loop to while(scanf("%d",&a) > 0)

A: you should check the documentation for scanf's return value... it returns the number of items scanned, 0, 1, 2, etc... not EOF


text:
Q: How can I convert many XLSX files into many CSV files using NESTED FOR LOOPS in R? I've been trying to convert many .xlsx into many .csv
First, I made a list with all .xlsx that I want to be converted.
> especies
 [1] "Aburria jacutinga.xlsx"       "Acrobatornis fonsecai.xlsx"   "Alectrurus tricolor.xlsx"
 [4] "Amadonatur lacernulatus.xlsx" "Amazona pretrei.xlsx"         "Amazona rhodocorytha.xlsx"
 [7] "Amazona vinacea.xlsx"         "Anodorhynchus leari.xlsx"     "Anthus nattereri.xlsx"
[10] "Antilophia bokermanni.xlsx"

Then, I edit the elemmnts in order not to have any space in the name and create another vector. It ended like this:
> nomes_
 [1] "Aburria_jacutinga"       "Acrobatornis_fonsecai"   "Alectrurus_tricolor"     "Amadonatur_lacernulatus"
 [5] "Amazona_pretrei"         "Amazona_rhodocorytha"    "Amazona_vinacea"         "Anodorhynchus_leari"
 [9] "Anthus_nattereri"        "Antilophia_bokermanni"

Then I tried the following nested for loops to convert each .xlsx file into .csv files:
for (file in especies){
  xlsx_objeto<- readWorksheetFromFile(file=file, sheet=1, keep=c(2,3,4,6,7,8,9,10,13,18))
  for( j in nomes_){
    write.csv(xlsx_objeto,file=paste0("./csv/",j,".csv"))
  }
}

What I've got is one .csv file for each element in nomes_. That's ok.
But inside these .csv file are exactly the same. They all have the data from the last .xlsx file in the especies list.

A: Finally, I could manage that. Here it goes the code. Sorry the comments are in portuguese.
library('XLConnect')
library('foreach')
# Cria uma lista com todos os arquivos em xlsx
especies<-list.files(pattern = "\\.xlsx$")
# Eliminar algum arquivo indesajado que esteja na pasta
especies<-especies[-c(1:41)]
## Cria um vetor que contenha os nomes desejados para serem os nomes dos arquivos finais.
# Retira a extensão ".xlsx"
nomes<-gsub(pattern=".xlsx",replacement="",especies)
# Substitui todo espaço por "_"
nomes_<-gsub(pattern=" ",replacement="_",nomes)
# Retira todo "." Atenção se quiser substituir pontos ".", estes devem estar entre colchetes assim: "[.]"
nomes_<-gsub(pattern="[.]",replacement="",nomes_)
# Cria um csv com a lista dos nomes dos arquivos.(Opcional)
write.csv(nomes_,file="./csv/_lista_especies.csv", quote=FALSE)
## Usando FOREACH LOOP para converter cada arquivo xlsx em um csv que terão como nome o elementos da lista criada acima.
# Detalhes do uso do foreach em http://cran.r-project.org/web/packages/foreach/vignettes/foreach.pdf
foreach(file = especies, j = nomes_) %do% {
  xlsx_objeto<- readWorksheetFromFile(file=file, sheet=1, keep=c(2,3,4,6,7,8,9,10,13,18))
  write.csv(xlsx_objeto,file=paste0("./csv/",j,".csv"))
}


text:
Q: USB is shocking me for no reason Yesterday, I plugged a metal USB into the computer case. When I tried to unplug the USB when the computer is powered on, it shocked me. I thought it's electricity from a malfunctioning part, so I tried to check on the computer. Device Manager said 'The device is working properly.', I can also find the USB on Explorer and can use it, create folders, save files, use it normally. That case is made of plastic, and I realized that when I tried to insert a plastic memory card it didn't shock me at all. I plugged that USB into a different computer and it didn't shock me at all. What is the cause of this? Now I'm scared of metal USB!

A: One key piece of information you've left out is whether the shock will happen repeatably (i.e: touch twice within a few seconds).
One Time Shocks
If the shock happens once, but then not when touching again within a few seconds, then it is likely down to static electricity that has built up on you, discharging via the computer's low impedance path to ground.
This is a common issue when wearing synthetic clothing (e.g: tracksuit, socks on carpet, etc...) and touching anything that is properly grounded (e.g: pipework, cars, desktop PC, etc...).
You might hear a snap, and may even see a spark. It's a sharp pain that dissipates quickly.
Repeatable Shocks - due to Class-Y Capacitors
This can be caused by the power supply's Class-Y capacitors - you may effectively have a "floating ground" within the system. This "ground" can actually have a significant potential compared to the local mains ground (I've seen ~50% of mains, or ~110v AC in the UK), and in many cases it's possible to sink / source a few tens of milliamps between the device "ground" and the local mains ground.
You may experience this when connecting a computer to a monitor, between the computer's chassis and the cable's shielding, and can also be the cause of ground loops and other interference.
This doesn't feel nice at all, but isn't usually too concerning when it comes to your personal health - pacemakers and other medical electronics make this situation more concerning of course.
You won't likely see or hear anything, and the sensation will persist while you are touching the two items.
Repeatable Shocks - due to No Earth (!)
A repeatable shock can also be caused due to a device being improperly earthed.
In this situation, you will typically need another fault to present concurrently (i.e: a live wire touching the chassis) for any significant shock to appear.
You will certainly know about it if you've experienced it - I suspect you haven't.
NOTE: This is a scary scenario and can lead to death.
Double insulated devices (e.g: laptops, monitors, etc...) should never present this issue. Look for the box-in-a-box icon on the adapter:

Avoid "testing" the hypothesis by using your left and right hands, as this will pass the current directly up one arm, across your heart, and down your other arm.
If you must, then using two fingers of the same hand is a safer option - though it may sting more :-)

If you're in any doubt or would like to be sure, then I suggest getting a "Socket Tester" that will indicate whether the wall outlet is correctly wired and safe to use - there are far too many places that have poor wiring, and I really consider these to be an important household toolbox item.

As a side note, Device Manager is not a reliable source of whether "The device is working properly", especially when it comes to this sort of issue.

A: This is called electrostatic discharge (ESD) and we all know that very well from school. I don't believe your computer doesn't have grounding. Instead you should thinking about other slippers maybe :)


text:
Q: Массив в масиве Что неправильно в такой конструкции?
$ter = array('test-3', 'test-4');

$taxquery = array(
    'post_type' => 'wpsc-product',
    'tax_query' => array(
        'taxonomy' => 'xtag',
        'field' => 'slug',
        'terms' => $ter
    )
);

A: Все правильно. Можете отступы для красоты расставить :)
$ter = array('test-3', 'test-4');
$taxquery = array(
  'post_type' => 'wpsc-product',
  'tax_query' => array(
    'taxonomy' => 'xtag',
    'field' => 'slug',
    'terms' => $ter
  )
);

A: А почему вы решили, что конструкция не работает? Все работает! Скажите, какую операцию у вас не получается сделать.
Код:
$ter = array('test-3', 'test-4');
$taxquery = array(
    'post_type' => 'wpsc-product',
    'tax_query' => array(
      'taxonomy' => 'xtag',
      'field' => 'slug',
      'terms' => $ter
    )
);

print_r($taxquery["tax_query"]["terms"]);
// выводит "Array ( [0] => test-3 [1] => test-4 )".

Все верно =)


text:
Q: Place  tag on a banner over 4 images to connect to 4 different urls I am trying to place  tags around certain area's on a banner I have.  This banner has 4 different logos where I need a link for each one.
Banner --->>>>
ImageOne                  ImageTwo            ImageThree            ImageFour
Banner --->>>>
ImageOne Url = www.cnnsi.com
ImageTwo Url = www.cnn.com etc etc
How can I do this to where I place them in a horizontal direction?
I can do the first one without any issues, but do I need to use absolute value for the position for the remaining 3?
Here is some Css below:  if I keep the position set to: relative on #imageTwo - then it will be below the header banner which is width 999 by height 151 at the top of the page. It will place it outside of the header kinda below the #imageOne.  Any help would be appreciated!
<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" type="text/css" href="../Content/Site.css"/>

#imageOne {
   display: block;
   position: relative;
   top: 24px;
   left: 16px;
   height: 95px;
   width: 162px;
}

#imageTwo {
  display: block;
  position: relative;
  top: 24px;
  left: 175px;
  height: 95px;
  width: 162px;
}

A: Either use
float:left;
width:25%;

for all images,
or you can set them with
display:inline;

it will be easier if you assign one class to all images. Also, if you just remove the display:block you should be fine.
Generally you want to avoid using position:aboslute in this case.


text:
Q: Find an element by its class attribute in DOM with raw javascript without using ids Ok. Suddenly I have this query in my mind.
Libraries like jQuery makes it real easy to look for an element having some class. It does not force us to apply an id on the element to be found. In Vanilla js we have the option to find out an element using the method getElementById() which forces me to apply IDs to a large extent.
I looked at this solution to find an element using an attribute which in this case is going to be class. After going through the solutions I find it very heavy on the browser. If I have a complex DOM structure, it will cost performance. And my question remains the same.
How do I find an element using class name and without using id in Vanilla Javascript?

A: How about
var elems = document.getElementsByClassName('someclass');

That will return a set of elements which have the given class. You could then access them using elems[0] , elems[1] and so on..
Remember that jQuery is ultimately based on JavaScript, so it can't be faster from an execution point of view.
You might find some interesting jQuery to JavaScript translations here
http://vanilla-js.com/
For older versions of IE you need to use getElementsByTagName and loop over the returned elements. This utility function should be compatible from IE6 onwards (probably similar to the solution you linked to)
function getElementsByAttributeValue(atrName,atrValue) {
    var matchElems = [];

    var allElems = document.getElementsByTagName('*');
    for(var x = 0, len = allElems.length; x < len; x++) {
        if(allElems[x].getAttribute(atrName) != atrValue) {
            continue;
        }

        matchElems.push(allElems[x]);
    }

    return matchElems;
}

Usage would be:
var elems = getElementsByAttributeValue("class","someclass");

A: document.getElementByClassName('testclass'); will give you the element with the testclass, You could also use document.getElementsByTagName('img'); this will give you the img elements.


text:
Q: TimeZoneInfo - AdjustmentRule error on .net core 1.1 I have a piece of code that allows me to get the current date/time (local).
It will be run on Azure.
I'm getting universal time and converting it to local UK time (taking into consideration for BST - British Summer Time).
While migrating from a .NET 4.6.1/Core project to .NET Core 1.1 I'm now faced with a error.

The type name 'AdjustmentRule' does not exist in the type
  'TimeZoneInfo'
'TimeZoneInfo' does not contain a definition for 'GetAdjustmentRules'
  and no extension method 'GetAdjustmentRules' accepting a first
  argument of type 'TimeZoneInfo' could be found (are you missing a
  using directive or an assembly reference?)

Using .NET Core 1.1 only - how can I resolve this?
public static DateTime GetLocalDateTimeNow()
{
    DateTime localDate = System.DateTime.Now.ToUniversalTime();

    // Get the venue time zone info
    TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
    TimeSpan timeDiffUtcClient = tz.BaseUtcOffset;
    localDate = System.DateTime.Now.ToUniversalTime().Add(timeDiffUtcClient);

    if (tz.SupportsDaylightSavingTime && tz.IsDaylightSavingTime(localDate))
    {
        TimeZoneInfo.AdjustmentRule[] rules = tz.GetAdjustmentRules();
        foreach (var adjustmentRule in rules)
        {
            if (adjustmentRule.DateStart <= localDate && adjustmentRule.DateEnd >= localDate)
            {
                localDate = localDate.Add(adjustmentRule.DaylightDelta);
            }
        }
    }

    DateTimeOffset utcDate = localDate.ToUniversalTime();

    return localDate;
}

I don't mind replacing the implementation as long as it takes into account BST and runs on .net core 1.1 (without 4.6.1).

A: You shouldn't need to do any of this yourself - just ask TimeZoneInfo to do the conversion. That's what it's there for!
// Only need to do this once...
private static readonly TimeZoneInfo londonZone =
    TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");

public static DateTime GetUkDateTimeNow() =>
    TimeZoneInfo.ConvertTime(DateTime.UtcNow, londonZone);

A few notes:

*

*I've renamed GetLocalDateTimeNow() to GetUkDateTimeNow() to make it clear that it's always dealing with the UK time zone, not the time zone local to a particular user or computer

*On Unix, you'd need to ask for "Europe/London" instead of "GMT Standard Time"

*To make it independent of any of that - and indeed of the system local time zone data - you could use my Noda Time project which I'd like to think will give you generally cleaner code instead.

Almost no-one needs to deal with AdjustmentRule in their code. I do in Noda Time, because I need to be able to represent TimeZoneInfo zones as Noda Time DateTimeZone objects, but that's pretty unusual. If you ever do need to use them, they're far more complicated than you might expect, and there have been several occurrences of bugs in the .NET implementation; I'm currently (as in, today) fighting bugs in the Mono implementation instead...
As an aside, I would strongly urge you not to use DateTime.Now anywhere. Always use DateTime.UtcNow, and then convert into the system local time zone if you really, really need to.


text:
Q: Visibility in sub-packages How's the visibility of members from a sub-package to its root package?
This is what I mean:
foo          // the "root" package
foo/utils    // a sub-package
foo/tools    // another sub-package

Can foo access private members of foo/utils and foo/tools or do they act as separate, independant packages?

A: Go has no concept of sub-directories nor sub-packages. Packages are separate from each other. The import path "foo/utils" is just an import path (a method of how to find the package) - the string "foo/utils" has no significance other than locating the package on local disk or in the Internet.
foo cannot access private members of foo/utils.
In Go1, each directory in a source tree corresponds to a single package. More about this can be found here: the go command.


text:
Q: Unable to connect to Pivotal cloudfoundry from IntelliJ, Unable to connect to Pivotal cloudfoundry from IntelliJ,
getting the error as Cannot connect : org.springframework.web.client.ResourceAccessException: I?O error on GET request for "http://api.run.pivotal.io/info": api.run.pivotal.io; nested excpetion is java.net.UnknownHostException:api.run.pivotal.io.
Has anybody tried intelliJ with pivotal Cloudfoundry
Thanks

A: You need to connect over https, https://api.run.pivotal.io/info.  Give that a try.  If you connect over http you get a 404, with https the request goes through.


text:
Q: Cassandra not value inserted I'm using cassandra.my columnfamily is testcassa and the column is test1. I tried to insert value like set testcassa['123'][test1]='Sample' but it returns 'null'. and no error message.. can anyone help me..
thanks in advance.

A: [default@unknown] create keyspace mykeyspace;
[default@unknown] use mykeyspace;
[default@mykeyspace] set cf1[1]['c2']=utf8('test');
[default@mykeyspace] get cf1[1];
[default@mykeyspace] set cf1[1]['c2']=utf8('test2');
[default@mykeyspace] del cf1[1];


text:
Q: Extracting row which are not in other dataframes I have one two dataframes df1 and df2, (say df2 is subset of df1) I have to get rows from df1 which are not df2, I have do it in scala, can any help me out on thhis.

A: You can use except:
df1.except(df2)