text:
Q: expression for$\sum_{k=0}^{n}(k+1)(k+2)$ what is a closed expression for$\sum_{k=0}^{n}(k+1)(k+2)$? the answer says to look at Generating function $a_k=(k+1)(k+2)$ and derive twice $\dfrac{1}{x}=1+x+x^2+...$ so the solution starts: $\sum_{k=0}^{n}(k+1)(k+2)=[\dfrac{1}{(1-x)}.\dfrac{2}{(1-x)^3}]$but isn't $\sum_{k=0}^{\infty}t^k=\dfrac{1}{(1-t)}$? so how the lhs and rhs in  $\sum_{k=0}^{n}(k+1)(k+2)=[\dfrac{1}{(1-x)}.\dfrac{2}{(1-x)^3}]$ are equal?

A: Hint. You may want to write
$$ \sum_{n=0}^{\infty} \left( \sum_{k=0}^{n} (k+1)(k+2) \right) x^{n} = \frac{2}{(1-x)^{4}}. $$

Here is another solution using the Pascal's triangle:
$$ \sum_{k=0}^{n} (k+1)(k+2) = 2 \sum_{k=0}^{n} \binom{k+2}{2} = 2 \left[ \binom{2}{2} + \cdots + \binom{n+2}{2} \right]. $$
Now we know that $\binom{2}{2} = 1 = \binom{3}{3}$. So by applying the property $\binom{m}{k-1} + \binom{m}{k} = \binom{m+1}{k}$ repeatedly, we observe
\begin{align*}
\binom{2}{2} + \cdots + \binom{n+2}{2}
&= \binom{3}{3} + \binom{3}{2} + \binom{4}{2} + \cdots + \binom{n+2}{2} \\
&= \binom{4}{3} + \binom{4}{2} + \cdots + \binom{n+2}{2} \\
&= \binom{5}{3} + \cdots + \binom{n+2}{2} \\
&\quad \quad \vdots \\
&= \binom{n+2}{3} + \binom{n+2}{2} \\
&= \binom{n+3}{3}.
\end{align*}
So we obtain a special case of Christmas Stocking Theorem:
$$ \sum_{k=0}^{n} (k+1)(k+2) = 2 \sum_{k=0}^{n} \binom{k+2}{2} = 2 \binom{n+3}{3} = \frac{(n+3)(n+2)(n+1)}{3}. $$

A: Isn't it like this:
$$ \sum_{k=0}^n (k+1)(k+2) = \sum_{k=1}^n k(k+1) = \sum_{k=1}^n k^2+k = \sum_{k=1}^n k^2 + \sum_{k=1}^n k = \sum_{k=1}^n k^2 + \frac{n(n+1)}{2} $$

A: Using the generalization proven in this answer, and the substitutions
$$
\begin{align}
M&\mapsto n\\
m&\mapsto k\\
k&\mapsto 2\\
n&\mapsto 0
\end{align}
$$
we get
$$
\begin{align}
\sum_{k=0}^n(k+1)(k+2)
&=2\sum_{k=0}^n\binom{k+2}{2}\binom{n-k}{0}\\
&=2\binom{n+3}{3}
\end{align}
$$

An Alternate Approach
The recursive definition of the Pascal Triangle says that
$$
\binom{k+2}{2}=\binom{k+3}{3}-\binom{k+2}{3}
$$
Therefore,
$$
\begin{align}
\sum_{k=0}^n(k+1)(k+2)
&=\sum_{k=0}^n2\binom{k+2}{2}\\
&=2\left[\sum_{k=0}^n\binom{k+3}{3}-\sum_{k=0}^n\binom{k+2}{3}\right]\\
&=2\left[\sum_{k=0}^n\binom{k+3}{3}-\sum_{k=-1}^{n-1}\binom{k+3}{3}\right]\\
&=2\left[\binom{n+3}{3}-\binom{2}{3}\right]\\
&=2\binom{n+3}{3}
\end{align}
$$

A: $$ \sum_{k=0}^n (k+1)(k+2) = \sum_{k=1}^n k(k+1) = \sum_{k=1}^n k^2+k=$$
$$=\sum_{k=1}^n k^2+\sum_{k=1}^n k = \frac{n(n+1)(2n+1)}{6} + \frac{n(n+1)}{2}=$$
$$=\frac{n(n+1)}{2}\left(\frac{2n+1}{3}+1\right)=\frac{n(n+1)}{2}\frac{2n+4}{3}=\frac{n(n+1)(n+2)}{3}$$

A: By induction it can easily be shown that: $$\sum_{k=r}^{n}\binom{k}{r}=\binom{n+1}{r+1}$$ This for $r=0,1,2,\dots$
For $r=2$ this results in: $$\frac{1}{2}\sum_{k=2}^{n}\left(k-1\right)k=\frac{1}{6}\left(n-1\right)n\left(n+1\right)$$
or equivalently: $$\sum_{k=0}^{n}\left(k+1\right)\left(k+2\right)=\frac{1}{3}\left(n+1\right)\left(n+2\right)\left(n+3\right)$$


text:
Q: How to set displayName in class based component? I'm trying to set the displayName property of this class that extends React.Component. The React docs say that displayName is a property, so it possible to set it in the constructor? Here's what I'm trying:
class TestUI extends React.Component {
   constructor(){
     this.displayName = 'CustomTestUI'
   }
}

But the library I'm using (pacomo) isn't picking it up. Am I setting it incorrectly? I've also tried setting it outside the class like stateless components MyClass.displayName = 'Test' which also doesn't have an effect.
Edit: The answer is: static displayName = 'CustomTestUI'

A: As stated in the comments, displayName should be set on the class as a static variable and not an instance using this.
class TestUI extends React.Component {
   static displayName = 'CustomTestUI';
   ...
}

Here are a couple of examples of where React retrieves displayName from the component class in this error and this function.
You can also set the displayName of a component via Component.displayName = 'myName'.
class TestUI extends React.Component {
    ...
}

TestUI.displayName = 'CustomTestUI';

