text:
Q: java.lang.IndexOutOfBoundsException: Index: xx, Size: xx I am loading a .csv file with comma delimiter by using jdom parser to split the data and insert into database.
but somehow I have hit this error as title mentioned.
the .csv file contains of over 200k of records.
when it reads until around 4000 records , the program was thrown this error.
index and size are the same value but before that all the records can be inserted successfully. Just wondering why it goes until almost 4k only hit this error.
this is my for loop :
for(int x = 0; x < FLODS.getBufferSize(); x++)

But I did a search on internet : they are sugguesting this method..
for(int x = 0; x < FLODS.getBufferSize()-1; x++)

Any idea? Thanks :)

A: java.lang.IndexOutOfBoundsException: Index: xx, Size: xx
A very common Exception. This clearly states that you're trying to access an Index of xx, where the Size of the ArrayList(for example) is also xx. Always remember that if the size is xx, you can access the index only till xx-1. If you try to access xx index, where the size is also xx, you are bound to get this error.
Hence the suggestion from Internet, asking you to traverse only till -1 of whatever size.
Though your FOR loop seems to be okay, but may be your are trying to access some index inside the loop which is 1 more than the current x value at some point.

A: java.lang.IndexOutOfBoundsException is a type of exception that appears when index of some sort (such as to an array, to a string, or to a vector) is out of range so check for the memory allotted.
that's all one can say without viewing the code before and within the for loop

A: This is a mistake when you have a nested For loop and try to access the 1st variable in the second one.
for(int i = 0;i<something.size(); i++) {
     //Some manipulations here..
     for(int j = 0;j<somethingElse.size(); j++) {
          //using blah(i) instead of blah(j) causes this issue
     }
}

A: List<WebElement> div1=driver.findElements(By.xpath(".//*[@class='art_title']"));

for(int i=0;i<=div1.size();i++)
{
    System.out.println(div1.get(i).getText());
    Thread.sleep(1000);
}

Instead of the above format I changed it into this format:
List<WebElement> div1=driver.findElements(By.xpath(".//*[@class='art_title']"));
String[] abc = new String[div1.size()];

int i= 0;

for (WebElement e : div1)
{
        abc[i] = e.getText();
        i++;
        System.out.println(e.getText());
}


text:
Q: Error handling np.arccos() and classifying triangles in Python The code below is my attempt at a codewars challenge asking you to calculate the interior angles of a triangle. Really inelegant, brute force.  I'm passing all test cases, but also receiving an error:
-c:37: RuntimeWarning: invalid value encountered in arccos
-c:38: RuntimeWarning: invalid value encountered in arccos
-c:39: RuntimeWarning: invalid value encountered in arccos

So I am trying to figure out how my current checks aren't catching invalid values prior to the gamma calculations (noted with ** in the code, below).
THE PROBLEM:
You should calculate type of triangle with three given sides a, b and c (given in any order).
If all angles are less than 90°, this triangle is acute and function should return 1.
If one angle is strictly 90°, this triangle is right and function should return 2.
If one angle more than 90°, this triangle is obtuse and function should return 3.
If three sides cannot form triangle, or one angle is 180° (which turns triangle into segment) - function should return 0.
Input parameters are sides of given triangle. All input values are non-negative floating point or integer numbers (or both).
import numpy
def triangle_type(a, b, c):
    # Should return triangle type:
    #  0 : if triangle cannot be made with given sides
    #  1 : acute triangle
    #  2 : right triangle
    #  3 : obtuse triangle

    # make sure all sides are non-zero
    if a and b and c:
        pass
    else:
        return 0

    # triangle inequality test
    if not ((c - b) < a < (c + b)) and ((a - c) < b < (a + c)) and ((b - a) < b < (b + a)):
        return 0
    elif a < b < c or b < a < c:
        # print a,b,c
        pass
    elif b < c < a or c < b < a:
        a, c = c, a
        # print a, b, c
    elif c < a < b or a < c < b:
        b, c = c, b
        # print a, b, c
    else:
        # print a, b, c
        pass

    # calculate the gammas **THIS IS WHERE I NEED HELD**
    gamma_1 = numpy.rad2deg(numpy.arccos((a * a + b * b - c * c) / (2.0 * a * b)))
    gamma_2 = numpy.rad2deg(numpy.arccos((c * c + a * a - b * b) / (2.0 * c * a)))
    gamma_3 = numpy.rad2deg(numpy.arccos((b * b + c * c - a * a) / (2.0 * b * c)))

    #check for a right angle
    if (a * a + b * b == c * c) or (b * b + c * c == a * a) or (c * c + b * b == a * a):
        return 2
    #check acute angles
    elif max(gamma_1, gamma_2, gamma_3) < 90.0:
        return 1
    #check obtuse
    elif max(gamma_1, gamma_2, gamma_3) > 90.0:
        return 3
    else:
        return 0

I can't check the validity of the gamma values without actually making the call, thus generating the error.  How can I get around this problem?
Some test cases are
triangle_type(7,3,2) # Not triangle 0
triangle_type(2,4,6) # Not triangle 0
triangle_type(8,5,7) # Acute 1
triangle_type(3,4,5) # Right 2
triangle_type(7,12,8) # Obtuse 3

But this is by no means exhaustive - there are 121 other tests I can't see.

A: You need to check the values you pass to numpy.arccos. They must be between -1 and 1. But due to floating point calculations they could end up larger than 1  or smaller than -1.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Authenticating a Today Widget for API access I need to add a Today Widget/extension to an existing iOS app, which requires the user to sign in via a WKWebView.
As the extension only communicates with Apple frameworks or via openURL() back to the main app, how would I best share the authentication token stored in the main app with the Today Widget/extension, so that it can make authenticated API calls?
Can this be done with a shared keychain? Or is there another secure alternative?
It is not feasible to have the user sign in again in the Today extension UI.

A: You can use App Groups to share data between the main application and today widget extension. You need to activate App Group for your application and create:
UserDefaults.init(suiteName: "group.com.yourOrganization.yourApplicationName")

In the main application set your data in this UserDefaults and try to access it from within your Today Widget extension.

A: Use a Shared Keychain Group to store the token, as described at 14m00s in this WWDC video.


text:
Q: 'typeid' versus 'typeof' in C++ I am wondering what the difference is between typeid and typeof in C++. Here's what I know:

*

*typeid is mentioned in the documentation for  type_info which is defined in the C++ header file typeinfo.

*typeof is defined in the GCC extension for C and in the C++ Boost library.
Also, here is test code test that I've created where I've discovered that typeid does not return what I expected. Why?
main.cpp
#include <iostream>
#include <typeinfo>  //for 'typeid' to work

class Person {
    public:
    // ... Person members ...
    virtual ~Person() {}
};

class Employee : public Person {
    // ... Employee members ...
};

int main () {
    Person person;
    Employee employee;
    Person *ptr = &employee;
    int t = 3;

    std::cout << typeid(t).name() << std::endl;
    std::cout << typeid(person).name() << std::endl;   // Person (statically known at compile-time)
    std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
    std::cout << typeid(ptr).name() << std::endl;      // Person * (statically known at compile-time)
    std::cout << typeid(*ptr).name() << std::endl;     // Employee (looked up dynamically at run-time
                                                       // because it is the dereference of a pointer
                                                       // to a polymorphic class)
 }

output:
bash-3.2$ g++ -Wall main.cpp -o main
bash-3.2$ ./main
i
6Person
8Employee
P6Person
8Employee

A: The primary difference between the two is the following

*

*typeof is a compile time construct and returns the type as defined at compile time

*typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html
typeid Reference: https://en.wikipedia.org/wiki/Typeid

A: typeid provides the type of the data at runtime, when asked for. Typedef is a compile time construct that defines a new type as stated after that. There is no typeof in C++
Output appears as (shown as inscribed comments):
std::cout << typeid(t).name() << std::endl;  // i
std::cout << typeid(person).name() << std::endl;   // 6Person
std::cout << typeid(employee).name() << std::endl; // 8Employee
std::cout << typeid(ptr).name() << std::endl;      // P6Person
std::cout << typeid(*ptr).name() << std::endl;     //8Employee

A: You can use Boost demangle to accomplish a nice looking name:
#include <boost/units/detail/utility.hpp>

and something like
To_main_msg_evt ev("Failed to initialize cards in " + boost::units::detail::demangle(typeid(*_IO_card.get()).name()) + ".\n", true, this);

A: typeid can operate at runtime, and return an object describing the run time type of the object, which must be a pointer to an object of a class with virtual methods in order for RTTI (run-time type information) to be stored in the class. It can also give the compile time type of an expression or a type name, if not given a pointer to a class with run-time type information.
typeof is a GNU extension, and gives you the type of any expression at compile time. This can be useful, for instance, in declaring temporary variables in macros that may be used on multiple types. In C++, you would usually use templates instead.

A: Answering the additional question:

my following test code for typeid does
  not output the correct type name.
  what's wrong?

There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.

These are two different tools. typeof returns the type of an expression, but it is not standard. In C++0x there is something called decltype which does the same job AFAIK.
decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];

Whereas typeid is used with polymorphic types. For example, lets say that cat derives animal:
animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
    // the object is of type cat! but the pointer is base pointer.
}

A: C++ language has no such thing as typeof. You must be looking at some compiler-specific extension. If you are talking about GCC's typeof, then a similar feature is present in C++11 through the keyword decltype. Again, C++ has no such typeof keyword.
typeid is a C++ language operator which returns type identification information at run time. It basically returns a type_info object, which is equality-comparable with other type_info objects.
Note, that the only defined property of the returned type_info object has is its being equality- and non-equality-comparable, i.e. type_info objects describing different types shall compare non-equal, while type_info objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.
Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of typeid to the same type might return different type_info objects (which, of course, still have to compare equal).

A: Although as top commenter pointed out, there is no such thing as typeof in C++, you can leverage function overloads to make a faux typeof function:
const char *type_of(int x){return "int";}
const char *type_of(const char *x){return "const char*";}

Of course, this is could be extended upon to also use other data types. I'm newer to C++, so there may be some issues with it, such as errors at runtime, however in my use case of using template params and descerning an int from a float, for example, was straightforward.
Optimizations: It would probably be better for the overloaded function to return a short as opposed to const char *'s for the sake of memory efficiency, which then could be compared to another short, or plugged into a hash table for the string representation.