A: The comments and answers given should suffice, however I thought it a good opportunity to describe why your initial attempt did not work (and why it would have been a bad idea anyways).
When working with classes, you have the class "constructor" which is used to create many class "instances". Inside your class methods, all references to this refer to the class instance. You can always access the constructor by doing this.constructor.
So the following would have worked, though it is very bad practice for an instance to change a property on its constructor - DO NOT DO THIS:
class TestUI extends React.Component {
   constructor(){
     // DO NOT DO THIS (for educational purposes only - see other answers)
     this.constructor.displayName = 'CustomTestUI'
   }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best practice to link modules split into multiple files with gcc/g++ I would like to have a file containing only the declarations  in a module and one or more files containing the definitions.
According to How to split a module into multiple files (and this awseome cppcon talk: https://youtu.be/nP8QcvPpGeM at 12:04) I should split my files like this:
Log.cpp:
export module Log;

int i = 0;
export void Log();

Log_imp.cpp:
module Log;

void Log() {
    std::cerr << "This is a log and i=" << i << "\n";
}

I can build both with g++-11 -std=c++20 -fmodules-ts -c Log.cpp and
g++-11 -std=c++20 -fmodules-ts -c Log_imp.cpp respectively.
My main simply imports the Log module and calls the Log() function.
Note that I have to link with both Log.o and Log_imp.o, otherwise I get linking errors.
Is it possible to have a single object file for a single module, without building a static library? If not, then should I link modules into a static library, or keep multiple .o files?

A: Modules are basically orthogonal to the linking process. Each module file is its own translation unit and therefore will produce its own object file. You can combine them into a library (or a single object file), but otherwise, you're going to have to link to all such object file.


text:
Q: If $z=\cos\theta+i\sin\theta$, where $\theta$ is real, show that $\frac{1}{1-z}= \frac{1}{2}\left(1 + i\cot(\theta/2)\right)$
Question.(source) If $z=\cos\theta+i\sin\theta$, where $\theta$ is real, show that
$$\frac{1}{1-z}= \frac{1}{2}\left( 1+ i\cot\frac{\theta}{2}\right)$$

I have been trying to rearrange the right-hand-side in order to make it look like the required form, but have been struggling to do so and want to see if anyone is able to show me what steps need to be taken to solve this question.

A: Hint:
Rewrite the expression, using the exponential notation:
\begin{align}
\frac{1}{1-z}&= \frac{1}{1-\mathrm e^{i\theta}}= \frac{1-\mathrm e^{-i\theta}}{(1-\mathrm e^{i\theta})(1-\mathrm e^{-i\theta})}\\
&= \frac{1-\mathrm e^{-i\theta}}{(2-\mathrm e^{i\theta}-\mathrm e^{-i\theta})}
== \frac{1-\mathrm e^{-i\theta}}{2(1-\cos\theta)}\\
&=\frac{1-\cos\theta}{2(1-\cos\theta)}+i\,\frac{\sin\theta}{2(1-\cos\theta)}
\end{align}
continue with the duplication formulæ.

A: Here is a fun trick I learned when I saw this question for the first time.
$$\frac{1}{1-e^{i\theta}} = \frac{e^{-i\theta/2}}{e^{-i\theta/2} - e^{i\theta/2}} = \frac{\cos\tfrac12\theta - \sin\tfrac12\theta}{-2i\sin\tfrac12\theta} = \ldots$$

A: Note that $e^{i\theta}=\cos\theta+i\sin\theta$.
$$\frac{1}{1-e^{i\theta}}$$
$$=\frac{1}{2}\times \frac{-2}{e^{i\theta}-1}$$
$$=\frac{1}{2}\times \frac{e^{i\theta}-1-(e^{i\theta}+1)}{e^{i\theta}-1}$$
$$=\frac{1}{2}\times \left(1-\frac{e^{i\theta}+1}{e^{i\theta}-1}\right)$$
Note that $e^{i\theta}+1=e^{\frac{i\theta}{2}}\cdot 2\cos(\frac{\theta}{2})$ and $e^{i\theta}-1=e^{\frac{i\theta}{2}}\cdot 2i\sin (\frac{\theta}{2})$.
Plug in these results above,
$$\frac{1}{1-e^{i\theta}}=\frac{1}{2}\times \left(1-\frac{\cot(\frac{\theta}{2})}{i}\right)$$
$$=\frac{1}{2}\times \left(1-\frac{i\cot(\frac{\theta}{2})}{i^2}\right)$$
$$\fbox{$\huge{\dfrac{1}{1-e^{i\theta}}=\frac{1}{2}\times \left(1+i\cot\left(\frac{\theta}{2}\right)\right)}$}$$
I used some results above. See how I got it below.
$$e^{i\theta}+1=\cos \theta+i\sin \theta+1$$
$$=2\cos^2 \frac{\theta}{2}-1+2i\sin\frac{\theta}{2} \times \cos\frac{\theta}{2}+1$$
$$=2\cos\frac{\theta}{2}\cdot e^{\frac{i\theta}{2}}$$
The other result:
$$e^{i\theta}-1=\cos \theta+i\sin \theta-1$$
$$=1-2\sin^2 \frac{\theta}{2}+2i\cos\frac{\theta}{2}\cdot \sin\frac{\theta}{2}-1$$
$$=2i\sin\frac{\theta}{2}\left(\frac{-\sin\frac{\theta}{2}}{i}+\cos\frac{\theta}{2}\right)$$
$$=2i\sin\frac{\theta}{2}\cdot e^{\frac{i\theta}{2}}$$


text:
Q: Finding a custom object in a set and then returning that object public Table findTable(Container container, String name) {
        Iterator<Table> tableFinder = container.getTables().iterator();

        while(tableFinder.hasNext()){
            if (tableFinder.equals(name)){
                return table;
            } else {
                return null;
            }
        }
    }

So basically this method is supposed to search for a table within the object containerby checking one of its properties tableswhich is a set. It is supposed to find the object through the property name which belongs to Table. Normally, I would just insert a parameter of type table, it'd be easier to find it that way, but the wireframe I was given specifically states that it has to be this way.
I've got hashcode() and equals() as methods for table, I know I need to use them somehow, however I'm not really sure how to do this. The other problem is that I need to return a table and I'm not sure how to do that without an instance of Table so I know that return table is going to give an error. Basically, what I need to know is how to search with name and how to get the table out of the set in order to have a valid return.

A: this required jdk 1.5+:
public Table findTable(Container container, String name) {
    for (Table table : container.getTables()) {
        if (table.getName().equals(name)) {// assume you have a getName() method on Table to get table name
            return table;
        }
    }
    return null;
}

A: You're currently comparing the iterator object against the String "name" every time. You should be doing something like this:
if (name.equals(tableFinder.next().getName())

A: With
if (tableFinder.equals(name)){

you are calling equals of the iterator object, this is not what you really want. Instead you want to compare with the Table the iterator is pointing at in each loop. To get that object you need to call the method Iterator#next() on the iterator object.
Table table = tableFinder.next();
if (table.equals(name)){ // assuming that your equals implementation
                         // compares with the property name of table


text:
Q: Why does the divisor-counting function appear in bounds for Kloosterman sums? Given integers $m,n$ and $c \geq 2$, the Kloosterman sum is defined as $S(m,n;c) = \sum_{k \in (\mathbb{Z}/c\mathbb{Z})^{\times}}{e^{\frac{2i\pi}{c}(mk+nk^{-1})}}$, where $k^{-1}$ is the reciprocal of $k$ mod $c$.
The following properties are easy to compute (and some are listed on the Wikipedia page):
1) If $q$ is a power of the prime $p$, $pS(m,n;q)=S(pm,pn;pq)$.
2) If $ua+vb=1$ with $c=ab$, $S(m,n;c)=S(vm,vn;a)S(um,un;b)$.
Now, we have from e.g. Iwaniec & Kowalski, Analytic Number Theory (Cor. 11.12), $|S(m,n;c)|\leq \tau(c)(m,n,c)^{1/2}c^{1/2}$ where $(m,n,c)$ is the gcd of $m,n,c$ and $\tau$ is the divisor-counting function.
The proof is as follows:
1) If $p$ is prime, $m$ and $n$ are coprime with $p$, $|S(m,n;p)| \leq 2\sqrt{p}$ (the most involved part of the proof, by Weil).
2) If $p$ is an odd prime power, Salie identities (from Wikipedia, or Chapter 12 of the same book) yield, for integers $m,n$ coprime to $p$, $|S(m,n;p)| \leq 2\sqrt{p}$ as well.
3) We combine 1) and 2) with the multiplicativity properties above to show the result in the general case.
My question is the following: here, we see a contribution of $2$ for each odd prime factor of $c$. So why, in the final bound, is there a divisor-counting function appearing? The logical explanation is that $S(m,n;2^l)$ gives a bound along the lines of $(l+1)2^{l/2}$, but is that the only reason why we use the divisor function instead of some more ad hoc arithmetic function in the bound?
Additionally, that case $c=2^l$ does not seem specifically explained in the book, and the argument does not seem to involve the exponent, so that the same bound as for odd prime powers seems to hold. So what happens for powers of $2$? Does anyone know of a reference where this is addressed?
TL;DR: Why does one use the divisor-counting function in the bounds for Kloosterman sums, instead of, say, $\tau'(n)=(1+v_2(n))\prod_{p|n,p\text{ odd}}{2}$ which should work by multipicativity and Selie identities? Would the even smaller $\tau''(n)=\prod_{p|n}{2}$ work?


text:
Q: maximum value of $c$
If the circles $x^2+y^2+(3+\sin \beta)x+(2\cos \alpha)y=0$ and $x^2+y^2+(2\cos \beta)x+2cy=0$ touches each other. Then maximum value of $c$ is

Center $\displaystyle C_{1}:\bigg(\frac{-3-\sin \beta}{2},\frac{-2\cos \alpha}{2}\bigg)$ and $\displaystyle r_{1}=\sqrt{\frac{(3+\sin \beta)^2+4\cos^2 \alpha}{4}}$
Center $\displaystyle C_{2}:\bigg(\frac{-2\cos \beta}{2},-\frac{2c}{2}\bigg)$ and $\displaystyle r_{2}=\sqrt{\frac{4\cos^2 \beta+4c^2}{4}}$
if circle touches each other, then distance between center of $2$ circle is sum of radius of circle
$$C_{1}C_{2}=r_{1}+r_{2}$$
$$\sqrt{(3+\sin \beta-2\cos \beta)^2+(2\cos \alpha -2c)^2}=\sqrt{(3+\sin \beta)^2+4\cos^2 \alpha}+\sqrt{4\cos^2 \beta+4c^2}$$
How do i solve it Help me please

A: Observe that both circles pass through $(0,0)$, no matter what $\alpha, \beta, c$ are.
So their centers and $(0, 0)$ are on the same line, this implies
$$
\frac{2c}{2\cos\alpha}=\frac{2\cos\beta}{3+\sin\beta},
$$
that is, $c=\frac{2\cos\beta\cos\alpha}{3+\sin\beta}$; at maximum it must be  $\cos\alpha=1$ (actually at $\cos\alpha=-1$ there is another maximum but it gives the same value and we can ignore it), and, by a quick calculation using derivative in $\beta$ we see it must be $\sin\beta=-\frac 13$ and $\cos\beta=\frac{\sqrt 8}{3}$ at maximum. So maximum of $c$ is $\frac {\sqrt 2}{2}$.


text:
Q: Confusion with understanding lambda and receivers Kotlin version 1.2.50
I have been following some examples on this tutorial on youtube https://www.youtube.com/watch?v=gPH9XnvpoXE. And there are a few things that I have understood, but there is still some confusion. I have left the comments in the code below where I am not sure what is happening.
fun main(args: Array<String>) {

    val javaClient = createClient {
        firstName = "joe"
        lastName = "bloggs"

        twitter {
            handle = "@joebloggs"
        }
    }

    println(javaClient.toConsole)
}

/* Are we passing in a lambda and receiver. What will the receiver be */
private fun JavaClientBuilder.twitter(suppler: JavaTwitterBuilder.() -> Unit) {
    /* We call JavaTwitterBuilder().apply(..) Will apply return the newly created object? Not sure why we have to pass the suppler in the apply */
    twitter = JavaTwitterBuilder().apply(suppler).build()
}

/* Are we passing in a lambda and receiver that return nothing */
private fun createClient(suppler: JavaClientBuilder.() -> Unit): JavaClient {
    val javaClientBuilder = JavaClientBuilder()

    /* confusion: Not sure about this, as we are calling suppler. Just wondering is the suppler the the JavaClientBuilder that was called in the above javaClient {} lambda */
    javaClientBuilder.suppler()

    return javaClientBuilder.build()
}

/* I understand this, an extension function that formats and returns the string from the JavaClient object it was called on */
private val JavaClient.toConsole: String
    get() =
        "Created client is: ${twitter.handle} ${company.name}"

A:
/* Are we passing in a lambda and receiver. What will the receiver be */
private fun JavaClientBuilder.twitter(suppler: JavaTwitterBuilder.() -> Unit)

We've indeed got a receiver in this function, and it's the instance of JavaClientBuilder that this function will be invoked on.

/* We call JavaTwitterBuilder().apply(..) Will apply return the newly created object? Not sure why we have to pass the suppler in the apply */
twitter = JavaTwitterBuilder().apply(suppler).build()

To understand how apply() works, take a look at its source code (simplified version):
public inline fun <T> T.apply(block: T.() -> Unit): T {
    block()
    return this
}

It's an extension function declared on a receiver of type T and returning an instance of T, which takes in a block - another extension function with receiver of type T returning Unit. It's usually used to replace the Builder pattern - apply custom initialization logic to an object. In your case, suppler is a block that contains initialization logic for an instance of JavaTwitterBuilder. The function code creates the instance and uses apply() with the logic in suppler to initialize that instance.

/* Are we passing in a lambda and receiver that return nothing */
private fun createClient(suppler: JavaClientBuilder.() -> Unit): JavaClient

In this case, createClient() doesn't have a receiver, it's a top-level function.

/* confusion: Not sure about this, as we are calling suppler. Just wondering is the suppler the the JavaClientBuilder that was called in the above javaClient {} lambda */
javaClientBuilder.suppler()

suppler is a lambda with JavaClientBuilder being the receiver type, which allows us to call it on the newly-created instance of JavaClientBuilder.

/* I understand this, an extension function that formats and returns the string from the JavaClient object it was called on */
private val JavaClient.toConsole: String
      get() =
          "Created client is: ${twitter.handle} ${company.name}"