text:
Q: Inexplicable ValueError in Pycharm with Python 3.10.4 First and foremost: I'm using Ubuntu 22.04 and Python 3.10.4.
Suddenly my PyCharm IDE is showing me a inexplicable ValueError when I run the script.
A code as simple as bellow return a value error on line 2
a = int(input())
b = int(input())
print(f'{a + b}')

My input:
1
1

The error:
Traceback (most recent call last):
  File "/home/user/sample/Python/main.py", line 2, in <module>
    b = int(input())
ValueError: invalid literal for int() with base 10: ''

Funny enough, if I type anything inside the input() function at line 2, the code works:
a = int(input())
b = int(input("Second number: "))
print(f'{a + b}')

Result:
1
Second number: 1
2

Process finished with exit code 0

Video of the actual behavior:

Can someone explain what is going on here?

A: Tldr update to 2022.1.2 where PyCharm bug was fixed.


text:
Q: how to avoid using instanceof? suppose I have some entities classes hierarchy , and I have a util class with a method that get the upper class hierarchy and has to to some change in another entity class (out of the previous hierarchy) according to the specific class that I got .
So I will use instanceof in order to find what specific object I got.
But I know :
Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.
so how can I do it without using instanceof ?
Please notice that I do not want to put the util method in the entities classes because I want the users (the implementers programmers) to be able to implement the method but I do not want them to be able to change the entities.

A: Instead of this:
// BAD:
public void doStuff(Parent p) {
    if (p instanceof Child1)
        doThis();
    else if (p instanceof Child2)
        doThat();
    else if …
}

do this:
// GOOD:
public class Parent {
    public void doIt();
}

public class Child1 extends Parent {
    @Override
    public void doIt() { /* the contents of doThis */ }
}

public class Child2 extends Parent {
    @Override
    public void doIt() { /* the contents of doThat */  }
}

public void doStuff(Parent p) {
    p.doIt();
}

(The code may not be 100% correct (my Java is a bit rusty) but I hope you get the idea.)
This is called polymorphism.

A: Method overloading is something you might wanna check out.


text:
Q: Using the 2nd conditional with present tenses I know I ask a lot of questions on conditionals here.
It's probably because how they work interest me a lot.
Suppose someone says
"If I was a bacon company owner, I'd see to it that you get a lifetime supply of free bacon."
Is it grammatically correct, the construction?
Does it mean the same thing as, "...., i'd see to it that you got a lifetime supply of free bacon."

A: Both "get" and "got are fine.  The difference in meaning between the two is subtle and minimal, because you're talking about it from the point of view of a hypothetical situation:
"If I owned a bacon factory, I would make sure that you would receive a lifetime supply of bacon."
"If I owned a bacon factory, I would make sure to put you in a situation where you received a lifetime supply of bacon."
Either way, bacon. These are just two different ways to say more or less the same thing.


text:
Q: Youtube Video freezes on clicking fullscreen mode in android webview I am able to play YouTube video in android webview but when i click on "fullscreen" mode of youtube,video freezes but i can still hear the audio.
I have set PluginsEnabled to true and PluginState.ON for webview.
Any help will be appreciated.
Thanks.

A: Try setting this properties, this might help
set the android:hardwareAccelerated="true" in application tag in android manifest.
and set all this properties to webview
        articleView.getSettings().setJavaScriptEnabled(true);
        articleView.getSettings().setPluginsEnabled(true);
        articleView.getSettings().setUserAgentString("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.36 (KHTML, like Gecko) Chrome/13.0.766.0 Safari/534.36");

Hope this helps


text:
Q: Angular JS Touch and Swipe I am very new to angular JS and working on a mobile application. As a part of it, I need to write a service that handles touch events like swipe-left, swipe-right, swipe-up and swipe down and I need to call back depending on which action is made. Please let me know if there any useful tutorials.

A: As mentioned in the comments ngTouch is a good place to start, however it only has swipe left and swipe right. I recommend using Angular Gestures; it's an angular implementation of hammer.js, and has pretty much everything you'd ever need:

*

*doubletap

*dragstart

*drag

*dragup

*dragdown

*dragleft

*dragright

*dragend

*hold

*pinch

*pinchin

*pinchout

*release

*rotate

*swipe

*swipeup

*swipedown

*swipeleft

*swiperight

*tap

*touch

*transformstart

*transform

*transformend

A: Another option is the angular-swipe module. It replaces ng-swipe and uses the same directives, adding up and down:
ng-swipe-up
ng-swipe-down
ng-swipe-left
ng-swipe-right

A: In html i used 5 tabs and i am able to swipe left or right smoothly.
my code given below.
 RECEIVED  |  SENT  |  DELETED  |  ARCHIVED   Reports
In html
ng-swipe-left="leftTab()" ng-swipe-right="rightTab()"
and In controller.
$scope.leftTab = function(){
     if($scope.tab != 4 ){
        $scope.getAlertsSummary($scope.tab + 1);
    }
};

$scope.rightTab = function(){
    if($scope.tab != 0 ){
        $scope.getAlertsSummary($scope.tab - 1);
    }
};

Here getAlertsSummary used for get tab data.


text:
Q: Tkinter in python: Unresolved reference so im making a simple log in and sign up page and all is going well until i try to get my variables from my definition for my sign up page. Python says it is an unresolved reference that should resolve the typing matches and all but maybe somebody can help. Also i know there is a easier way to add pages by using classes but i i decided to do it this way. Thanks ahead of time. p.s the error is in the sign_up_check() code which the variables are gotten from the sign_up() definition.
import tkinter

# window set up

window = tkinter.Tk()
window.geometry("300x200")
window.title("Game")
window.configure(bg="grey26")

# username label

lbl = tkinter.Label(window, text="username", bg="gold")
enter_username = tkinter.Entry(window, bg="indian red1")
lbl.pack()
enter_username.pack()

# password setup

label_password = tkinter.Label(window, text="password", bg="gold")
enter_password = tkinter.Entry(window, bg="indian red1")
label_password.pack()
enter_password.pack()

# sign in

def log_in():
    username = enter_username.get()
    password = enter_password.get()
    if len(username) > 0 and len(password) > 0:
        print("it passed")
    else:
        print("Log in error: Double check username and password")

def sign_up_check():
    # init vars
    username = signup_username.get()
    password = signup_pasword.get()
    age = signup_age.get()
    # check if vars greater than one
    if len(username) > 0 and len(password) > 0 and age > 0:
        print("this all passed")
    else:
        print("all else failed")

def sign_up():
    # create new window

    window1 = tkinter.Toplevel()
    window1.geometry("300x200")
    window1.title("Sign up")
    window1.configure(bg="grey26")
    # create buttons and labels

    # username
    label_sign_up = tkinter.Label(window1, text="Enter new username", bg="indian red1")
    signup_username = tkinter.Entry(window1, bg="gold")
    label_sign_up.pack()
    signup_username.pack()

    # password
    label_sign_up_password = tkinter.Label(window1, text="Enter new password", bg="indian red1")
    signup_password = tkinter.Entry(window1, bg="gold")
    label_sign_up_password.pack()
    signup_password.pack()

    # age
    label_enter_age = tkinter.Label(window1, text="Enter your age", bg="indian red1")
    signup_age = tkinter.Entry(window1, bg="gold")
    label_enter_age.pack()
    signup_age.pack()

    # confirm account
    button_account = tkinter.Button(window1, text="Create account", bg="red", command=lambda: sign_up_check())
    button_account.pack()

# log in button set up

button_login = tkinter.Button(window, text="Log in", bg="gold", command=lambda: log_in())
button_login.pack()

# sign up button

button_signup = tkinter.Button(window, text="Sign up", bg="gold", command=lambda: sign_up())
button_signup.pack()

window.mainloop()

A: The main reason for your behavior is that the locally defined variables from your functions are in a local scope.
That means that they are only available in your local function, not outside of it.
Like martineau pointed out, you have a typo in password in function sign_up_check.
Using global Variables:

*

*to make this work every widget that is created inside a function needs to be created globally.

    def login():
        global enter_username, enter_password
        # [... The rest of the code ...]
    def sign_up_check():
        global signup_username, signup_password, signup_age
        # [... The rest of the code ...]

Is there any specific and programmatically relevant reason why you do not want to use classes?
To be honest with you, i do not see any advantage in using global variables and procedural programming in coding Graphical User Interfaces especially with python.
I highly recommend an object oriented programming style here to improve maintenance of code and reduce the amount of redundant coding (global declaration at beginning, global usage in every function, etc...).


text:
Q: React prevent focus stealing onClick I'm building a simple input component, like this:
const InputComponent = () => {
  const inputField = React.createRef(),
        focusAtInput = () => inputField.current.focus()
  return (

      <input ref={inputField} className="inputfield">
      </input>
      <button>
        x
      </button>
      <button onClick={focusAtInput}>
        ?
      </button>

  )
}

It has sliding out input field upon clicking ? button (which triggers <input> element focus).
Since I don't really like "clear input" button rendered on type="search" attribute specified, I want to implement a custom one (x in my example).
The problem is clicking x button triggers <input>'s onBlur, which I need to avoid before cleaning input. Neither e.stopPropagation() nor e.preventDefault() didn't help. I'm guessing the reason is onBlur is fired before onClick has a chance to stop its propagation.
My question is: is there anything like useCapture parameter of addEventListener() or something else that could've let me prioritize event handlers or avoid stealing focus from input field on click within
 in any other way?
Quick demo of the problem:

const { render } = ReactDOM

const InputComponent = () => {
  const inputField = React.createRef(),
        focusAtInput = () => inputField.current.focus()
  return (

      <input ref={inputField} className="inputfield">
      </input>
      <button onClick={e => e.preventDefault()}>
        x
      </button>
      <button onClick={focusAtInput}>
        ?
      </button>

  )
}

render(<InputComponent />, document.getElementById('root'))
.inputfield {
  width: 0;
  padding: 0;
  border:none;
  transition: width 0.2s;
}
.inputfield:focus {
  padding: 1px;
  width: 150px;
}

A: I would handle the visibility of your text input using React state, not focus & CSS.
This gives you a bit more flexibility on what you can do with it.
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const { render } = ReactDOM;

const InputComponent = () => {
  const [inputValue, setInputValue] = React.useState("");
  const [isVisible, setIsVisible] = React.useState(false);

  const inputField = React.createRef();

  function toggleVisibility() {
    setIsVisible(currValue => !currValue);
  }

  function focusInput() {
    inputField.current.focus();
  }

  function openAndFocusInput() {
    toggleVisibility();
    focusInput();
  }

  function clearInput() {
    focusInput();
    setInputValue("");
  }

  function handleChange(event) {
    setInputValue(event.target.value);
  }

  return (

      <button onClick={clearInput}>x</button>
      <button onClick={openAndFocusInput}>?</button>
      <input
        ref={inputField}
        value={inputValue}
        onChange={handleChange}
        className={`inputfield ${isVisible ? "visible" : ""}`}
      />

  );
};