Right! Just a small correction, it's an extension property. Properties can have custom getters and setters. This property defines a custom getter, so indeed whenever this property is accessed it will produce a String with the format described by the getter code.

A: Hope the following example helps understand lambda with receiver type:
data class Person(val name: String)

fun getPrefixSafely(
    prefixLength: Int,
    person: Person?,
    getPrefix: Person.(Int) -> String): String
{
    if (person?.name?.length ?: 0 < prefixLength) return ""
    return person?.getPrefix(prefixLength).orEmpty()
}

// Here is how getPrefixSafely can be called
getPrefixSafely(
    prefixLength = 2,
    person = Person("name"),
    getPrefix = { x -> this.name.take(x) }
)

PS: These functional literals with receiver types are similar to extension functions IMO.


text:
Q: Counting number of digits in a double C++ I'm using a while loop to count the number of digits in my input.
So my input was 1.525
length = 0;
num = num - int(num);
while ( num >= .0001 ) {
    num = num * 10;
    length = length + 1;
    num = num - int(num); }

When i do
cout << "\n\nLength: " << length << "\n";

The answer I get is 51 and other numbers give me an asnwear of 49 or something that is obviously wrong.
Is it the way c++ works or is it just my mistake. Thank you.

A: double and float can't always hold precisely the values you try to store in them, thats not how they work. In many cases they will store an approximate value, that usually can be rounded up to what you meant to store there in the first place, but not exactly. Thats why you are getting those results.

A: You can use string or char array to store the the number inputed.  it can precisely count the length. float double store a  approximate value, you can reference here.

A: Floating point numbers cannot store the decimal 1.525 precisely but if you use round instead of int cast and use fabs when comparing against the tolerance to protect against negative numbers you will get something you might be happy with:
num -= round(num);
while(fabs(num) >= .0001) {
  num *= 10;
  ++length;
  num -= round(num);
}

If you are happy to accept that 1.9999999 has the same number of digits as 2.0.
Generally, trying to find the number of digits in a floating point number is going to be a bit meaningless because it is not stored as decimal digits.


text:
Q: How to pass an input from a UITextField to a UILabel in different controllers? Basically I have a table view cell that is set up with two UILabels, one on left and one on the right. The first one on the left is titled Bus Name and will remain static.  The one on the right will change based on the what the user inputs on the textfield in another view controller.  I have a modal segue set up such that when a user clicks on the cell, they are directed to the view controller with a textfield.  The text within that field should then be updated on the UILabel on the previous table view cell when the user taps Done in the navigation. What is the best way to go about this? Thanks in advance.

A: In your prepareForSegue method, store a weak reference to the sender (which will be your UITableViewCell) on your modal view controller.  Assuming you have the UILabel exposed on your UITableViewCell you'll be able to set it directly.  For example:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    UITableViewCell *cell = (UITableViewCell *) sender;
    UIViewController* controller = segue.destinationViewController;
    controller.callingCell = cell;
}

Assuming on your modal view you have the following property:
@property(nonatomic, weak) UITableViewCell* callingCell;

You can then say:
self.callingCell.desiredTextField.text = @"Text";

Instead of keeping a reference to the UITableViewCell itself, you could also create a protocol that only exposes the ability to set the text field you desire. Then your UITableViewCell would conform to that.  For example:
@protocol SettableLabel <NSObject>

-(void) setText:(NSString*) text;

@end

Then your UITableViewCell would conform to that protocol and have the method implemented:
-(void) setText:(NSString*) text {
    self.desiredTextField.text = text;
}

Then on your modal view you'd have the property:
@property(nonatomic, weak) id<SettableLabel>* callingCell;

and would just call setText when you need to. This may be a better design but I leave that decision to you.

A: Well you have few options but the most simple, common way is to use delegation.
In the controller with the text field you should declare a Delegate Protocol.
@protocol YourTextFieldViewControllerDelegate <NSObject>
- (void)userDidFinishEditingWithText:(NSString *)text;
@end

@interface YourTextFieldViewController : NSObject

@property (nonatomic,weak) id < YourTextFieldViewControllerDelegate> delegate;

@end

Then when the user taps done or any other trigger that you want to set, in your YourTextFieldViewController call -
[self.delegate userDidFinishEditingWithText:yourTextField.text];

Now what you basically did is to create a way for you YourTextFieldViewController to announce the "world" that your text field text is done editing.  When your YourTextFieldViewController calls the delegate method it "shouts" - "Hey, if there is any one interested in this text, here is it".
But for it to work someone needs to say, "Hey, I want to get this message when from the YourTextFieldViewController. For that your TableviewController will say to the YourTextFieldViewController - "I want to be your delegate, and get your messages". (This is different from Notifications where any one can get them even if it does not know the sender, In the delegate pattern, you must "Know" the sender).
So to do that your TableviewController register itself as the delegate of the YourTextFieldViewController -
In the header file you need to declare that you are implementing the YourTextFieldViewControllerDelegate delegate:
@interface YourTableViewController : UIViewController<YourTextFieldViewControllerDelegate >

@end

Then you need to tell YourTextFieldViewController that you want to be it's delegate:
YourTextFieldViewController *controller =  [[YourTextFieldViewController alloc] init];
controller.delegate = self;

And lastly, implement the delegate method -
 - (void)userDidFinishEditingWithText:(NSString *)text
 {
       //here you should update your table view dataSource array
 }

BTW you are already using delegate method if you are using UITableView.
Good luck

A: According to my understanding ,
class A has tableview and on the selection of table cell opening some modal view.
In modal view user is entering some data which is passing to class A table cell label.
So my solution for this, create one protocol in modal view and call delegate for updated changes in class A table.


text:
Q: Android Studio is not accepting new project I want to start learning Android programming and recently downloaded the Android Studio. Now if I want to start a new project, I can't get past this initial screen. Whenever I click next, the window just jerks, which I guess is indicating that I am doing something wrong. So how can I solve this problem?

Note: I am a total beginner but I am genuinely trying to learn and searching the web for the problem didn't give me any solution.

A: I guess something is wrong with your Android Studio / JDK installation. In the status bar on the bottom, I can see a NullPointerException. I think this is the cause. Try to open the Android Studio Log and hopefully the error is better explained there.
How to find Android Studio Log

A: Maybe you have unknown characters in your package name like "ı,ö,ü" ? And you may want to watch a android starter tutorial video which has a part about starting a project to see if you are doing something wrong?
If it couldn't be a good answer sorry for it but that's all i can offer :3


text:
Q: How to output large csv file through Apache POI Excel in java? Struggling to write 300k rows to csv file through Apache POI java. I have been trying to generate a csv file from an excel file with 300k rows. Everytime, I get GCOutMemory error when it tries to write to output csv file. I even tried splitting the write for every 100k rows. The output file size keeps on growing but I don't see system.println statement isnt getting printed.
import javafx.beans.binding.StringBinding;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReadWrite {
    private static Logger logger= LoggerFactory.getLogger(ReadWrite.class);

    public static void main(String[] args) {
        try {
            long startReading = System.currentTimeMillis();
            Path path = Paths.get("/Users/venkatesh/Documents/Citiout_files/citiout300k_2sheets.xlsx");

            byte[] result = new byte[0];
            try {
                result = Files.readAllBytes(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStream is = new ByteArrayInputStream(result);

            Workbook workbook = WorkbookFactory.create(is);

            long readDone = System.currentTimeMillis() - startReading;
            logger.info("read time " + readDone);

            Sheet sheet = workbook.getSheetAt(1);
            Row firstRow = sheet.getRow(0);
            int headcol = firstRow.getLastCellNum();
            long startTransform = System.currentTimeMillis();
            firstRow.createCell(headcol++).setCellValue("Sold Amount1");
            firstRow.createCell(headcol++).setCellValue("CF_Quantity1");
            firstRow.createCell(headcol++).setCellValue("CF_Quantity2");
            firstRow.createCell(headcol++).setCellValue("CF_TradePrice");
            firstRow.createCell(headcol++).setCellValue("CF_ForwardPrice");
            firstRow.createCell(headcol++).setCellValue("CF_UnrealizedPL");
            firstRow.createCell(headcol++).setCellValue("CF_Quantity1Round");
            firstRow.createCell(headcol++).setCellValue("CF_Quantity2Round");
            firstRow.createCell(headcol++).setCellValue("CF_FXLotKeyNoTradeDate");
            firstRow.createCell(headcol++).setCellValue("CF_FXRoundedKeyNoTradeDate");
            firstRow.createCell(headcol++).setCellValue("CF_SettlementDate");
            for (int i = 1; i <=sheet.getLastRowNum()+1; i++) {
                String jj="";
                Row nRow = sheet.getRow(i-1);
                for(Cell c:nRow) {
                    if (c.getColumnIndex()==3 && i!=1) {
                        Calendar cal = Calendar.getInstance();
                        Date date1 = new SimpleDateFormat("dd-MMM-yyyy").parse(c.getStringCellValue());
                        cal.setTime(date1);
                        jj = String.valueOf(cal.get(Calendar.MONTH)+1) + "/" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH)) + "/" + String.valueOf(cal.get(Calendar.YEAR));
                    }
                }
                int count = nRow.getLastCellNum();
                //System.out.println(nRow.getCell(3).getClass());
                nRow.createCell(count++).setCellFormula("G" + i + "*-1");
                nRow.createCell(count++).setCellFormula("E" + i + "/" + "G" + i);
                nRow.createCell(count++).setCellFormula("G" + i + "/E" + i);
                nRow.createCell(count++).setCellFormula("ROUND(ABS(T" + i + "/S" + i + "),6)");
                nRow.createCell(count++).setCellFormula("ROUND(K" + i + ",6)");
                nRow.createCell(count++).setCellFormula("ROUND(N" + i + ",2)");
                nRow.createCell(count++).setCellFormula("ROUND(S" + i + ",0)");
                nRow.createCell(count++).setCellFormula("ROUND(T" + i + ",0)");
                nRow.createCell(count++).setCellFormula("CONCATENATE(T" + i + "," + "\"~\"" + ",S" + i + ")");
                nRow.createCell(count++).setCellFormula("CONCATENATE(X" + i + "," + "\"~\"" + ",Y" + i + ")");
                nRow.createCell(count++).setCellValue(jj);
                c.setCellValue(DateUtil.getExcelDate(calendar.getTime()));

            }
            long endTransform = System.currentTimeMillis() - startTransform;
            System.out.println("Transformations time " + endTransform);
            final FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            FileWriter writer= new FileWriter(new enter code hereFile("/Users/venkatesh/Documents/cit300k.csv"));
            StringBuilder data = new StringBuilder();
            Iterator<Row> rowIterator = workbook.getSheetAt(1).iterator();

            try {
                while (rowIterator.hasNext()) {

                    Row row = rowIterator.next();

                    Iterator<Cell> cellIterator = row.cellIterator();
                    while (cellIterator.hasNext()) {
                        Cell cell = cellIterator.next();

                        CellType type = cell.getCellType();
                        if (type == CellType.BOOLEAN) {
                            data.append(cell.getBooleanCellValue());
                        } else if (type == CellType.NUMERIC) {
                            data.append(cell.getNumericCellValue());

                        } else if (type == CellType.STRING) {
                            data.append(cell.getStringCellValue());
                        } else if (type == CellType.FORMULA) {
                            switch (evaluator.evaluateFormulaCell(cell)) {
                                case STRING:
                                    data.append(cell.getStringCellValue());
                                    break;
                                case NUMERIC:
                                    data.append(cell.getNumericCellValue());
                                    break;
                            }
                        } else if (type == CellType.BLANK) {
                        } else {
                            data.append(cell + "");
                        }
                        data.append(",");
                    }
                    writer.append(data.toString());
                    writer.append('\n');
                }
            } catch(Exception e){
                e.printStackTrace();
            }
            finally{
                if(writer!=null){
                    writer.flush();
                    writer.close();
                }
            }

            for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) {
                if (mpBean.getType() == MemoryType.HEAP) {
                    System.out.printf(
                            "Name: %s: %s\n",
                            mpBean.getName(), mpBean.getUsage()
                    );
                }
            }
            try {
                workbook.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
}

20-01-12 19:52:49:267  INFO main ReadWrite:64 - read time 11354
Transformations time 38659
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.TreeMap$Values.iterator(TreeMap.java:1031)
    at org.apache.poi.xssf.usermodel.XSSFRow.cellIterator(XSSFRow.java:117)
    at org.apache.poi.xssf.usermodel.XSSFRow.iterator(XSSFRow.java:132)
    at org.apache.poi.xssf.usermodel.XSSFEvaluationSheet.getCell(XSSFEvaluationSheet.java:86)
    at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateFormula(WorkbookEvaluator.java:402)
    at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:275)
    at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:216)
    at org.apache.poi.xssf.usermodel.BaseXSSFFormulaEvaluator.evaluateFormulaCellValue(BaseXSSFFormulaEvaluator.java:56)
    at org.apache.poi.ss.formula.BaseFormulaEvaluator.evaluateFormulaCell(BaseFormulaEvaluator.java:185)
    at ReadWrite.main(ReadWrite.java:150)