render(<InputComponent />, document.getElementById("root"));

With a stylesheet like this:
.inputfield {
  width: 0;
  padding: 0;
  border: none;
  transition: width 0.2s;
}
.visible {
  padding: 1px;
  width: 150px;
  border: 1px solid black;
}

I have added a crude black border to highlight when the input is visible or not.
By handling the visibility through the state it means the user can click elsewhere on the page & outside the page without losing the input.
It also means when we clear the input we can apply the focus back to the input.
You can see it working here


text:
Q: Complex Sum Function In Java I am trying to complete the following sigma notation sum but I am honestly stuck, I am not sure how to proceed with the (Xi/2) to the power of i/2. I don't know if I am doing it right in the first place any help would be appreciated it this is the code i have so far.
public static double ComplexSumFunctionA (int[] input) {
    double [] arr15  = {1, 2, 3, 4, 5};
    double sum = 0;
    for (double i = 0; (i < arr15.length/2); i++) {

     }

    return 0;
}

Complex Sum Function

A: The notation xi means the value of ith value of x, so if x is an array it's the value in x[i]

*

*I assumed N is also the array length

*You get the value x[i]

*You divide by 2

*Then power to i/2

*sum it as Sigma is for sum computation

Here it is
public static double complexSumFunctionA(int[] input) {
    double sum = 0, val;
    for (int i = 0; i < input.length; i++) {
        val = Math.pow(input[i] / 2.0, i / 2.0);
        sum += val;
    }
    return sum / (input.length + 3);
}


text:
Q: linearly dependent linear tranformations Let $E$ be a vector space over $k$ of finite dimension $n$. Let $f_1, \ldots, f_p \in \mathcal{L}(E)$ with $p \leq n$ and assume that the $f_i$ are simultaneously diagonalizable (put it simply, there exists a basis of $E$, where the matrices representing the $f_i$ are all diagonal).
Assume that for all $x \in E$, the vectors $f_1(x), \ldots, f_p(x)$ are linearly dependent. Then the vectors $f_1, \ldots, f_p$ are linearly dependent in $\mathcal{L}(E)$.
I have a complicated proof of that, and I'd like to know if there is a simple argument proving this result. Furthermore, I feel like the diagonalizability assumption could be withdrawn and one could only assume that for any $i,j$ we have $f_i \circ f_j = f_j \circ f_i$, but I have no clue on how to prove that last assertion.

A: Without loss of generality $E=k^n$ and the $f_i$ are identified with diagonal matrices $D_i$ with $f_i\colon x\mapsto D_i x$. Now note that for $D=\operatorname{diag}(\lambda_1,\dots,\lambda_n)$ and $\mathbf 1=(1,\dots,1)^t$ we have $D\mathbf 1 = (\lambda_1,\dots,\lambda_n)^t$.
So taking $x=\mathbf 1$ you get that the vectors $D_i\mathbf 1$, which consist of the diagonal entries of the $D_i$, are linearly dependent. Then of course the corresponding diagonal matrices satisfy the same linear relation.

A: Counterexample for the case when the matrices are not simultaneously diagonalisable:
$$f_1:=\begin{pmatrix}1&1\\0&0\end{pmatrix},\qquad f_2:=\begin{pmatrix}1&2\\0&0\end{pmatrix}$$
Then $f_1,f_2$ are linearly independent, yet for any vector $x=(a,b)^t$, $$\tfrac{1}{a+b}f_1(x)+\tfrac{1}{a+2b}f_2(x)=0$$ (unless $a+b=0$ or $a+2b=0$; those cases correspond to eigenvectors of $f_1$, $f_2$ respectively, so $f_1(x)=0$ or $f_2(x)=0$, so $f_1(x)$, $f_2(x)$ are still dependent.)

Looking at the $2\times2$ case, commutativity of the matrices is not required for the property to hold; rather it is invertibility.
Suppose $f_1=\begin{pmatrix}a&b\\c&d\end{pmatrix}$ is invertible and $f_2=\begin{pmatrix}\alpha a&\beta b\\\alpha c&\beta d\end{pmatrix}$ are as in the question. The second matrix must be of this form since $f_1(\mathbf{i})$, $f_2(\mathbf{i})$ are linearly dependent, and similarly $f_1(\mathbf{j})$, $f_2(\mathbf{j})$. Furthermore, $f_1(x)$ and $f_2(x)$ are in the same direction, hence if $x=(u,v)^t$, then $$\lambda\begin{pmatrix}au+bv\\cu+dv\end{pmatrix}=\begin{pmatrix}\alpha au+\beta bv\\\alpha cu+\beta dv\end{pmatrix}$$ $$\therefore\ (au+bv)(\alpha cu+\beta dv)=(cu+dv)(\alpha au+\beta bv)$$ $$\therefore\ (\beta-\alpha)(ad-bc)uv=0$$ Hence $\alpha=\beta$, that is, $f_2=\alpha f_1$ as required.


text:
Q: Why use jQuery filter? Why is there a filter function in jQuery when you can get and show / hide the elements by class?
$('.yourClass');

A: Just because you have some elements that you'd like to work with doesn't mean that they're in the DOM. Consider this contrived example:
var $els = $('

');
console.log($('.a'));
console.log($els.find('.a'));
console.log($els.filter('.a'));

Demo: http://jsfiddle.net/ambiguous/h3GMB/
The first one, $('.a'), gives you nothing because $els aren't in the DOM yet. The second one also gives you nothing because find searches descendents. Only the third one will give you what you're looking for because filter reduces:

the set of matched elements to those that match the selector [...]

This sort of manipulation of things not in the DOM is fairly common when preparing template chunks for the DOM. The difference between filter and find is also fairly important even when the elements in question are in the DOM.

A: As from the document:

Given a jQuery object that represents a set of DOM elements, the .filter() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; all elements matching the selector will be included in the result.
Consider a page with a simple list on it:
We can apply this method to the set of list items:

$('li').filter(':even').css('background-color', 'red');

The result of this call is a red background for items 1, 3, and 5, as they match the selector (recall that :even and :odd use 0-based indexing).

The filter function is used to filter the result of your original query into specific elements.
But if you are referring to .hide() and .show(), it's a choice you have, instead of splitting your code into both css and javascript, you have a couple of methods that are cross browser to do the job instead.

A: filter allows you to filter part of the set you have, let's say we have a list of items, and to all items I want to add a class, but to part of it I want to add another class:
$('#mylist li').addClass('someclass').filter('.someotherclass').addClass('filtered');

I could have split this up in two queries.


text:
Q: Delphi - Use an existing automation object in a new application I've got an existing application which has an an automation object.
I have to rewrite this application, and I would like to use the existing automation object in the new application.
Is this possible somehowm, or do I have to create a new automation object in the new application and copy-paste the functions from the old one?
Thanks for your advice!

A: I think you may not need to re-write the automation object, and you can keep the old one, as long as it is running properly.
Re-writing working code is necessary only if you want to extend the functionality, or overcome incompatibility with new versions of the OS.  Otherwise it is plainly risky.


text:
Q: Swift 5 self.displayAlert error - "Value of type 'ViewController' has no member 'displayAlert'" I'm trying to make a sign in and sign out function using back4app. There is an error with the self.displayAlert lines, with xcode saying

Value of type 'ViewController' has no member 'displayAlert'

Code:
@IBAction func signin(_ sender: Any) {
    PFUser.logInWithUsername(inBackground: self.userSignin.text!, password: self.passSignin.text!) {
      (user: PFUser?, error: Error?) -> Void in
      if user != nil {
        self.displayAlert(withTitle: "Login Successful", message: "")
      } else {
        self.displayAlert(withTitle: "Error", message: error!.localizedDescription)
      }
    }
}

@IBAction func signup(_ sender: Any) {
    let user = PFUser()
    user.username   = self.userSignup.text
    user.password = self.passsSignup.text

    user.signUpInBackground {(succeeded: Bool, error: Error?) -> Void in
        if let error = error{
            self.displayAlert(withTitle: "Error", message: error.localizedDescription)
        } else {
            self.displayAlert(withTitle: "Success", message: "Account has been successfully created")
        }

    }
}

A: add this extension :
    extension UIViewController {

        func displayAlert(withTitle: String, message: String) {

            let alertController = UIAlertController(title:withTitle, message: message, preferredStyle: .alert)
            let action1 = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in

            }
            alertController.addAction(action1)
            self.present(alertController, animated: true, completion: nil)
        }
}


text:
Q: EventKit + Swift: Get Events I am trying to use EventKit to read the user's current events for the day and am having some trouble.
To make it easier, I tried using TTEventKit for wrapping, but still without success.   Here's my current code:
 override func viewDidLoad() {
    super.viewDidLoad()
    EventStore.requestAccess() { (granted, error) in
        if granted {
            print("got permission")
        }
    }

    let events = EventStore.getEvents(Month(year: 2016, month: 7))

    if events != nil {
        for e in events {
            print("Title \(e.title)")
            print("startDate: \(e.startDate)")
            print("endDate: \(e.endDate)")

    }

}
}

The code above is printing the events, but there are a few things that aren't working:

*

*it won't accept NSDate for getevents and

*it is only getting the events from a generic calendar (just showing like US holidays).

How can I fix these two issues?


text:
Q: Android Bluetooth sending concatenated data at once I am using Bluetooth Chat App code to transfer data between two android device.
But the code is sending concatenated data.
For example: When I try to send data like below:

*

*a

*b

*c

*d

It sometime send data in this form:

*

*a

*bc

*d

Here is my write code for sending data:
public synchronized void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            mHandler.obtainMessage(BluetoothHelper.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
            mmOutStream.flush();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

Also my read code is:
if (mmInStream.available()>0){
                    bytes = mmInStream.read(buffer);
                    mHandler.obtainMessage(BluetoothHelper.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                }else {
                    SystemClock.sleep(100);
                }

I tried flush and sleep but they dont fix problem. Please help.

A: The concatenation is taking place due to difference in execution speed of two different threads.
One is the UI thread (you android application), i.e. where the data received over Bluetooth is being viewed. The UI thread refresh is by following line.
mHandler.obtainMessage(BluetoothHelper.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();

And the second thread is the one collecting the data being received over Bluetooth link. the code receiving the data over Bluetooth is:
mmInStream.read(buffer);

This is a blocking call, i.e. returns only when something is received over Bluetooth.
The UI thread is refreshing the view comparatively slowly than the data being received over Bluetooth thread. It means by the time UI view is refreshed next time, more than one characters may have already received on BT reading thread. Hence it appears the data is concatenated. And this concatenation will be at random times and with random number characters being concatenated.
To resolve this issue:
1) While transmitting : Transmit character (or a packet) followed by a delimiter character.
2) And while receiving : Send the message to UI only after concluding that a  character (or a packet) followed by a delimiter is received. That means you will have to accumulate the receiving characters and verify these accumulated buffer each time after the blocking call mmOutStream.write(buffer) returns.
Have a look at this question and answer provided therein.


text:
Q: -[User length]: unrecognized selector sent to instance 0x7fc7b60143e0' I have the following code and receive the error code indicated in title:
This is the only messages i send to User object (other than initialising it by using "new")
When I out comment addObject: it doesn't complain.
Can anybody help? Thanks!
self.freshUser.name = self.name.text;
self.freshUser.age = (int)self.age.text;
self.freshUser.gender = self.gender.text;

//NSLog(@"%@",[NSThread callStackSymbols]);
[appDelegate.users addObject:self.freshUser];

(My user object subclasses NSObject. it has more property that I don't use. just a little extra info)
-(UITableViewCell *)tableView:(UITableView *)tableViewPara cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UserCell *cell = [tableViewPara dequeueReusableCellWithIdentifier:usersTableIdentifier forIndexPath:indexPath];

  if(indexPath.row == [appDelegate.users count]){
    cell.nameLabel.text = @"+";
    cell.nameLabel.font = [UIFont systemFontOfSize:36];
    cell.bgImg.image = [UIImage imageNamed:@"background_gray"];
    cell.statusImg.image = nil;
  }else{
    cell.nameLabel.text = appDelegate.users[indexPath.row];
    cell.nameLabel.font = [UIFont systemFontOfSize:17];
    cell.bgImg.image = [UIImage imageNamed:@"background_dark_red"];
    cell.statusImg.image = [UIImage imageNamed:@"icon_cloud"];
  }
  cell.nameLabel.textAlignment = NSTextAlignmentCenter;
  cell.nameLabel.textColor = [UIColor whiteColor];
  cell.nameLabel.backgroundColor = [UIColor clearColor];

  return cell;
}

space
0   CoreFoundation                      0x000000010ff1bf35 __exceptionPreprocess + 165
1   libobjc.A.dylib                     0x000000010fbb4bb7 objc_exception_throw + 45
2   CoreFoundation                      0x000000010ff2304d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3   CoreFoundation                      0x000000010fe7b27c ___forwarding___ + 988
4   CoreFoundation                      0x000000010fe7ae18 _CF_forwarding_prep_0 + 120
5   UIKit                               0x00000001104d034b -[UILabel _setFont:] + 101
6   Raymio                              0x000000010f67857f -[StartViewController tableView:cellForRowAtIndexPath:] + 991
7   UIKit                               0x00000001103ff4b3 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 508
8   UIKit                               0x00000001103defb1 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2846
9   UIKit                               0x00000001103f4e3c -[UITableView layoutSubviews] + 213
10  UIKit                               0x0000000110381973 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
11  QuartzCore                          0x0000000113c09de8 -[CALayer layoutSublayers] + 150
12  QuartzCore                          0x0000000113bfea0e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
13  QuartzCore                          0x0000000113bfe87e _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
14  QuartzCore                          0x0000000113b6c63e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
15  QuartzCore                          0x0000000113b6d74a _ZN2CA11Transaction6commitEv + 390
16  QuartzCore                          0x0000000113b6ddb5 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
17  CoreFoundation                      0x000000010fe50dc7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
18  CoreFoundation                      0x000000010fe50d20 __CFRunLoopDoObservers + 368
19  CoreFoundation                      0x000000010fe46b53 __CFRunLoopRun + 1123
20  CoreFoundation                      0x000000010fe46486 CFRunLoopRunSpecific + 470
21  GraphicsServices                    0x00000001134fd9f0 GSEventRunModal + 161
22  UIKit                               0x0000000110308420 UIApplicationMain + 1282
23  Raymio                              0x000000010f678a83 main + 115
24  libdyld.dylib                       0x00000001124ab145 start + 1

A: This line:
cell.nameLabel.text = appDelegate.users[indexPath.row];

You're trying to set a User object to the text of a label field. That's not going to work. You'll want this or something close:
cell.nameLabel.text = ((User *)appDelegate.users[indexPath.row]).name;

A: You shared your stack trace with us. A useful technique is to look in it for anything that references code you wrote. You may notice that line 6 references your StartViewController:
6   Raymio                              0x000000010f67857f -[StartViewController tableView:cellForRowAtIndexPath:] + 991

You can show the relevant line of code by typing source list command using that address in the third column:
(lldb) source list -a 0x000000010f67857f

   43        cell.nameLabel.text = @"+";
   44        cell.nameLabel.font = [UIFont systemFontOfSize:36];
   45        cell.bgImg.image = [UIImage imageNamed:@"background_gray"];
   46        cell.statusImg.image = nil;
   47      }else{
-> 48        cell.nameLabel.text = appDelegate.users[indexPath.row];
   49        cell.nameLabel.font = [UIFont systemFontOfSize:17];
   50        cell.bgImg.image = [UIImage imageNamed:@"background_dark_red"];
   51        cell.statusImg.image = [UIImage imageNamed:@"icon_cloud"];
   52      }

Clearly your line numbers and memory addresses will vary, but hopefully this will illustrate the idea. Scan the stack trace for anything that references your code, and examine that line of code for any potential issues.
By the way, this discussion. also shows you how to use the -[StartViewController tableView:cellForRowAtIndexPath:] + 991 of the stack trace to show the relevant line of code.


text:
Q: Display folder and file (only .doc/docx) in tree view with their icon I am creating a window form in C# where I have a TreeView control. I have to do following task:

*

*Click on a browse button

*Select the base folder

*Display all the files(.doc/.docx) and folder of the base folder with their icon

*Click the sub-folder to expand it and display the files and folders it contains

Kindly give me some suggestions/links.

A: This must help you http://www.csharp-examples.net/get-files-from-directory/

A: I have used thet following code:
   void GetTree(string strSearchPath)
        {
            treeFiles.Nodes.Clear();
            SetNode(treeFiles, strSearchPath);
            treeFiles.TopNode.Expand();
        }

        void SetNode(TreeView treeName, string path)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            TreeNode node = new TreeNode(dirInfo.Name);
            node.Tag = dirInfo;
            GetFolders(dirInfo, node);
            GetFiles(dirInfo, node);
            treeName.Nodes.Add(node);
        }

        void GetFolders(DirectoryInfo d, TreeNode node)
        {

            try
            {
                DirectoryInfo[] dInfo = d.GetDirectories();

                if (dInfo.Length > 0)
                {
                    TreeNode treeNode = new TreeNode();
                    foreach (DirectoryInfo driSub in dInfo)
                    {
                        treeNode = node.Nodes.Add(driSub.Name, driSub.Name, 0, 0);
                        GetFiles(driSub, treeNode);
                        GetFolders(driSub, treeNode);
                    }
                }
            }
            catch (Exception ex) { }

        }

        void GetFiles(DirectoryInfo d, TreeNode node)
        {
            var files = d.GetFiles("*.doc*");
            FileInfo[] subfileInfo = files.ToArray<FileInfo>();

            if (subfileInfo.Length > 0)
            {
                for (int j = 0; j < subfileInfo.Length; j++)
                {
                    bool isHidden = ((File.GetAttributes(subfileInfo[j].FullName) & FileAttributes.Hidden) == FileAttributes.Hidden);
                    if (!isHidden)
                    {
                        string strExtention = Path.GetExtension(subfileInfo[j].FullName);
                        if (strExtention.Contains("doc"))
                        {
                            TreeNode treeNode = new TreeNode();
                            string path = subfileInfo[j].FullName;
                            string name = subfileInfo[j].Name;
                            treeNode = node.Nodes.Add(path, name, 1, 1);
                            AddBookMarkFile(path, treeNode);
                        }
                    }
                }
            }
        }


text:
Q: VB.NET Unable to find data using datatable.select() dt is a datatable from ODBC, where i need to find a specific value
LookupCode is returning correct value from DataGrid
LookupRow is returning System.NullReferenceException but i'm sure that in dt there is data that I'm looking for
Imports System.Linq
...
Dim dt As New DataTable
Dim LookupRow As DataRow
Dim LookupCode As String

If dt.Rows.Count > 0 Then
   For Each row As DataGridViewRow In MagDataGridView.Rows
      LookupCode = row.Cells(1).Value
      LookupRow = dt.Select("'" & dt.Columns(0).ColumnName & "'='" & LookupCode & "'").FirstOrDefault
      row.Cells(5).Value = LookupRow.Item(1)
   Next
End If

Screenshot of Compilator
After 1st comment
If i change the line to LookupRow = dt.Select(dt.Columns(0).ColumnName & "='" & LookupCode & "'").First
then i have unable to perform '=' on System.Int32 and System.String."
Solved with this replacement of code:
Dim fRow = From row In dt.AsEnumerable()
 Where row.Field(Of String)(dt.Columns(0).ColumnName) = LookupCode
 LookupRow = fRow.First
 r.Cells(5).Value = LookupRow.Item(1)


text:
Q: Existing Database Indentity Column MVC 4 I am using an existing database to create an Project Reporting System. And I want the Primary Key, which is the Project id value of the project table to be automatically created and it is not setting a new value, as I have to input the Id, but I don't want the user to do that. Can anyone help me with this problem please?
Patrick
Controller
`        //
        // GET: /Project/Create
    public ActionResult Create()
    {
        ViewBag.Status = new SelectList(db.pjt_Statuses, "pjt_Status_ID", "StatusName");
        ViewBag.SubCategoryID = new SelectList(db.pjt_SubCategories, "pjt_SubCat_ID", "SubCatName");
        return View();
    }

    //
    // POST: /Project/Create

    [HttpPost]
    public ActionResult Create(pjt_Projects pjt_projects)
    {
        if (ModelState.IsValid)
        {
            pjt_projects.CreationDate = DateTime.Now;
            db.pjt_Projects.Add(pjt_projects);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.Status = new SelectList(db.pjt_Statuses, "pjt_Status_ID", "StatusName", pjt_projects.Status);
        ViewBag.SubCategoryID = new SelectList(db.pjt_SubCategories, "pjt_SubCat_ID", "SubCatName", pjt_projects.SubCategoryID);
        return View(pjt_projects);
    }`