A: So now that we have a usable stacktrace, it is clear that the problem is NOT happening while writing the CSV file.  It is actually happening while you are evaluating a spreadsheet formula.  My guess is that the formula is summing across all rows in a sheet ... or something like that.
This is a problem, and there is probably no simple solution.
Here's what the POI documentation says:

File sizes/Memory usage

*

*There are some inherent limits in the Excel file formats. These are defined in class SpreadsheetVersion. As long as you have enough
  main-memory, you should be able to handle files up to these limits.
  For huge files using the default POI classes you will likely need a
  very large amount of memory.

*

*There are ways to overcome the main-memory limitations if needed:

*For writing very huge files, there is SXSSFWorkbook which allows to do a streaming write of data out to files (with certain
  limitations on what you can do as only parts of the file are held in
  memory).

*For reading very huge files, take a look at the sample XLSX2CSV which shows how you can read a file in streaming
  fashion (again with some limitations on what information you can read
  out of the file, but there are ways to get at most of it if
  necessary).

You are clearly running into these memory limitations.  Basically, POI is trying to load too much of the spreadsheet into memory ... while you are evaluating the spreadsheet formulae ... and you are filling the heap.
One solution would be to increase the Java heap size.  Or if you are already using all available RAM for your heap, run the conversion on a machine with more RAM.  A lot of standard PCs have 16GB RAM these days.  Maybe it is time for a hardware upgrade?  But I'm guessing you have already thought of this.
If increasing the heap size is not viable, then you will need to rewrite your application to use SXSSFWorkbook.  Furthermore, you may need to replace your approach of using formula evaluation with doing the calculations in native Java in a way that is compatible with row-by-row streaming of the spreadsheet.  (It will depend on what the formulae do.)
Look at the linked example from the POI documentation for ideas.


text:
Q: move_uploaded_file($tmpPath, $destPath); Returns False. Mac return move_uploaded_file($tmpPath, $destPath);

Where
$destPath = "/Library/WebServer/Documents/root/media/tmp/catalog/650540b.jpg"

And
$tmpPath = "/Library/WebServer/Documents/root/tmp/640540b.jpg"

I chmodded both directories,
$_FILES['image_file']['tmp_name'] = "/Library/WebServer/Documents/superiorstore/tmp/640540b.jpg"
$_FILES['image_file']['name'] = "650540b.jpg"

But move_uploaded_file always returns false. I put the file in the tmp directory prior to running the code for testing on my local machine.

A: I would like you to check those lines from documentation

*

*This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

*This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system.

My best bet is that your are trying to only move the file from a directory to another, and if so there is a command you might want to use as rename() but move_uploaded_file() will only works if the upload process has been done correctly. That's why you still get false.


text:
Q: Change class in table column with jquery I have a table like this:

            ....
            ....

        <tr....

How can I change with jquery class "fa fa-check" to "fa fa-ban" in the first  and remove the content of the last  (fa-file-o and fa-close) in the row with data-index="0"?

A: You can do something like this
$('tr[data-index="0"]') // <-- this will get the td with data-index 0
  .find('td:first .fa-check').addClass('fa-ban').removeClass('fa-check') // <-- this will get the first td and replace fa-check to fa-ban
  .end() // <-- this will refer back to the tr with data index 0 initially referenced
  .find('td:last').empty(); // <-- this will search the last td and empty it

You need .end() because after jquery gets the tr with index 0 and then iterates inside the first td we need to traverse back to the parent tr so that the last td can be captured.

$('tr[data-index=0]')
  .find('td:first .fa-check').addClass('fa-ban').removeClass('fa-check')
  .end()
  .find('td:last').empty();

    ....
    ....

A: For first:
$(".fa fa-check").addClass('fa-ban').removeClass('fa-check')

edit:
$('tr[data-index="0"]').find('td:first .fa fa-check').addClass('fa-ban').removeClass('fa-check')


text:
Q: one to many relationship in mongoose I'm using mean stack to create a hybrid app.I'm using nosql to create DB in mongoose.My DB consists of two tables one is 'donors' and another one is 'bloodGroup'.
My 'bloodGroup' schema is as follows:
module.exports = function(mongoose) {
 var Schema = mongoose.Schema;

  /* bloodGroup Schema */
  var bloodGroupSchema = new Schema({
   name: { type: String, required: true }
  });
}

My 'Donor'schema is as follows:
/* Donor Schema */
var DonorSchema = new Schema({
 Name: { type: String, required: true },
 DOB: { type: Date, required: true, trim: true },
 Sex: { type: String },
 BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
 ContactNo: { type: String, required: true },
 LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
 EmailId: { type: String, required: true },
 Password: { type: String, required: true }
});

When many donors refer to a single blood group then BloodGroup object Id error is reported.How to solve this problem?

A: You can refer this link for documentation: http://mongoosejs.com/docs/populate.html

Saving Refs

    /* Donor Schema */
    var DonorSchema = new Schema({
     _id : {type: Number},
     Name: { type: String, required: true },
     DOB: { type: Date, required: true, trim: true },
     Sex: { type: String },
     BloodGroupID: { type: Schema.Types.ObjectId, ref: 'BloodGroup', required: true },
     ContactNo: { type: String, required: true },
     LocationId: { type: Schema.Types.ObjectId, ref: 'Location', required:true },
     EmailId: { type: String, required: true },
     Password: { type: String, required: true }
    });

    /* bloodGroup Schema */
   var bloodGroupSchema = new Schema({
       _bid :{ type: Number, ref: 'Donor' },
       name: { type: String, required: true }
   });

    module.exports = mongoose.model('Donor', DonorSchema);
    module.exports = mongoose.model('Blood', bloodGroupSchema);

    var vidya = new Donor({ _id: 0, name: 'Vidya', sex: 'F' });
        vidya.save(function (err) {
          if (err) return handleError(err);

          var blood = new BloodGroup({
            name: 'B+',
            _bid: vidya._id    // assign the _id from the Donor
          });

          blood.save(function (err) {
            if (err) return handleError(err);
            // thats it!
          });
        });

A: Mongo is not a Relational database, relation one to many does not exist in mongDB. The question is quite confusing, but following the title, you should either embed the donnors into the BloodGroup, or create an Id field unique to which you will refer and do two queries.


text:
Q: Auth0 Access Token Not Returning Roles (Authorization Extension) Please assist. I am very new in Auth0. I want to use Role Based Access Control (RBAC) in my angular 8 app and ASP.NET Core 2.2 API. I have registered both the API and SPA in Auth0. The authentication is working fine but I am having issues with authorization. The access_token that I am getting back from Auth0 does not have the roles in it. It has the permissions instead of the roles. I have installed Auth0 Authorization2.6 extension. I have also enabled RBAC.
I get this from the output log (Visual Studio 2019) Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: Successfully validated the token. And it fails to authorize with this error Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed
I have created users, roles and permissions. I assigned all my users the relevant roles. Below is the code snippet from my Startup class (the API).
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder =>
                {
                    builder
                    .WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                });
        });

        var domain = $"https://{Configuration["Auth0:Issuer"]}/";

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = ClaimTypes.NameIdentifier,
                RoleClaimType = ClaimTypes.Role,
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Auth0:Issuer"],
                ValidAudience = Configuration["Auth0:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Auth0")["ClientSecret"]))
            };
            options.Authority = domain;
            options.Audience = Configuration["Auth0:Audience"];
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("StakeholderManager", policy => policy.RequireRole("StakeholderManager"));
        });
    }