Database Table Script
`CREATE TABLE [dbo].[pjt_Projects](
[Pjt_Id] [int] IDENTITY(1,1) NOT NULL,
[ProjectName] [nchar](100) NULL,
[Status] [int] NULL,
[Start_Date] [date] NULL,
[Estimated_End_Date] [date] NULL,
[Documents] [nvarchar](max) NULL,
[Notes] [nvarchar](max) NULL,
[Budget] [smallmoney] NULL,
[Current_Spending] [smallmoney] NULL,
[ProjectOwner] [nvarchar](50) NULL,
[Active] [bit] NULL,
[Actual_End_date] [date] NULL,
[CreationDate] [date] NULL,
[CreatedByEmpNo] [nchar](10) NULL,
[UpdateDate] [date] NULL,
[UpdatedByEmpNo] [nchar](10) NULL,
[SubCategoryID] [int] NULL,`

**Generate Context Db Code**
    public int Pjt_Id { get; set; }
    public string ProjectName { get; set; }
    public Nullable<int> Status { get; set; }
    public Nullable<System.DateTime> Start_Date { get; set; }
    public Nullable<System.DateTime> Estimated_End_Date { get; set; }
    public string Documents { get; set; }
    public string Notes { get; set; }
    public Nullable<decimal> Budget { get; set; }
    public Nullable<decimal> Current_Spending { get; set; }
    public string ProjectOwner { get; set; }
    public Nullable<bool> Active { get; set; }
    public Nullable<System.DateTime> Actual_End_date { get; set; }
    public Nullable<System.DateTime> CreationDate { get; set; }
    public string CreatedByEmpNo { get; set; }
    public Nullable<System.DateTime> UpdateDate { get; set; }
    public string UpdatedByEmpNo { get; set; }
    public Nullable<int> SubCategoryID { get; set; }

A: Simply exclude the ID field from the Razor view.  (Self explanatory unless you're using EditorForModel, in which case you'd need to modify the Display annotation for the ID field, so that the Razor engine knows to exclude it from the view.)
Once excluded, its value will not get posted back to the server.  That way it will get the default value when created in the MVC controller; and the database will auto-generate the new ID.


text:
Q: LUA count repeating characters in string I have a string "A001BBD0" and i want to know this info:

*

*0 repeats 3 times

*B repeats 2 times

and that's it.
I found this pattern on web: "([a-zA-Z]).*(\1)" but it always returns nil for some reason
I guess i should split this string and check each symbol in several loops. I don't think this is a good idea (low performance)
i also found this topic but it doesn't give me any information

A: gsub returns the number of substitutions. So, try this code:
function repeats(s,c)
    local _,n = s:gsub(c,"")
    return n
end

print(repeats("A001BBD0","0"))
print(repeats("A001BBD0","B"))

A: Creating a record for each alphanumeric char will give a more generic solution
local records = {} -- {['char'] = #number of occurances}
s = "A001BBD0"
for c in string.gmatch(s, "%w") do
    if records[c] then
        records[c] = records[c] + 1
    else
        records[c] = 1
    end
end

for k,v in pairs(records) do
    if(v > 1) then -- print repeated chars
        print(k,v)
    end
end
-- Output:
-- 0    3
-- B    2

A: Shorter version of the previous answer about use of the ternary operator
local records = {}
s = "A001BBD0"
for c in string.gmatch(s, "%w") do
    records[c] = records[c] and records[c] + 1 or 1
end

for k,v in pairs(records) do
    if(v > 1) then -- print repeated chars
        print(k,v)
    end
end

A: Here's an even shorter answer than the previous ones that I just came up with.
This is the simplest, and most efficient way to count repeating characters in a string on Lua.
local str = "A001BBD0"

local count_0 = #string.gsub(str, "[^0]", "") -- count the 0's only
local count_B_and_0 = #string.gsub(str, "[^B0]", "") -- count the B's and 0's together

print(count_0, count_B_and_0)


text:
Q: '\cite{}' is behaving oddly: it will only show [?] I decided to make a new and simple question from my previous question since I found that my \cite{} command behaved wrong.
I used this example from http://grad.iit.edu/latex/LaTeX/BiblioHelp2.pdf:
\documentclass{report}

\begin{document}

time approaches infinity \cite{Pan}.

\begin{thebibliography}{100} % 100 is a random guess of the total number of
%references

\bibitem{Boney96} Boney, L., Tewfik, A.H., and Hamdy, K.N., ``Digital
Watermarks for Audio Signals," \emph{Proceedings of the Third IEEE
International Conference on Multimedia}, pp. 473-480, June 1996.

\bibitem{MG} Goossens, M., Mittelbach, F., Samarin, \emph{A LaTeX
Companion}, Addison-Wesley, Reading, MA, 1994.

\bibitem{HK} Kopka, H., Daly P.W., \emph{A Guide to LaTeX},
Addison-Wesley, Reading, MA, 1999.

\bibitem{Pan} Pan, D., ``A Tutorial on MPEG/Audio Compression," \emph{IEEE
Multimedia}, Vol.2, pp.60-74, Summer 1998.

\end{thebibliography}
\end{document}

My result:

you can see [?] instead of [4] from the example. Any suggests to fix it? Yes, I checked the version. All are in the most recently version..
However, I received 3 warnings:
Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO)
LaTeX Warning: Citation `Pan' on page 1 undefined on input line 54.
LaTeX Warning: There were undefined references.
LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

This is from entire log file:
This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2014) (preloaded format=pdflatex   2014.10.30)  12 NOV 2014 09:32
entering extended mode
 restricted \write18 enabled.
 %&-line parsing enabled.
**test.tex
(./test.tex
LaTeX2e <2014/05/01>
Babel <3.9l> and hyphenation patterns for 79 languages loaded.
(/usr/local/texlive/2014/texmf-dist/tex/latex/base/report.cls
Document Class: report 2007/10/19 v1.4h Standard LaTeX document class
(/usr/local/texlive/2014/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2007/10/19 v1.4h Standard LaTeX file (size option)
)
\c@part=\count79
\c@chapter=\count80
\c@section=\count81
\c@subsection=\count82
\c@subsubsection=\count83
\c@paragraph=\count84
\c@subparagraph=\count85
\c@figure=\count86
\c@table=\count87
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/graphics/graphicx.sty
Package: graphicx 2014/04/25 v1.0g Enhanced LaTeX Graphics (DPC,SPQR)

(/usr/local/texlive/2014/texmf-dist/tex/latex/graphics/keyval.sty
Package: keyval 2014/05/08 v1.15 key=value parser (DPC)
\KV@toks@=\toks14
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/graphics/graphics.sty
Package: graphics 2009/02/05 v1.0o Standard LaTeX Graphics (DPC,SPQR)

(/usr/local/texlive/2014/texmf-dist/tex/latex/graphics/trig.sty
Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/latexconfig/graphics.cfg
File: graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
)
Package graphics Info: Driver file: pdftex.def on input line 91.

(/usr/local/texlive/2014/texmf-dist/tex/latex/pdftex-def/pdftex.def
File: pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX

(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/infwarerr.sty
Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO)
)
(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/ltxcmds.sty
Package: ltxcmds 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
)
\Gread@gobject=\count88
))
\Gin@req@height=\dimen103
\Gin@req@width=\dimen104
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/graphics/color.sty
Package: color 2014/04/23 v1.1a Standard LaTeX Color (DPC)

(/usr/local/texlive/2014/texmf-dist/tex/latex/latexconfig/color.cfg
File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
)
Package color Info: Driver file: pdftex.def on input line 137.
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/framed/framed.sty
Package: framed 2011/10/22 v 0.96: framed or shaded text with page breaks
\OuterFrameSep=\skip43
\fb@frw=\dimen105
\fb@frh=\dimen106
\FrameRule=\dimen107
\FrameSep=\dimen108
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/base/alltt.sty
Package: alltt 1997/06/16 v2.0g defines alltt environment
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/upquote/upquote.sty
Package: upquote 2012/04/19 v1.3 upright-quote and grave-accent glyphs in verba
tim
)
No file test.aux.
\openout1 = `test.aux'.

LaTeX Font Info:    Checking defaults for OML/cmm/m/it on input line 53.
LaTeX Font Info:    ... okay on input line 53.
LaTeX Font Info:    Checking defaults for T1/cmr/m/n on input line 53.
LaTeX Font Info:    ... okay on input line 53.
LaTeX Font Info:    Checking defaults for OT1/cmr/m/n on input line 53.
LaTeX Font Info:    ... okay on input line 53.
LaTeX Font Info:    Checking defaults for OMS/cmsy/m/n on input line 53.
LaTeX Font Info:    ... okay on input line 53.
LaTeX Font Info:    Checking defaults for OMX/cmex/m/n on input line 53.
LaTeX Font Info:    ... okay on input line 53.
LaTeX Font Info:    Checking defaults for U/cmr/m/n on input line 53.
LaTeX Font Info:    ... okay on input line 53.
(/usr/local/texlive/2014/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
\scratchcounter=\count89
\scratchdimen=\dimen109
\scratchbox=\box26
\nofMPsegments=\count90
\nofMParguments=\count91
\everyMPshowfont=\toks15
\MPscratchCnt=\count92
\MPscratchDim=\dimen110
\MPnumerator=\count93
\makeMPintoPDFobject=\count94
\everyMPtoPDFconversion=\toks16
) (/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/pdftexcmds.sty
Package: pdftexcmds 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO
)