My API endpoint looks like this
[HttpGet("students")]
[Authorize(Roles = "StakeholderManager")]
    public IActionResult GetAllStudents()
    {
        var user = User;
        return Ok(new
        {
            Student1 = "James Bond",
            Student2 = "Belinda Abrahams"
        });
    }

Below if my access token that is sent to the API for authentication and authorization

Enabled RBAC

I have also modified the Auth0 Authorization rule to try and include the roles as per screenshot below, but this did not help either.

A: The authorization extension will be deprecated and replaced by the core RBAC feature (this is the roles you see in the user section of the dashboard). If you migrate your roles and permission to that feature, you should be able to add the roles to the token in a custom claim like you have tried to do in the screenshot you provided.
See this doc for an example:
https://auth0.com/docs/authorization/concepts/sample-use-cases-rules#add-user-roles-to-tokens
This doc is also useful:
https://auth0.com/docs/authorization/concepts/core-vs-extension


text:
Q: Remove duplicates from the table by using two columns in sql? I have table like this
Id Name Lang   templateid
1  xxx  ENGISH  1
2  xxx  SPANISH 2
3  xxx  ENGISH  1
4  xxx  ENGISH  1
5  xxx  ENGISH  1
6  xxx  SPANISH 1

I want to remove the duplicate records which have same lang and templateid.For example templateid 1 + Lang ENGLISH is repeated more than once .
Delete the duplicates records and leave latest one ie., Id 5 is latest record for english language.
Any suggestions would be appreciated.

A: MySQL
Query
DELETE t2
FROM   tbl t1
JOIN   tbl t2 ON
(
   t2.lang = t1.lang
   AND t2.templateId=t1.templateId
   AND t2.id < t1.id
);

Fiddle Demo

PostgreSQL
Query
DELETE FROM tbl t1
WHERE id IN
(
  SELECT t1.id
  FROM   tbl t1
  JOIN   tbl t2 ON
  (
    t2.lang = t1.lang
    AND t2.templateId=t1.templateId
    AND t2.id > t1.id
  )
);

Fiddle Demo


text:
Q: form_load subroutine in MS Access VBA I am writing a code in MS Access VBA, which is as follows:
Private Sub Form_Load()
    MsgBox "loggedIn = " + CStr(loggedIn)
    If (loggedIn = 1) Then
    Else
        Exit Sub
    End If
End Sub

I want to decide whether to load the form or not based on loggedIn variable. If loggedIn variable is 1, form shall be loaded. If the same is not 1, form shall not be loaded.
Issue that I am facing is that, whatever I do in ELSE part of the code above, I am not able to stop the form from loading.
How can I achieve this?
Pls comment if any additional information is required.
Thank you.

A: If the loggedIn value is available at form open, you could cancel the form open event.
Private Sub Form_Open(Cancel As Integer)
    Cancel = Not (loggedIn = 1)
End Sub

If the value of loggedIn is not available until the form's load event, you can close the form.
Private Sub Form_Load()
    If loggedIn <> 1 Then
        DoCmd.Close acForm, Me.Name
    End If
End Sub


text:
Q: Properly resize Image View for iPhone5 and iPad app background I'm using an Image View to display the background of my app, which is a single view app. It's basically a calculator for iPhone5 but the problem that I have as you may know that the app should be able to run in an iPad to be able to be approved for the iTunes Store, and what is happening is that the button part of my image get cut off and some important buttons are not displayed in the screen (when its running on an iPad)
I have been looking around but I can't find the proper way to achieve this and not the my image displayed with pixels or simple ugly..
1. If I set the image over Xcode not programmably, its when the image get cut off (I'm doing this over my Main.storyboard and then on my attributes inspector, and setting an image that I have created in this dimensions 640 × 1136 for my iphone5 app.
2. I tried this approach too, but I had some kind of success but not what I'm looking for which is to properly show a clear background (no pixels) or (ugly) and keeping the same alignment of my buttons in the ipad display (it could be retina, mini...)
Note: to accomplish this part, I have to remove the image from my Image View and leave it blank which creates a funny ugly image..
    UIGraphicsBeginImageContext(self.view.frame.size);
        [[UIImage imageNamed:@"myCal-bg-iphone5 .png"] drawInRect:self.view.bounds];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        //[self imageWithImage:thumbImage scaledToSize:CGSizeMake(30,30)]

        self.view.backgroundColor = [UIColor colorWithPatternImage:image];

3. I also tried way, changing the image of my Image View but I had not much success either.. it expands the image like crazy and in the ipad display it shows almost none buttons at all..
Note: I also tried with the same image that I'm providing for the iphone5 display
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
        if (screenBounds.size.height == 568){
           [self.myBackground setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"myCal-bg-iphone5.png"]]];
        }else{
            [self.myBackground setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"myCal-bg-ipadMini.png"]]];
        }

A: There's a stretching property on IB.

You can set an area of image which will be stretched. For example, if you set X=0.9, width=0.1, the right 10% of image will be stretched with your imageView size.
Programmably? Use UIImage's instance method. resizableImageWith...

A: I made it work this way, if you guys have any suggestions please let me know..
I have a MACRO for detecting the screen size..
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

Then, this is in my viewDidLoad
UIImage *image;

if ( IS_IPHONE_5 )
    image = [UIImage imageNamed:@"myCal-bg-iphone5.png"];
else
    image = [UIImage imageNamed:@"myCal-bg-iphone4.png"];

 self.myBackground = [[UIImageView alloc] initWithFrame:self.view.bounds];
 self.myBackground.image = image;
 self.myBackground.autoresizingMask = UIViewAutoresizingFlexibleHeight;
 self.myBackground.contentMode = UIViewContentModeScaleAspectFill;
 [self.view insertSubview:self.myBackground atIndex:0];

At the end, what I'm doing is resizing the image that Im using for my iphone5 app as background to able to fit iphone4 which it also, fits in ipad but with the 1X or 2X display for iphone apps..
Note: I would love to be able to resize the whole thing.. example or in a few words, after doing this resize the buttons of my app get all in a misalignment for iphone4 or ipad becasue the screen size is different, so I'm wondering if there is a way I can control all of them and re-adjust to the new screen size/device?

A: If you use Xcode5 and above, just create new image in Images.xcassets
-Right Click Images.xcassets -> new Image Set (rename)
-Right click on work panel of your image set -> choose Rentina 4 in and iPad.
 Unselect universal image and iPhone (if not target iPhone 4)
-Drag each image associate with type
Then just set image name in code


text:
Q: How to load more than one cell into UITableView from Firebase Realtime Database when array is saved as a dictionary string I hope the question makes sense.
I am saving named poems to Firebase Realtime Database.
Class
var named = ""

var data = [""]

var filteredArray = [String]()
var isSearching = false

Save function
named = "Test1"

let poem = data //(data = "Tester1")

let addPoem: [String: [String]] = [named: poem]

let userAdding = ref.child(user)

userAdding.updateChildValues(addPoem, withCompletionBlock:
{
    (error:Error?, ref:DatabaseReference) in
    if let error = error
    {
       print("Data could not be saved: \(error).")
    }
    else
    {
       print("Data saved successfully!")

       self.savedPoemAlert()
    }
})

I've done it three times, to make sure it saves them as separately named poems, it looks like this [here]: https://i.stack.imgur.com/EcGo1.png
I am trying to load it back into the tableView but it appears to load them all as one cell.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{
    isSearching = true

    mainTable.reloadData()
    mainTable.isHidden = false

    filteredArray = data.filter({$0.range(of: searchBar.text!, options: .caseInsensitive) != nil })
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    if isSearching
    {
        return filteredArray.count
    }
    else
    {
        return data.count
    }
}

func numberOfSections(in tableView: UITableView) -> Int
{
    return self.data.count
}

It loads as one cell even though it says there are three cells?
    let refs = ref.child(user)

    refs.observe(.value, with:
    {
        (snapshot) in
        let loadToTable = (snapshot.value)

        let cellsInDB = (snapshot.childrenCount)

        if cellsInDB > 1
        {
          print(cellsInDB)
          print(loadToTable!)

          if loadToTable != nil
          {
             self.data = ["\(loadToTable!)"]
          }
        }
    })

If I just load the snapshot into the data, it only loads the table with the MOST RECENT SINGLE uploaded dictionary to the database.
If I load it as is seen in that last bit of code, it loads all three children into the one cell back into the tableView.
I am able to select the row and populate two separate areas as intended.
Either way, I have only been able to load one cell into the tableView.
I have two other apps where everything works well when searching, and it loads the tableView as intended with all the cells. Those are saved to the database without having saved the data as individual dictionaries.
Please tell me what I am missing, and/or what other code you need to see.
Thanks in advance.
Just asked this one today too How to load more than one cell into UITableView from Firebase Firestore Database


text:
Q: D3.js Barchart timescale : Uneven space between bars I guess the title explains the problem.  Similar questions on SO refer to ordinal scales.
x axis scale:
var x = d3.time.scale()
        .domain(d3.extent(data, function(d) {
            return d.date;
        }))
        .range([width/data.length/2, width-(width/data.length/2)]);

The bars
bars.enter()
    .append("rect")
        .classed("column", true)
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)
        .attr("width", (width-(width/data.length)) / (data.length+2))
        .attr("x", function(d) { return x(d.date) - (width/data.length)/2; })
        .attr("y", height)
        .attr("height", 0)
        .transition().duration(1000)
        .attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return height - y(d.value);});

How can I amend this code so that I have a whole and equal number of pixels between each vertical bar, and thereby getting an even spacing ?


text:
Q: How to automate a transfer of file from server to local system using ftp I have a windows server 2003 which generates backup file to ftp folder in the server(using my own script). And I will ftp and copy it to my local hard disk daily. How can I automate this process using any scripts?
Edit--
I want to pull the archive(rar format) file which will be around 50MB, I am using Windows 7 on my local and using windows FTP in the server.
Authentication and encryption is not required currently