(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/ifluatex.sty
Package: ifluatex 2010/03/01 v1.3 Provides the ifluatex switch (HO)
Package ifluatex Info: LuaTeX not detected.
)
(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/ifpdf.sty
Package: ifpdf 2011/01/30 v2.3 Provides the ifpdf switch (HO)
Package ifpdf Info: pdfTeX in PDF mode is detected.
)
Package pdftexcmds Info: LuaTeX not detected.
Package pdftexcmds Info: \pdf@primitive is available.
Package pdftexcmds Info: \pdf@ifprimitive is available.
Package pdftexcmds Info: \pdfdraftmode found.
)
(/usr/local/texlive/2014/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty
Package: epstopdf-base 2010/02/09 v2.5 Base part for package epstopdf

(/usr/local/texlive/2014/texmf-dist/tex/latex/oberdiek/grfext.sty
Package: grfext 2010/08/19 v1.1 Manage graphics extensions (HO)

(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/kvdefinekeys.sty
Package: kvdefinekeys 2011/04/07 v1.3 Define keys (HO)
))
(/usr/local/texlive/2014/texmf-dist/tex/latex/oberdiek/kvoptions.sty
Package: kvoptions 2011/06/30 v3.11 Key value format for package options (HO)

(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/kvsetkeys.sty
Package: kvsetkeys 2012/04/25 v1.16 Key value parser (HO)

(/usr/local/texlive/2014/texmf-dist/tex/generic/oberdiek/etexcmds.sty
Package: etexcmds 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
Package etexcmds Info: Could not find \expanded.
(etexcmds)             That can mean that you are not using pdfTeX 1.50 or
(etexcmds)             that some package has redefined \expanded.
(etexcmds)             In the latter case, load this package earlier.
)))
Package grfext Info: Graphics extension search list:
(grfext)             [.png,.pdf,.jpg,.mps,.jpeg,.jbig2,.jb2,.PNG,.PDF,.JPG,.JPE
G,.JBIG2,.JB2,.eps]
(grfext)             \AppendGraphicsExtensions on input line 452.

(/usr/local/texlive/2014/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg
File: epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Liv
e
))

LaTeX Warning: Citation `Pan' on page 1 undefined on input line 55.

[1

{/usr/local/texlive/2014/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
[2

] (./test.aux)

LaTeX Warning: There were undefined references.

LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.

 )
Here is how much of TeX's memory you used:
 1623 strings out of 493109
 23450 string characters out of 6135003
 81506 words of memory out of 5000000
 5092 multiletter control sequences out of 15000+600000
 4900 words of font info for 18 fonts, out of 8000000 for 9000
 1141 hyphenation exceptions out of 8191
 38i,5n,23p,281b,147s stack positions out of 5000i,500n,10000p,200000b,80000s
</usr/local/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx10.pfb
></usr/local/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx12.pfb>
</usr/local/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.pfb></
usr/local/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmti10.pfb>
Output written on test.pdf (2 pages, 54797 bytes).
PDF statistics:
 27 PDF objects out of 1000 (max. 8388607)
 18 compressed objects within 1 object stream
 0 named destinations out of 1000 (max. 500000)
 1 words of extra memory for PDF output out of 10000 (max. 10000000)

Updated: Also I am not sure if this is important information. I used R Sweave document in Rstudio on the Mac machine.
From .tex file:
\documentclass{report}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

\definecolor{fgcolor}{rgb}{0.345, 0.345, 0.345}
\newcommand{\hlnum}[1]{\textcolor[rgb]{0.686,0.059,0.569}{#1}}%
\newcommand{\hlstr}[1]{\textcolor[rgb]{0.192,0.494,0.8}{#1}}%
\newcommand{\hlcom}[1]{\textcolor[rgb]{0.678,0.584,0.686}{\textit{#1}}}%
\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}%
\newcommand{\hlstd}[1]{\textcolor[rgb]{0.345,0.345,0.345}{#1}}%
\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.161,0.373,0.58}{\textbf{#1}}}%
\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.69,0.353,0.396}{#1}}%
\newcommand{\hlkwc}[1]{\textcolor[rgb]{0.333,0.667,0.333}{#1}}%
\newcommand{\hlkwd}[1]{\textcolor[rgb]{0.737,0.353,0.396}{\textbf{#1}}}%

\usepackage{framed}
\makeatletter
\newenvironment{kframe}{%
 \def\at@end@of@kframe{}%
 \ifinner\ifhmode%
  \def\at@end@of@kframe{\end{minipage}}%
  \begin{minipage}{\columnwidth}%
 \fi\fi%
 \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep
 \colorbox{shadecolor}{##1}\hskip-\fboxsep
     % There is no \\@totalrightmargin, so:
     \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}%
 \MakeFramed {\advance\hsize-\width
   \@totalleftmargin\z@ \linewidth\hsize
   \@setminipage}}%
 {\par\unskip\endMakeFramed%
 \at@end@of@kframe}
\makeatother

\definecolor{shadecolor}{rgb}{.97, .97, .97}
\definecolor{messagecolor}{rgb}{0, 0, 0}
\definecolor{warningcolor}{rgb}{1, 0, 1}
\definecolor{errorcolor}{rgb}{1, 0, 0}
\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX

\usepackage{alltt}
\usepackage{infwarerr}
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}

time approaches infinity \cite{Pan}.

\begin{thebibliography}{100} % 100 is a random guess of the total number of
%references

\bibitem{Boney96} Boney, L., Tewfik, A.H., and Hamdy, K.N., ``Digital
Watermarks for Audio Signals," \emph{Proceedings of the Third IEEE
International Conference on Multimedia}, pp. 473-480, June 1996.

\bibitem{MG} Goossens, M., Mittelbach, F., Samarin, \emph{A LaTeX
Companion}, Addison-Wesley, Reading, MA, 1994.

\bibitem{HK} Kopka, H., Daly P.W., \emph{A Guide to LaTeX},
Addison-Wesley, Reading, MA, 1999.

\bibitem{Pan} Pan, D., ``A Tutorial on MPEG/Audio Compression," \emph{IEEE
Multimedia}, Vol.2, pp.60-74, Summer 1998.

\end{thebibliography}

\end{document}


text:
Q: Spring reactive : mixing RestTemplate & WebClient I have two endpoints : /parent and /child/{parentId}
I need to return list of all Child
public class Parent {
  private long id;
  private Child child;
}

public class Child {
  private long childId;
  private String someAttribute;
}

However, call to /child/{parentId} is quite slow, so Im trying to do this:

*

*Call /parent to get 100 parent data, using asynchronous RestTemplate

*For each parent data, call /child/{parentId} to get detail

*Add the result call to /child/{parentId} into resultList

*When 100 calls to /child/{parentId} is done, return resultList
I use wrapper class since most endpoints returns JSON in format :
{
  "next": "String",
  "data": [
    // parent goes here
  ]
}

So I wrap it in this
public class ResponseWrapper<T> {
  private List<T> data;
  private String next;
}

I wrote this code, but the resultList always return empty elements.
What is the correct way to achieve this?
public List<Child> getAllParents() {
    var endpointParent = StringUtils.join(HOST, "/parent");
    var resultList = new ArrayList<Child>();

    var responseParent = restTemplate.exchange(endpointParent, HttpMethod.GET, httpEntity,
            new ParameterizedTypeReference<ResponseWrapper<Parent>>() {
            });

    responseParent.getBody().getData().stream().forEach(parent -> {
        var endpointChild = StringUtils.join(HOST, "/child/", parent.getId());
        // async call due to slow endpoint child
        webClient.get().uri(endpointChild).retrieve()
                .bodyToMono(new ParameterizedTypeReference<ResponseWrapper<Child>>() {
                }).map(wrapper -> wrapper.getData()).subscribe(children -> {
                    children.stream().forEach(child -> resultList.add(child));
                });
    });

    return resultList;
}

A: Calling subscribe on a reactive type starts the processing but returns immediately; you have no guarantee at that point that the processing is done. So by the time your snippet is calling return resultList, the WebClient is probably is still busy fetching things.
You're better off discarding the async resttemplate (which is now deprecated in favour of WebClient) and build a single pipeline like:
public List<Child> getAllParents() {
    var endpointParent = StringUtils.join(HOST, "/parent");
    var resultList = new ArrayList<Child>();

   Flux<Parent> parents = webClient.get().uri(endpointParent)
            .retrieve().bodyToMono(ResponseWrapper.class)
            .flatMapMany(wrapper -> Flux.fromIterable(wrapper.data));

    return parents.flatMap(parent -> {
      var endpointChild = StringUtils.join(HOST, "/child/", parent.getId());
      return webClient.get().uri(endpointChild).retrieve()
                .bodyToMono(new ParameterizedTypeReference<ResponseWrapper<Child>>() {
                }).flatMapMany(wrapper -> Flux.fromIterable(wrapper.getData()));
    }).collectList().block();
}

By default, the parents.flatMap operator will process elements with some concurrency (16 by default I believe). You can choose a different value by calling another variant of the Flux.flatMap operator with a chosen concurrency value.


text:
Q: Im trying to clear AsynStorage on logout Im developing an app using react native and im running into this issue with AsyncStorage. I store the user data on login, and then I get the data on the main page. I simply want to display the users name in a small welcome message, then if the user signs out, I need to clear the storage and then get the storage of the next user signing in on the device and display their name.
The issue is the first time I sign in the users name does not display, only when I sign out and back in does the name display. Not only this, but it seems it keeps the name of the last person signed in and diplays that name the next time a sign in occurs.
Any help would be greatly appreciated.
Here is the main code where I get and display the username

    AsyncStorage.getItem('user_data', (err, result) => {
        console.log(result);
        var userdata = JSON.parse(result);
        console.log(userdata);
        firstname = userdata.firstName;
        lastname = userdata.lastName;
    });

    const history = useHistory();
    const doLogout = event => {
        event.preventDefault();
        history.push('/');
        AsyncStorage.removeItem('user_data', (err, result) => {
            console.log(result);
        });
    };

    return (
        <View style={styles.container}>
            <Text>Welcome {firstname} </Text>
            <View style={{ marginTop: 10 }}>
                <TouchableOpacity
                    style={styles.loginbut}
                    activeOpacity={.5}
                    onPress={doLogout}
                >
                    <View style={{ flexDirection: 'row', alignSelf: 'center' }}>
                        <FontAwesomeIcon icon={faSignOutAlt} size={20} style={{ color: '#ffffff' }} />
                        <Text style={{ textAlign: 'center', fontWeight: 'bold', color: 'white' }}> Sign Out </Text>
                    </View>
                </TouchableOpacity>
            </View>
        </View>
     );

} export default MainUI```

A: Try this way
async removeItemValue(key) {
    try {
        await AsyncStorage.removeItem(key);
        return true;
    }
    catch(exception) {
        return false;
    }
}

A: I thought it's better to use redux or context to store user data during the process running if you want to clear it after logging out.
AsyncStorage is something like you want to store some data after user exit the process.
Like the logging email or some app setting.


text:
Q: React state object updates in console but not in browser? I am building a small React app that processes and then re-renders a few different state objects when a button is clicked. For two of them (stocks, accounts), they render fine using the setState function, but for the items in gameplayHandler(), they render to the console but not to the browser. They don't strictly need their own component, like the other two do.
I think I'm doing something quite obvious wrong - could anyone give me a tip on how to get all of the below rendering?
Thanks in advance.
import React, { Component } from 'react'
import './App.css'
import {stocks, accounts, gameplay} from './dummy_data/data'
import Stock from './Stock/Stock'
import Account from './Account/Account'