A: Assuming your workstation is windows based (other OS's ftp clients work similarly though)
ftp -help

Transfers files to and from a computer running an FTP server service
(sometimes called a daemon). Ftp can be used interactively.

FTP [-v] [-d] [-i] [-n] [-g] [-s:filename] [-a] [-A] [-x:sendbuffer] [-r:recvbuf
fer] [-b:asyncbuffers] [-w:windowsize] [host]

  -v              Suppresses display of remote server responses.
  -n              Suppresses auto-login upon initial connection.
  -i              Turns off interactive prompting during multiple file
                  transfers.
  -d              Enables debugging.
  -g              Disables filename globbing (see GLOB command).
  -s:filename     Specifies a text file containing FTP commands; the
                  commands will automatically run after FTP starts.
  -a              Use any local interface when binding data connection.
  -A              login as anonymous.
  -x:send sockbuf Overrides the default SO_SNDBUF size of 8192.
  -r:recv sockbuf Overrides the default SO_RCVBUF size of 8192.
  -b:async count  Overrides the default async count of 3
  -w:windowsize   Overrides the default transfer buffer size of 65535.
  host            Specifies the host name or IP address of the remote
                  host to connect to.

Notes:
  - mget and mput commands take y/n/q for yes/no/quit.
  - Use Control-C to abort commands.

Note the -s:filename. All you have to do is create a text file that contains the commands you would type manually to retrieve the file. Something like
open myserver.example.com
xyzzy
plugh
lcd c:\savedbackups
cd c:\backup\directory
bin
get backup.file
quit

Then if the file is backups.ftp you can use it as
ftp -s:backups.ftp

You can find a list of available ftp commands by running the client and typing help.

In the example above the ftp client will connect to myserver.example.com, provide the username xyzzy and the password plugh. It then changes to the local directory c:\savedbackups and the remote directory c:\backup\directory and pulls a copy of backup.file using a binary mode transfer.


text:
Q: collectionview cell is not visible even after delegate methods are getting called I have a UICollectionview of size height 40. UICollectionviewcell of (25,25). Cells are not getting shown. every delegate method call is working fine.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: 25.0, height: 25.0)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 1.0
}

A: class yourviewcontroller:UICollectionViewDelegate ,UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{

}

UICollectionViewDelegateFlowLayout add this


text:
Q: simplify (1 + 2 Cos[2 x])/(Sqrt[3] - 2 Sin[2 x]) I want to simplify (1 + 2 Cos[2 x])/(Sqrt[3] - 2 Sin[2 x]) to Tan[x + Pi/3]
FullSimplify[(1 + 2 Cos[2 x])/(Sqrt[3] - 2 Sin[2 x])]

couldn't simplify it. Why doesn't Mathmatica simplify it?

A: In:
rule = x -> y - Pi/3;
left = (1 + 2 Cos[2 x])/(Sqrt[3] - 2 Sin[2 x]) /. rule // TrigExpand //
   TrigReduce
right = Tan[x + Pi/3] /. rule

Out:
Tan[y]
Tan[y]


text:
Q: EF Core - return null for entity with foreign key with id = 0 I'm using a database from a 3rd party (only have read access to it) with a nullable column that is a foreign key to another table:
Person.Id    1-*    PatientFile.PatientId
PatientFile.PrescDocID    0...1 - 0...1    Person.Id

I'm using an OData clone (https://github.com/trenoncourt/AutoQueryable) to fetch related data when adding to the URL: ?select=*
The problem is that the nullable column (Person.Id) sometimes contains the id 0 instead of null. This means that the property PrescDoc is presented in my JSON response as
"prescDoc": {
   "surName": null,
   "firstName": null,
   "isNaturalPerson": null,
   "birthDate": null,
   "id": 0
}

while it should be:
"prescDoc": null

Is there a way to configure EF Core to set the property prescDoc on PatientFile to null if the id of the prescDoc object or the PatientFile.PrescDocId id 0?
Version I'm using:

*

*ASP.NET Core 2.1.1

*EF Core 2.1.1

*Database running on MSSQL 2008R2

*Webserver running on Windows Server 2016

A: Some other options:
In your entity class, you can override the getter:
private int? prescDocID;
public int? PrescDocID
{
    get => prescDocID == 0 ? default : prescDocID;
    set => prescDocID = value;
}

Or, you can use a custom JsonConverter to control it during serialization:
public class ZeroToNullConverter : JsonConverter<int?>
{
    public override int? ReadJson(JsonReader reader, Type objectType, int? existingValue, bool hasExistingValue, JsonSerializer serializer) =>
        reader.Value as int? == 0 ? default : reader.Value as int?;

    public override void WriteJson(JsonWriter writer, int? value, JsonSerializer serializer) =>
        writer.WriteValue(value == 0 ? default : value);
}

Then:
[JsonConverter(typeof(ZeroToNullConverter))]
public int? PrescDocID { get; set; }

A: If you are using AutoQueryable, according to their docs, you can override the Get method. So you can override with a Select so that the Person object being constructed can have the prescDoc prop null if the value of the id is 0:
[Route("api/[controller]")]
public class UsersController : Controller
{
    [HttpGet]
    [AutoQueryable]
    public IQueryable<Person> Get([FromServices] myDbContext dbContext)
    {
        return dbContext.Person.Select(p => new Person() {
           --other props go here--,
           prescDoc = p.prescDoc.Id == 0 ? null: p.prescDoc
           }
           );
    }
}


text:
Q: How can I fix "Refused to load the stylesheet because it violates the following Content" in Magento 2.3.5 I've recently upgraded to Magento 2.3.5 and I've been encountering an issue with my Content Security Policy when trying to load a style sheet.
The error (Chrome dev console):

I've added maxcdn to my csp_whitelist.xml but the error still occurs after setup:upgrade + setup:static-content:deploy + cache flush
My csp_whitelist.xml:
<?xml version="1.0"?>
 <csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp/etc/csp_whitelist.xsd">
    <policies>
        <policy id="style-src">
            <values>
                <value id="maxcdn-fontawesome" type="host">maxcdn.bootstrapcdn.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>

I've tried adding https in the hostname, but that didn't make any difference.
I'm curious as to why the violated directives are from different domains as well. getfirebug.com is only used for the tinymce editor in my admin backend not on the storefront.
How can I go about removing this error?
Also, could anyone provide me with additional resources for researching this? I've read through Mozillas CSP guide, but it's not exactly the same for Magento 2.3.5.

A: Magento 2.3.5 p1 added a new module module-csp ( Magento_Csp ) which supports Content Security Policies ( CSP ) headers and provides ways to configure them. The policies can be configured for backend and frontend areas both.
Content Security Policies ( CSP ) has two modes – report-only and restrict. In Magento 2.3.5 p1, the default mode is report-only which is shows the policy violations in the browser's console. You can configure these csp for all third party loaded content as per your custom modules and theme.
I was able to solve all the policy errors for my site by creating a custom module.
app/code/Namespace/Csp/registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Namespace_Csp',
    __DIR__
);

app/code/Namespace/Csp/etc/module.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Namespace_Csp" setup_version="1.0.0" />
</config>

app/code/Namespace/Csp/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <csp>
            <mode>
                <storefront>
                    <report_uri>https://www.example.com/</report_uri>
                </storefront>
                <admin>
                    <report_uri>https://www.example.com/</report_uri>
                </admin>
            </mode>

        </csp>
    </default>
</config>

app/code/Namespace/Csp/etc/csp_whitelist.xml
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp/etc/csp_whitelist.xsd">
    <policies>
        <policy id="script-src">
            <values>
                <value id="cloudflare" type="host">*.cloudflare.com</value>
                <value id="twitter.com" type="host">*.twitter.com</value>
                <value id="google-analytics" type="host">*.google-analytics.com</value>
                <value id="twimg" type="host">*.twimg.com</value>
                <value id="gstatic" type="host">*.gstatic.com</value>
                <value id="trustedshops" type="host">*.trustedshops.com</value>
                <value id="usercentrics" type="host">*.usercentrics.eu</value>
                <value id="fontawesome" type="host">*.fontawesome.com</value>
            </values>
        </policy>
        <policy id="style-src">
            <values>
                <value id="cloudflare" type="host">*.cloudflare.com</value>
                <value id="googleapis" type="host">*.googleapis.com</value>
                <value id="twitter.com" type="host">*.twitter.com</value>
                <value id="twimg" type="host">*.twimg.com</value>
                <value id="gstatic" type="host">*.gstatic.com</value>
                <value id="typekit" type="host">*.typekit.net</value>
                <value id="trustedshops" type="host">*.trustedshops.com</value>
                <value id="usercentrics" type="host">*.usercentrics.eu</value>
                <value id="fontawesome" type="host">*.fontawesome.com</value>

            </values>
        </policy>
        <policy id="img-src">
            <values>
                <value id="cloudflare" type="host">*.cloudflare.com</value>
                <value id="klarna-base" type="host">*.klarna.com</value>
                <value id="googleadservices" type="host">*.googleadservices.com</value>
                <value id="google-analytics" type="host">*.google-analytics.com</value>
                <value id="paypal" type="host">*.paypal.com</value>
                <value id="twitter.com" type="host">*.twitter.com</value>
                <value id="twimg" type="host">*.twimg.com</value>
                <value id="vimeocdn" type="host">*.vimeocdn.com</value>
                <value id="youtube-img" type="host">*.ytimg.com</value>
                <value id="data" type="host">'self' data:</value>
                <value id="lightemporium" type="host">*.lightemporium.com</value>
                <value id="usercentrics" type="host">*.usercentrics.eu</value>
            </values>
        </policy>
        <policy id="connect-src">
            <values>
                <value id="cloudflare" type="host">*.cloudflare.com</value>
                <value id="twitter.com" type="host">*.twitter.com</value>
                <value id="paypal" type="host">*.paypal.com</value>
                <value id="twimg" type="host">*.twimg.com</value>
            </values>
        </policy>
        <policy id="font-src">
            <values>
                <value id="cloudflare" type="host">*.cloudflare.com</value>
                <value id="twitter.com" type="host">*.twitter.com</value>
                <value id="gstatic" type="host">*.gstatic.com</value>
                <value id="typekit" type="host">*.typekit.net</value>
                <value id="twimg" type="host">*.twimg.com</value>
                <value id="trustedshops" type="host">*.trustedshops.com</value>
                <value id="googleapis" type="host">*.googleapis.com</value>
            </values>
        </policy>

        <policy id="frame-src">
            <values>
                <value id="twitter.com" type="host">*.twitter.com</value>
            </values>
        </policy>

        <policy id="form-action">
            <values>
                <value id="twitter.com" type="host">*.twitter.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>

Add your thirdparty urls/domains to csp_whitelist.xml. All suggestions are most welcome

A: I have this code and it works fine:
<?xml version="1.0" encoding="UTF-8"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
    <policies>
        <policy id="style-src">
            <values>
                <value id="bootstrapCdn" type="host">*.bootstrapcdn.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>

Try to clear these folders manually also:
rm -rf var/cache/*
rm -rf var/page_cache/*
rm -rf pub/static/*

A: You met this issue because the Security Policy was added into Magento version 2.3.5
For detailed information, please check this document: https://devdocs.magento.com/guides/v2.3/extension-dev-guide/security/content-security-policies.html

A: I am trying to use the solution above but it is not working
it is showing:
php bin/magento module:enable Namespace_Csp
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Namespace_Csp',
DIR
And yes, I have tried changing "Namespace" to something else and still, not working


text:
Q: Print Intent for Google Cloud Print App As of today, the official Cloud Print documentation from Google still tells you to include the PrintDialogActivity into your app to print documents using Google Cloud Print. However, it's now also possible to print using the official Google Cloud Print app. I couldn't find any documentation for that though.

A: The answer is pretty straightforward, but it still took me a few days to figure it out:
Intent printIntent = new Intent(Intent.ACTION_SEND);
printIntent.setType("text/html");
printIntent.putExtra(Intent.EXTRA_TITLE, "some cool title for your document");
printIntent.putExtra(Intent.EXTRA_STREAM, uri);

startActivity(printIntent);

That's the correct way to do it. Important: Intent.ACTION_SEND_MULTIPLE does NOT work at the moment.


text:
Q: Ajax.actionLink returns the same result in IE I'm trying to implement an Ajax.ActionLink in my MVC4 website and for some reason I keep getting the same result in IE (Firefox works fine).
I added this to the bottom of my _Layout.cshtml page:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

(before adding the jqueryval line i kept getting redirected)
this is my ajax call:
@{
    ViewBag.Title = "Test";
}

Test

@Ajax.ActionLink("Click to get a new guid", "GetGuid",
new AjaxOptions
{
    UpdateTargetId = "result",
    InsertionMode = InsertionMode.InsertAfter,
    HttpMethod = "GET"
})

my controller action:
public ActionResult GetGuid()
{
    string guid = Guid.NewGuid().ToString();
    return PartialView("_guid", guid);
}

and the partial view:
@model String

@Model.ToString()

When tested in IE I keep getting the same result appended, but in Firefox it works fine.
Any way to make this code compatible with IE or am I doing something wrong?

A: Have you tried setting the following in the document ready of the layout?
$.ajaxSetup({cache:false});

Si


text:
Q: Traceback error in Python 1 I have this code:
import urllib.request
import json

import pickle

import time

class Weather:

    current_temp = 0

    def __init__(self):
        json_info = get_info()
        Weather.current_temp = k_to_f(((json_info['list'][0]['main']['temp'])))
        current_city = (json_info['list'][0]['name'])
        print ('Current temperature {0} degrees F in {1} '.format(Weather.current_temp, current_city))
        map = manage_file(current_city)

    def manage_file(self, current_city):
        read_f = open('temp.txt', 'rb')
        dict = pickle.load(read_f)
        read_f.close()
        dict[time.strftime('%Y/%m/%d %H:%M:%S ') + current_city] = Weather.current_temp
        write_f = open('temp.txt', 'wb')
        return dict

    def get_info(self):
        city = input("What city would you like the weather for? ")
        url = 'http://api.openweathermap.org/data/2.5/find?q=' + city + 'mode=json'
        data = urllib.request.urlopen(url)
        data = data.read()
        json_info = json.loads(data.decode('UTF-8'))
        return json_info

    def k_to_f(self, num):
        num = (num-273.15)*1.8
        return round(num + 32, 2)
Weather()

and I am getting a traceback error of :
Traceback (most recent call last):
  File "/home/httpnick/nicks_python/new_weather.py", line 36, in <module>
    Weather()
  File "/home/httpnick/nicks_python/new_weather.py", line 14, in __init__
    map = manage_file(current_city)
  File "/home/httpnick/nicks_python/weather.py", line 36, in manage_file
     def get_info(self):
NameError: global name 'current_temp' is not defined

Can anyone spot it? I have looked for a couple hours now...

A: One thing that stood out to me... is that you're not using the instance methods in the constructor.  You might try to make this explicit:
def __init__(self):
    json_info = self.get_info()
    ...
    map = self.manage_file(current_city)

(Also... I'd avoid naming a variable "map", as this is a builtin function.)


text:
Q: Add Only on an import definition requires a primary key? I am confused - why does the "Add Only" option on an Import Definition require a primary key?  This doesn't make much sense to me.  The nature of this data extension in question doesn't necessitate the need for primary keys.  The client will be sending incremental delta files to add to this data extension.  Please, someone explain this!! :)

A: The functionality of "Add Only" import type is to add new records. For instance your DE contains 4 records already and now you are importing a file with 6 records(that file contains those 4 already existing records and 2 new records that you need to add in your DE). Now if the DE does not have a primary key, it will add duplicate records and you will end up having 10 records, but you needed just 2 newly added.
You can verify this by creating a DE containing a primary key. Create a record in that. Now if you have a file containing that record and few other records and if you try to import that file, it will insert only the new data and not that existing row for "Add only" import type.
SO for this, "Add Only" and "Add and Update Only" requires a DE to have primary key as many a times customers send updated files containing old and newly added rows where we want only newly added rows in our DE.
But to cater to the other cases where a new file is given by customer (example: date wise data), in those cases we can use "Overwrite" option.


text:
Q: opening hallo editor on document ready I'm trying to open the hallo editor toolbar on document.ready with focus on the first element or anywhere, it doesn't really matter I just need to open it
I tried triggering a click event on the editable element, and a focus event, nothing worked.
I have also tried to put the caret in the editable element:
var el = document.getElementById("content");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.firstChild, 2);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);

any other ideas?

A: I got it, must insert the caret in the element and then trigger the event halloactivated on document.ready
   var range = rangy.createRange();
   var sel = rangy.getSelection();
   range.selectNode(el);
   sel.removeAllRanges();
   sel.addRange(range);

   jQuery('#content').trigger('halloactivated');


text:
Q: Проблема с @Autowired Есть код:
package com.example.sweater3;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

_
package com.example.sweater3.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Message {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String text;
    private String tag;

    public Message() {
    }

    public Message(String text, String tag) {
        this.text = text;
        this.tag = tag;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public Integer getId() {
        return id;
    }

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

    public String getTag() {
        return tag;
    }

    public void setTag(String tag) {
        this.tag = tag;
    }
}

_
package com.example.sweater3;

import com.example.sweater3.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class GreetingController {

    @Autowired
    private MessageRepo messageRepo;
}

__
import com.example.sweater3.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MessageRepo extends CrudRepository<Message, Long> {

    List<Message> findByTag(String tag);
}

pom.xml
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mustache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.1.9.RELEASE</version>
        </dependency>

    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

При запуске программы вылетает такая ошибка:
 :: Spring Boot ::        (v2.0.0.RELEASE)

2019-10-30 17:21:11.059  INFO 5064 --- [  restartedMain] com.example.sweater3.Application         : Starting Application on IlyaPC with PID 5064 (D:\TEST\5October\30\sweater3\target\classes started by Ilya in D:\TEST\5October\30\sweater3)
2019-10-30 17:21:11.063  INFO 5064 --- [  restartedMain] com.example.sweater3.Application         : No active profile set, falling back to default profiles: default
2019-10-30 17:21:11.308  INFO 5064 --- [  restartedMain] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@7fa14664: startup date [Wed Oct 30 17:21:11 MSK 2019]; root of context hierarchy
2019-10-30 17:21:16.065  INFO 5064 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-10-30 17:21:16.111  INFO 5064 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-10-30 17:21:16.112  INFO 5064 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2019-10-30 17:21:16.122  INFO 5064 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_212\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Java\jdk-12.0.1\bin\;C:\Program Files\Java\jdk1.8.0_212\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Program Files\Java\jre1.8.0_221\bin;C:\Users\Илья\AppData\Roaming\npm;.]
2019-10-30 17:21:16.390  INFO 5064 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-10-30 17:21:16.390  INFO 5064 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5132 ms
2019-10-30 17:21:16.787  INFO 5064 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2019-10-30 17:21:16.800  INFO 5064 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-10-30 17:21:16.801  INFO 5064 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-10-30 17:21:16.801  INFO 5064 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-10-30 17:21:16.801  INFO 5064 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-10-30 17:21:16.885  WARN 5064 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'greetingController': Unsatisfied dependency expressed through field 'messageRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.sweater3.repos.MessageRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2019-10-30 17:21:16.889  INFO 5064 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-10-30 17:21:16.926  INFO 5064 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 17:21:17.360 ERROR 5064 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field messageRepo in com.example.sweater3.GreetingController required a bean of type 'com.example.sweater3.repos.MessageRepo' that could not be found.

Action:

Consider defining a bean of type 'com.example.sweater3.repos.MessageRepo' in your configuration.

Если убираю аннотацию @Autowired всё работает.
В чем проблема и как решить?
p.s. код максимально упрощенный, так как я убрал лишние куски, чтобы они не мешали читать код и не захламляли обзор.
UPD: Я допустил ошибку в копировании.
Вот ещё раз ошибка, которая вызвала вопрос:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 20:48:16.787 ERROR 2548 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field messageRepo in com.example.sweater3.GreetingController required a bean of type 'com.example.sweater3.repos.MessageRepo' that could not be found.

Action:

Consider defining a bean of type 'com.example.sweater3.repos.MessageRepo' in your configuration.

И добавляю скрин:

A: Спасибо огромное всем кто заминусил мой вопрос и так и не помог!
Подсказали решение в другом источнике.
Нужно добавить аннотацию @EnableJpaRepositories:
@SpringBootApplication
@EnableJpaRepositories

public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Обязательно добавить зависимость:
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

И уже всё заработает, но тогда может появиться ошибка такого характера:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-10-30 21:46:01.970 ERROR 2716 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

Значит мы на верном пути, остается подключить базу данных:
Возьму для пример postgresql:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

И конфигурации в resources/templates/application.properties (у каждого индивидуальные):
spring.datasource.url=jdbc:postgresql://localhost/sweater
spring.datasource.username=postgres
spring.datasource.password=root
spring.jpa.generate-ddl=true

UPD:
Аннотация @EnableJpaRepositories  необязатально.

A: Всё просто, добавь в класс GreetingController вот эту строчку: com.example.sweater3.repos.MessageRepo
Если не поможет, то обрати внимание на ошибку, потому что у тебя Контроллер не видит репозиторий.
У тебя ошибка, потому что написано sweater, а нужно sweater3.


text:
Q: Java Game, Bouncing & Movements I'm trying to create a simple game library mainly to teach myself. I read some posts here and in the web as such. But I think my problem is a bit different because I'm using my "own logic".
The basics:
All my objects on screen are called "entity" and they are capable to implement an interface called "EntityActionListener" wich allows to interact with the mouse, the keyboard, to move on the screen etc.
How to move the entity the best way?
Idea:
First of all I want to implement the movement, then the bouncing and then the collision for the entities.
For the movement and bouncing, and this is where I have problems, I want the following variables and functions:
protected float posx = 0, posy = 0;
protected float v = 0, vx = 0, vy = 0;
protected int direction = 0;

I use the setVelocity(float arg1) function to set the velocity (v) to arg1 and update the velocity on the axis (vx, vy):
/**
 * Set the velocity on both axis according to the direction given
 *
 * @param arg1 the direction in degrees
 * @param arg2 the velocity
 */