class App extends Component {
    state = {
        stocks: stocks,
        accounts: accounts,
        gameplay: gameplay
}

 sleep = () => {
    this.stockHandler()
    this.accountHandler()
    this.gameplayHandler()
}

gameplayHandler = () => {

    let netWorth = this.state.accounts.reduce(function(prevAcc,curAcc){
        return prevAcc + curAcc.balance
        },
    0)

     this.setState({
        gameplay: [
            {
                playerName: gameplay.playerName,
                gameDay: gameplay.gameDay += 1,
                netWorth: netWorth.toFixed(2)
            }
        ]
    })
}

accountHandler = () => {
    this.state.accounts.map(newAccount => {
        const interestPayment = parseFloat(((newAccount.balance / 100) * newAccount.interestRate).toFixed(2))
        newAccount.balance = Math.round((newAccount.balance + interestPayment) * 100) / 100
        })

    return this.setState({
        accounts: accounts
    })
}

stockHandler = () => {
     this.state.stocks.map(newStock => {
        newStock.currentPrice *=2
    })

    this.setState({
        stocks: stocks,
    })
}

render() {
    let accounts = null
    if (this.state.accounts) {
        accounts = (

                {this.state.accounts.map(account => {
                    return <Account key={account.key} name={account.name} balance={account.balance}/>
                })}

        )
    }

    let stocks = null
    if (this.state.stocks) {
        stocks = (

                {this.state.stocks.map(stock => {
                    return <Stock key={stock.key} name={stock.name} currentPrice={stock.currentPrice}/>
                })}

        )

        return (

                > Gameplay:

Player Name: {this.state.gameplay.playerName}, Game Day: {this.state.gameplay.gameDay}, Job Title: {this.state.gameplay.jobTitle}, Net Worth: £{this.state.gameplay.netWorth}

                > Stocks:
                { stocks }
                > Accounts:
                { accounts }
                <button onClick={this.sleep}>Go =></button>

        )
    }
}

}
export default App

A: It is weird because first of all you need to bind gameplayHandler function.So it should be like this:
constructor(props) {
    super(props);
    this.state = {
        stocks: stocks,
        accounts: accounts,
        gameplay: gameplay
    };
    this.gameplayHandler = this.gameplayHandler.bind(this);
  }

Otherwise, it should have give an error when you try setState and of course you should bind accountHandler and stockHandler functions. Can you tell me the issue is exist even if you bind these functions?


text:
Q: I ran fsck /dev/sda8 now Ubuntu doesn't work I have a laptop which has both linux Ubuntu and windows 10 partitions. I am not the one who installed it and I don't know the specifics. I consistently use both systems and never had a problem.
The other day I turned on ubuntu and there was a similar message as here fsck error on boot: /dev/sda6: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY so after reading some comments I ran fsck /dev/sda8
It ran ok, there were no other issues, but then when I booted again Ubuntu didn't work. At first it got stuck and didn't recognize any input from keyboard/trackpad etc, so I booted again and it seemed ok, however I can't do anything on it: I can only access some text files, and open R studio, but if I run codes or even type it gives errors, I can't open chrome and most other programs, and it seed my USB stick but tells me I can't open it because it's read-only.
Windows is running fine, I'm using it rn, but of course I can't access any linux data.
Does anyone have a clue about what might have happened? I am not tech savvy so I'm sorry if I'm missing important details, pls let me know if I should add something!
Edit to add: meanwhile, is there a way for me to access the files I have on ubuntu? For instance making a back up from recovery mode or accessing them from windows


text:
Q: How do I change the timezone/timestamp of this jquery plugin? I'm using this plugin called timeago found here: timeago.yarp.com
It works great, except that it operates in what appears to be a different timezone. I live in Eastern US (Philadelphia timezone) and when I put the exact time EST into the timeago plugin (say 2011-05-28, 13:47:18), it reprints as four hours later on my html page. When I write 2011-05-28, 17:47:18 (four hours later than my actual time from where I live), THEN it reprints as "less than a minute ago"
Here's the jquery plugin code:
        (function($) {
      $.timeago = function(timestamp) {
    if (timestamp instanceof Date) {
      return inWords(timestamp);
    } else if (typeof timestamp === "string") {
      return inWords($.timeago.parse(timestamp));
    } else {
      return inWords($.timeago.datetime(timestamp));
    }
    };
    var $t = $.timeago;

    $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: "added",
        prefixFromNow: "added",
        suffixAgo: "ago",
        suffixFromNow: "from now",
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years",
        numbers: []
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      function substitute(stringOrFunction, number) {
        var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
        var value = ($l.numbers && $l.numbers[number]) || number;
        return string.replace(/%d/i, value);
      }

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/\.\d\d\d+/,""); // remove milliseconds
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
      var iso8601 = isTime ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    }
    });
  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
   };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) {
        element.attr("title", text);
      }
    }
     return element.data("timeago");
   }

    function inWords(date) {
    return $t.inWords(distance(date));
    }

    function distance(date) {
      return (new Date().getTime() - date.getTime());
    }

    // fix for IE6 suckage
    document.createElement("abbr");
    document.createElement("time");
    }(jQuery));

I realize this problem is something very minor and can be easily fixed if I were to just remember the plugin works on a 4 hour delay, but I'd still like to know the answer if possible to provide.
Thanks!

A: Updated
I'm going to give this a shot but I must add the disclaimer that I'm a little fuzzy on this myself so I might be quite wrong!
The plugin expects the time in the ISO 8601 format which can also include offset information. I've now tried using the plugin and this is what I see (at 14:42 EDT, about 3 minutes from the test time string):

*

*When a trailing Z is used, indicating Zulu time or an offset of 0 from UTC, the plugin interprets it as UTC (obviously) and when printing the relative time string, it takes into consideration your actual timezone. This causes the extra 4 hours to be added (EST is UTC-5 (UTC-4 when following DST, like now)).
2011-05-28T14:39:33Z prints as about 4 hours ago

*When a trailing Z is not used, the plugin interprets the time specified according to your timezone and it seems to work just fine (as long as the timezone for the timestamp and the timezone you're viewing this timestamp in are the same). This is in line with what the Wikipedia article has to say:

If no UTC relation information is given with a time representation, the time is assumed to be in local time. While it may be safe to assume local time when communicating in the same time zone, it is ambiguous when used in communicating across different time zones. It is usually preferable to indicate a time zone (zone designator) using the standard's notation.

This would not be a recommended way since it's going to mess up the times when viewed from elsewhere since the timestamp will be interpreted as being the timestamp for that timezone which is incorrect.
2011-05-28T14:39:33 prints as 3 minutes ago

*When a trailing Z is specified along with the timezone offset (in the format of hh:mm, only hh seems to be ignored), it still seems to work just fine.
2011-05-28T14:39:33Z-04:00 prints as 3 minutes ago
You can see a working example here: http://jsfiddle.net/nogoodatcoding/SVgck/

You shouldn't be changing the timezone/offset of the plugin itself since that will cause visitors from other timezones to see incorrect values.

*

*One fix is to also specify the timezone offset in your date-time strings: 2011-05-28, 13:47:18Z-04:00 - in a sense, a more complete description of the time since it also includes the UTC offset information.

*Depending on how you're generating this page (if it's not just static HTML), the other option is to fix your server-side code so that the date-time string it outputs is in the UTC format - if not built in, you should be able to find a library that does the conversion from a timestamp in your local timezone into UTC. This is how sites I've seen do it - for example, the timestamps here on StackOverflow (or on Twitter and Facebook) are in UTC time - they are then formatted differently based on the user's timezone.

A: Hey, I use this plugin. It's not the javascript you have to edit. Look for the php file, in wordpress it's called 'wpTimeAgo.php' it should be something similar to that.
In that file look for this:
var $_gmtOffset = '';
Add a number there, I believe that should do the trick.

A: If you're using timeago in the .NET world, you'll find it's very fussy about the offset it gets. z and zz won't work, it needs to be zzz and should include the delimiting big "Z" and "T".
For example:
string.Format("{0}Z{1:%zzz}", DateTime.Now.ToString("s"), DateTime.Now);
This displays as:

2013-01-06T12:46:28Z-08:00


text:
Q: Need insight on this piece of Python I'm working on adapting this small piece of Python code to my own use (it's from the sendpkm DNS spoofing tool, used to redirect the original Pokémon DS games' DNS requests to ones own computer.)
def dnsspoof():
  s=socket.socket(); s.connect(("bash.org",80));
  me="".join(chr(int(x)) for x in s.getsockname()[0].split("."))
  print "Please set your DS's DNS server to",s.getsockname()[0]
  dnsserv=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  dnsserv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
  dnsserv.bind(("0.0.0.0",53))
  while True:
    r=dnsserv.recvfrom(512)
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('4.2.2.2', 53))
s.send(r[0])
rr=s.recv(512)
if "gamestats2" in rr: rr=rr[:-4]+me
dnsserv.sendto(rr, r[1])

serv=None
log=None

Would someone be so kind as to walk me through the sockets and explain how this is returning an IP for a DNS query? I'm just learning about Python.

A: Port 53 is the standard DNS port. But this code doesn't know anything about DNS beyond that number. All it does is listen on port 53, forward any requests to a server at 4.2.2.2, and return whatever that server returns.
In other words, it's a dumb byte proxy on port 53, which works because the remote server is a DNS server.
If you want to know how it works:
dnsserv=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dnsserv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
dnsserv.bind(("0.0.0.0",53))

This is standard code to create a socket to listen on a port. You're listening for UDP because that's what INET/DGRAM means. The setsockopt means that if you quit and restart the server it will be able to grab the same port again. And the bind says to listen on all IPv4 addresses on port 53.
The loop reads packets of up to 512 bytes, connects to the remote server and sends the same packets, reads the response from the server, and sends it back to the client. Because recvfrom returns a tuple of (data, address), you send r[0] to the server, and send the response to r[1]. (This part would be a lot more readable with tuple unpacking: data, address = recvfrom(...). Then you could use names instead of r[0].)


text:
Q: Is FileReader.ReadAsync truly async? So recently I was reading Richter's book CLR via C#. It is about .NET Framework 4.5 or something, and there he states that FileReader.ReadAsync is not truly asynchronous, it is actually just an async wrapper over synchronous win32 API. I am not a .NET Framework developer, I use .NET Core. So I have a few questions:

*

*How bad for app scaling is the fact that it wraps sync functions with something like Task.Run ?

*Is the behavior described above fixed in .NET Core? If I say FileReader.ReadAsync, will it read asynchronously?

*What's the point of having that FileOptions.Asynchronous if you can determine whether I want operations to be sync or async based on methods I call e.g Read or ReadAsync?

*Why not use WinRT for async reading/opening if WinRT provides that and win32 doesnt?

A: FileStream.ReadAsync always asynchronously reads from file from application level view (in sense call not blocked at this point and just return control to user code).
but are this is truly or emulated asynchronous I/O - depend from FileOptions.Asynchronous option: from Using Async for File Access (C#)

this option causes asynchronous I/O to occur at the operating system
  level. By using this option, you can avoid blocking a ThreadPool
  thread in many cases

this is answer for

What's the point of having that FileOptions.Asynchronous

and from book

When you create a FileStream object, you get to specify whether you
  want to communicate using synchronous or asynchronous operations via
  the FileOptions.Asynchronous flag (which is equivalent to calling the
  Win32 CreateFile function and passing into it the FILE_FLAG_OVERLAPPED
  flag). If you do not specify this flag, Windows performs all
  operations against the file synchronously. Of course, you can still
  call FileStream's ReadAsync method, and to your application, it looks
  as if the operation is being performed asynchronously, but internally,
  the FileStream class uses another thread to emulate asynchronous
  behavior; use of this thread is wasteful and hurts performance. On the
  other hand, you can create a FileStream object by specifying the
  FileOptions.Asynchronous flag. Then you can call FileStream's Read
  method to perform a synchronous operation. Internally, the FileStream
  class emulates this behavior by starting an asynchronous operation and
  then immediately puts the calling thread to sleep until the operation
  is complete. This is also inefficient, but it is not as inefficient as
  calling ReadAsync by using a FileStream constructed without the
  FileOptions.Asynchronous flag

so here stated that FileStream class uses another thread to emulate asynchronous behavior only in case you not specify FileOptions.Asynchronous flag .

Why not use WinRT for async reading/opening if WinRT provides that and
  win32 doesnt?

winRT internal anyway call win32 (or native) api.


text: Q: how do I make a scrollable List of entry widgets in gtksharp? I'm trying to make a scrollable list of entry widgets, because I have an unknown number of entry widgets, and don't want them to go off the window, I've tried a few things, like a ScrolledWindow, which I think can only contain one object, so I tried using a Vbox container, which just resulted in a black box with the entry widgets in, but it just packed the entry widgets closer together as I added more instead of keeping them spaced apart but letting me scroll through them, I tried a TreeView, which just resulted in a blank box with none of the widgets showing, and I made a scrollbar, but I have no idea how I even make the scrollbar do anything, does anyone know how I can make it work?


text:
Q: Why is the empirical cumulative distribution of 1:1000 a straight line? Why does plot(ecdf(1:1000)) produce a straight line?

Since Fn($x_n$) = $x_1$/(total sum) +$x_2$/(total sum) +...+$x_n$/total sum = ($x_1+x_2+x_3+...+x_n$)/total sum.
the fact that Fn(200) roughly being equal to 0.2 and sum(0:200) roughly being equal to 0.4 seems to indicate that sum(1:200) is roughly half of sum(1:400), which isn't true, the two expressions being 20,000 and 80,000 respectively.
What am i misunderstanding?

A: Empirical cumulative distribution function is a cumulative sum of frequencies of observed $x_i$'s divided by total sample size. Your data is a vector of values from $1$ to $1000$, where each of the values appears exactly once. This means that your "variable" follows a discrete uniform distribution, that has a flat CDF.
As you can see on the example below, it'd be different if you used other imput data.
set.seed(123)

x <- sample(0:1000, 1e5, replace = TRUE)
y <- rnorm(1e5)

def <- par(mfrow = c(1,2))
plot(ecdf(x))
plot(ecdf(y))
par(def)

or
z <- c(1,2,5,7,12,14,19,25,100,250,300,301,500,800,900,901,1000)
plot(ecdf(z))

Notice that in the second example distances between different values are different so no matter that each value appeared only once, the line is curved.

A: You can think about it mechanically, too.
The ECDF $\hat F$ evaluated at $x$ is the proportion of observations with value $x$ or below. Since you have exactly 1,000 observations $\{y_i\}_{i=i}^{1000}$, the difference between $\hat F(y_i)$ and $\hat F(y_{i+1})$ is always 0.001 for any $1 \le i < 1000$.
Moreover, your sample values are evenly spaced, so the difference between $y_i$ and $y_{i+1}$ is always 1. Therefore, for any $1 \le i < 1000$, the slope between $\left(y_i, \hat F(y_i)\right)$ and $\left(y_{i+1}, \hat F(y_{i+1})\right)$ is always $\frac{0.001}{1}$. A curve with a constant slope is just a straight line.
As for what you're misunderstanding, the $Fn$ you defined is definitely not the right formula. The denominator should be the number of observations, and the numerator should be the number of observations with value at or below $x_n$.

A: The empirical distribution function of a sample $Y_1, ..., Y_n$ is defined as
$$ \widehat{F}(x) = \frac{1}{n} \sum_{i=1}^{n} \mathcal{I} \{ Y_i \leq x \} $$
In your data set, $Y_i = i$. So, $ \widehat{F}(x) = x/n$, for $x = 1, 2, ..., 1000$. Plotted the way you did, this looks like a linear function of $x$.

A: The cumulative distribution function of a random variable $X$ has nothing to do with summing the random variable. It is

the probability that $X$ will take a value less than or equal to $x$.

And of course, the probability that a value randomly sampled from your vector $(1, \dots, 1000)$ is less than or equal to 200 is exactly half the probability that it is less than or equal to 400.


text:
Q: Is casting a function [X, Y] X => Y to X => () safe as long as I ignore the returned value? val f = { x :Int => x }
val g = f.asInstanceOf[Int, Unit]
g(1) //works

How brittle is the above code? It works currently, but of course it is not a part of language specification. For this reason, it is of course possible, that one day it will not; my question is how likely it would be, understood in the sense of sensible alternatives for the compiler. I do not know bytecode well, but I could easily imaging it breaking by trying to put an Int into a Unit register. On the other hand, this working can actually be an undocumented consequence of documented specification
of the Scala compiler and Java bytecode itself.
My motivation lies primarly in @specialized code. For example, Iterable contains the following method:
trait Iterable[E] /* ... */
    def foreach[T](f :E => T) :Unit

This signature was probably chosen to allow passing any function of E one might have as an argument.
In practice though, it will almost always be a lambda/method value. The problem with the above method
is that it would require specializing on both E and T, leading to a square number of method variants, which should be avoided. Not specializing on T is pointless, because scalac doesn't emit @specialized subclasses for subsets of type parameters: if any of the @specialized parameters receive a reference (or a non-specialized) type as the argument, the whole object will be an instance of the erased superclass. Similarly, there is no apply(Int):Object method - if the return type is erased, then the erased apply(Object):Object will be called, resulting in boxing. So, it would be much more desirable in this case to have
def foreach(f :E => Unit) :Unit

Introducing such a method (with a different name) and using it as the delegate target of the regular foreach is possible and doesn't result in any boxing, at least as long as the created lambda doesn't have a reference type as its return type.

A: Depends on the context.
Most of the time Scala will compile code so that function returning Unit will be called as JVM's void (no returned result) or it will treat it as returning scala.Unit's only value which can be discarded. As long as JVM won't try to call anything on this returned value it will only assume that it is some java.lang.Object that should be checked for scala.Unit if used for anything, which could never happen.
But it doesn't mean it's impossible.
val f: Int => Int = _ * 2
val g: Unit => Int = _ => 10
(f.asInstanceOf[Int => Unit] andThen g)(10)
java.lang.ClassCastException: class java.lang.Integer cannot be cast to class scala.runtime.BoxedUnit (java.lang.Integer is in module java.base of loader 'bootstrap'; scala.runtime.BoxedUnit is in unnamed module of loader 'app')
  scala.Function1.$anonfun$andThen$1(Function1.scala:85)
  scala.Function1.apply$mcII$sp(Function1.scala:69)
  ammonite.$sess.cmd27$.<clinit>(cmd27.sc:1)

As long as you call it in your own code, that you have full control, always know the context, test, etc it should be fine.
Which IMHO is a bad assumption for basically every library in the world or any codebase that would be maintained more than one week.
f.andThen(_ => ())

would always be safer and I would have to have some really good reasons to use optimization like .asInstanceOf and risk some funny errors in the future.

A: asInstanceOf is an inherently unsafe universal escape hatch. When you use it, you're really telling the type checker to blindly trust you.
In general, when you write x.asInstanceOf[Y], you're making a promise to the compiler that the value x is really of type Y.
This is only ever guaranteed to work if x really is of type Y. If not, the compiler will do some special handling if x is known statically to be a primitive type, or null. Then one of two things will happen:

*

*Runtime will see through your lies and throw a ClassCastException.

*You get away with your lies and possibly other things break down the line.

In your example, f is of type Int => Int, which is clearly not a subtype of Int => Unit. In other words: you're lying to the compiler, and all guarantees are void.
The moral of this story is: You should never rely on implementation details for correctness, and you should always treat asInstanceOf as unsafe.
As Mateusz wrote, f.andThen(_ => ()) or equivalently { x => {f(x); ()}} is the only correct way to convert some A => B to A => Unit.
You should also note that while it is possible to generate specialized methods that take specialized functions as arguments, (x => x).asInstanceOf[Int => Unit] will always return an unspecialized Function1[Int,Unit], not a specialized type, so this won't help you at all with performance.


text:
Q: Protected Question does not show Add an Answer button This question is protected. To answer it, I must have at least 10 reputation.

Word meaning "to walk clumsily among many obstacles"?

Ignoring the association bonus of 100, I should at least have 73.
Yet, the Android app does not show the blue "Add an Answer" button at the bottom. The app also does not show the protection status.
If I view the question in the desktop or mobile browser (and I'm signed in), I can add an answer there.

A: We used to have a really complex and super annoying way of checking user permissions for most things (e.g. checking for mod-ship, reputation, etc all on the client side) -- Since then, our API has gotten a can_answer attribute on questions (which we're already using on iOS).
As of any version greater than 1.0.81, we now use this field rather than doing the check for if you can answer on the client side. This means you will now see an "Add Answer" button on posts that are protected. You should see version 1.0.82 hitting the beta tier later today or tomorrow.