private void setVelocityOnAxis(int arg1, float arg2)
{
    // Check for speed set to 0
    if (arg2 == 0) {
        vx = 0;
        vy = 0;
        return;
    }

    // Set velocity on axis
    vx = (float) (Math.cos(arg1 * Math.PI / 180) * arg2);
    vy = (float) (Math.sin(arg1 * Math.PI / 180) * arg2);
}

So the velocity (v) may updates within a triggered event for example.
=> This step seems to work fine.
But I'm having some troubles with the direction which should be handled as follows:
/**
 * Set the entity direction
 *
 * @param arg1 the direction in degrees
 */
protected final void setDir(int arg1)
{
    // Update direction
    direction = arg1;

    // Update velocity on axis
    setVelocityOnAxis(direction, v);
}

/**
 * Get the enity direction based on the axis
 *
 * @param arg1 the x velocity
 * @param arg2 the y velocity
 */
protected final int getPointDir(float arg1, float arg2)
{
    // Set the direction based on the axis
    return (int) (360 - Math.abs(Math.toDegrees(Math.atan2(arg1, arg2)) % 360));
}

I wanted to have a bouncing on the border of the frame so I checked for the 4 directions by comparing the x and y coordinates and set either the vx or the vy according to the side to its additive inverse (like 1 to -1). But this does fail.
If I would just update the vx or vy on each side it would bounce like expected but the direction is not updated for this reason.
Here is the code I used:
// ...
// Hit bounds on x axis
direction = -vx; // works.
setDir(getPointDir(-vx, vy)); // does not work.

I'm not that good in geometry and trigonometry. The problem is that I can't say why a collision with a horizontal speed of 1 in direction 360 results in 45 degrees or other strange things I got from the debug prints ...
I really hope someone out there can help me. I just can't fix it.
EDIT:
My question is: Why is this not working. Some code in either setDir() or getPointDir() must be wrong.
EDIT 2
So, I finally get it work. The problem was that the entity had a direction of 45 and moved downwards instead of upwards so I additive inverse for the v speed - this causes this stupid error because minus and minus are positive and while I was bouncing it changed always both velocities, the vx and the vy. I just had to change something in the calculation for the degrees instead. Thank you for your help.

A: I'm taking a guess that getPointDir() and setVelocity() should calculate a direction in degrees from an x,y and an x,y from a direction in degrees (respectively). In that case, here's the proper line of getPointDir():
return (int) (360 + Math.toDegrees(Math.atan2(arg2, arg1))) % 360;

A simple test:
public static void main(String[] args) {
    Test t = new Test();

    for (int i = 0; i < 360; i++) {
        t.setVelocityOnAxis(i, 10);
        System.out.println("Angle: " + i + " vx: " + t.vx + " vy: " + t.vy);
        System.out.println("getPointDir: " + t.getPointDir(t.vx, t.vy));
    }

}

Edit as for the error, atan2() is always y,x -- easier to spot with variables names other than arg1, arg2. The other error was in the Math.abs logic.

A: Check this answer. It has the bounce on an axis correctly. You have to think the incoming angle is just as big as the outgoing angle, just opposite. The picture in the post describes this. Good luck.

A: Maybe this is what you're looking for... (still not sure I get your code).
In getPointDir():
double deg = Math.toDegrees(Math.atan2(arg1, arg2));
if (deg < 0) deg += 360;
return (int) deg;

And then use setDir(getPointDir(-vx, vy)) like in your original post.


text:
Q: File Dialog Throws a Null Reference When Cancelled In my site that has a file upload function, the File Dialog returns a null reference when I don't select a file and click Cancel. But here's the catch:
When the user:

*

*Open file dialog > select file > click Open, but thought maybe he selected the wrong file, so he -- > open file dialog > click Cancel, the file uploads successfully. But...

*On that same page, there's a button that allows you to edit the entry you just created. So maybe the user uploaded the wrong file, so he -- open file dialog > select file > click Open, but again thought maybe he selected the wrong file so he -- openfile dialog > click Cancel. The fun ends here as I get an Object reference not set to an instance of an object error.
What confuses me is that it goes through the same code but the first time it's run it works and on the second it fails?
BTW, I'm using Michiel Post's MultiFileUpload project.
The scenarios I've given runs through this code:
else
        {
            MultiFileUpload.SelectUserFiles();  //This calls the MultiFileUpload

            if (MultiFileUpload.UserFiles.FileList.LastOrDefault().FileName != refFileName)
            {
                //do something
            }

            else
            {
                //this is triggered when the user clicks Cancel on the FileDialog
                return;
            }
        }

Again, the code works for scenario number 1, but fails for scenario number 2 which obviously is just the same as 1.

A: Try to put your code in
try{

}
catch(Exception ex){
  // Show message here
}

Or you should make a filter for File Dialog.


text:
Q: make the div (in css) to grow bottom-up? how? I'm wondering how to make a div to grow bottom-up and not like it does normally.
I've here a example at jsFiddle. As u can see the right div will grow with more content but I want both div to stay fixed at the same level. (The left-div will never grow)
How can i make the right-div to grow bottom-up?

        læskdfsædlfksæ

               AUTHENTIQUE
               1.6 16V
               239

               AUTHENTIQUE
               1.6 16V
               239

The css:
#wrapper{ overflow: hidden;}

#div_1{
    border: 1px solid red;
    width: 100px;
    height: 50px;
    float: left;
}

#div_2{
    border: 1px solid black;
    width: 200px;
    float: left;
}

.clearing{ clear: both;}

#base{ border-top: 2px solid #666;}

A: No luck with float:left, because they are always aligned top. Change to display:inline-block;
http://jsfiddle.net/HerrSerker/ZEYvk/15/
Note: No whitespace between
 and

A: Changing float to inline is probably what you are after - but you could also absolutely position your div relative to another div it's inside and use bottom: 0 to keep the div stuck down.

A: This could be fixed by Javascript.. I used jQuery as shown in the example: jsfiddle
I just added the code:
$(document).ready(function (){
    $("#div_1").height($("#wrapper").height());
});


text:
Q: Question about loadNibNamed: I implemented a loadNibNamed: method to awake some window.
A Window, that opened is not active. How can I make this window current, when is will loaded?

A: [window makeKeyAndOrderFront: nil];


text:
Q: Attribute routing for simple ping controller with Get() not working I have simple asp.net core web api with a nudge controller that returns true for Get request. The PingController.cs looks as follows:
[Route("api/[Controller]")]
public class PingController : Controller
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(true);
    }
}

Why is navigating to the controller (http://localhost:56103/api/Ping) returning 404 ?
I added route on top of the controller and the HttpMethod for specific action. What is it that I am missing or not understanding here ?
When I add app.UseMvcWithDefaultRoute() in Startup.cs the controller works fine. (This is also confusing me.)
Startup.cs looks like the following :
public class Startup
{

            public IConfiguration Configuration { get; set; }

            public Startup()
            {
               Configuration = BuildConfiguration();
            }

            // This method gets called by the runtime. Use this method to add services to the container.
            public IServiceProvider ConfigureServices(IServiceCollection services)
            {
                ...
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
                ConfigureRoutes(app);
            }

            private static void ConfigureMvc(IServiceCollection services, Config config)
            {
                services.AddMvc()
                    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)// auto generated
                    .AddJsonOptions(options => { options.SerializerSettings.Formatting = Formatting.Indented; })
                    .AddControllersAsServices();

            }

            private static void ConfigureRoutes(IApplicationBuilder app)
            {
                //app.UseMvcWithDefaultRoute();
            }
        }

A: You need to add UseMvc() or UseMvcWithDefaultRoute() in startup to define routing.
UseMvcWithDefaultRoute adds a default route named 'default' to the request execution pipeline and equals to
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});


text:
Q: Text to excel using TextToColumns, only first record copied Newbie in VBA (excel) I am understanding a code that gets the value from a file, but only the first record in the file is transferred to the excel. Code as per below:
LineIndex = 0
Erase strLine()
Open myMainFile For Input As #1
   While Not EOF(1)
     LineIndex = LineIndex + 1
     ReDim Preserve strLine(1 To LineIndex)
     Line Input #1, strLine(LineIndex)
     MsgBox strLine(LineIndex)
 Wend
Close #1
.
.
.
With Nw.Worksheets(Mid(FileCol.Cells(i).Value, 7, 4)).Range("A1").Resize     (LineIndex, 1).Value = WorksheetFunction.Transpose(strLine)
             .TextToColumns Destination:=.Cells(1), DataType:=xlDelimited, _
             TextQualifier:=xlTextQualifierNone,     ConsecutiveDelimiter:=False, _              Tab:=True, Semicolon:=False,     Comma:=False, Space:=False
.
.
.

I am having a hard time understanding the second code block, and I believe this is the one causing the error. The file image file is the sample file that I need to transfer to excel
sample file
Excel output of the code is that it only gets the first line of the attached text