text:
Q: Java cloning with super and sub classes I have a two simple Java classes and I am trying to understand more about cloning and how to cast between different levels of classes. This is the superclass Vehicle.
public class Vehicle implements Cloneable
{
     public int x;

     public Vehicle(int y) {
          x = y;
     }

     @Override public Object clone() {
      Object result = new Vehicle(this.x);
      // Location "A"
      return result;
    }
}

And this is the subclass Truck
public class Truck extends Vehicle
{
   private int y;

   public Truck(int z) {
       super(z);
       y = z;
   }

   @Override public Object clone() {
      Object result = super.clone();
      System.out.println(result.getClass());
      ((Truck) result).y = this.y;
      return result;
    }
}

I am trying to get a copy of Truck while using the superclass to clone but having issues with downcasting not being allowed. I am not really sure how to fix this or where the error is.
I would like to have: Truck a = new Truck(1) and Truck b = a.clone() become the same object.

A: You're misusing clone(). All the instantiation and field copying is done by the super implementation when you implement Cloneable. Your Vehicle implementation should look like this:
@Override
public Vehicle clone() {
    try {
        return (Vehicle)super.clone();
    } catch (CloneNotSupportedException e) {
        throw new AssertionError();
    }
}

And you can optionally override it in Truck like this:
@Override
public Truck clone() {
    return (Truck)super.clone();
}

A: When you cast from one class to another, you are not changing the actual object, but making it accessible in a different way.
class A { public int x; }
class B extends A { public int y; }
A a = new A();
B aB = new B();
System.out.println(aB); // A@...
System.out.println(aB.y); // throws an error

When you call super.clone(), it creates a Vehicle instance, and Vehicle instances do not have y.
Instead, you probably want to initiate the object and not call super.clone() in Truck.clone:
    return new Vehicle(this.y);


text:
Q: How do I create an enum from a string in Kotlin? I have an enum with some instances Foo and Bar.  If I have a string "Foo", how can I instantiate a Foo enum from that?  In C# it would be Enum.Parse(...), is there an equivalent in Kotlin?
Currently, the best I have found is to create a factory that switches on all possible strings, but that is error prone and performs poorly for large enumerations.

A: As bashor suggested, use MyEnum.valueOf() but please have in mind that it throws an exception if value can't be found. I recommend using:
enum class MyEnum {
  Foo, Bar, Baz
}

try {
   myVar = MyEnum.valueOf("Qux")
} catch(e: IllegalArgumentException) {
   Log.d(TAG, "INVALID MyEnum value: 'Qux' | $e")
}

A: Would do it like
enum class MyEnum {
  Foo, Bar, Baz
}

val value = MyEnum.values().firstOrNull {it.name == "Foo"} // results to MyEnum.Foo

A: I think the best solution is enumValueOf<T>(String):
enum class MyEnum { Foo, Bar }

@Test
fun test() {
  assertEquals(MyEnum.Foo, enumValueOf<MyEnum>("Foo"))
}

A: Reusable Exception Safe Solution
The default solution in Kotlin will throw an exception. If you want a reliable solution that works statically for all enums, try this!
Now just call valueOf<MyEnum>("value"). If the type is invalid, you'll get null and have to handle it, instead of an exception.
inline fun <reified T : Enum<T>> valueOf(type: String): T? {
    return try {
        java.lang.Enum.valueOf(T::class.java, type)
    } catch (e: Exception) {
        null
    }
}

Alternatively, you can set a default value, calling valueOf<MyEnum>("value", MyEnum.FALLBACK), and avoid a null response. You can extend your specific enum to have the default be automatic
inline fun <reified T : Enum<T>> valueOf(type: String, default: T): T {
    return try {
        java.lang.Enum.valueOf(T::class.java, type)
    } catch (e: Exception) {
        default
    }
}

Or if you want both, make the second:
inline fun <reified T : Enum<T>> valueOf(type: String, default: T): T = valueOf<T>(type) ?: default

A: If you want to create an enum value from one of its parameters, instead of the name, this funny code does a pretty decent job:
inline fun <reified T : Enum<T>, V> ((T) -> V).find(value: V): T? {
    return enumValues<T>().firstOrNull { this(it) == value }
}

This can be used like this:
enum class Algorithms(val string: String) {
    Sha1("SHA-1"),
    Sha256("SHA-256"),
}

fun main() = println(
    Algorithms::string.find("SHA-256")
            ?: throw IllegalArgumentException("Bad algorithm string: SHA-256")
)

This will print Sha256

A: Kotlin enum classes have "static" function valueOf  to get enum entry by string(like Java enums). Additionally they have "static" function values to get all enum entries. Example:
enum class MyEnum {
  Foo, Bar, Baz
}

fun main(args : Array<String>) {
  println(MyEnum.valueOf("Foo") == MyEnum.Foo)
  println(MyEnum.valueOf("Bar") == MyEnum.Bar)
  println(MyEnum.values().toList())
}

A: You can create this kind of enum class which will take a string and convert it to enum type
enum class EmployeeType(val value: String) {
    Contractor("CONTRACTOR"),
    FullTime("FULL_TIME"),
    PartTime("PART_TIME");

    companion object {
        public fun fromValue(value: String): EmployeeType = when (value) {
            "CONTRACTOR" -> Contractor
            "FULL_TIME"  -> FullTime
            "PART_TIME"  -> PartTime
            else         -> throw IllegalArgumentException()
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invoke Method using Reflection I've got two classes. I want to invoke the "saveq" method in the QuestionPicker.class. This method saves some Strings into the SharedPreferences. I want to invoke that method from another class, that is called Questions.
I want to invoke the method using reflection, but my code doesn't work..
I think the problem is somewhere at the reflection, but I can't see it.
Can someone see the problem? Thanks
Here is the QuestionPicker.class
public class QuestionPicker {

    public void saveq() {

        // MyApplication Class calls Context
        Context context = MyApplication.getAppContext();

        // Values to save
        String Q1 = "SomeQuestion";
        String Q2 = "SomeOtherQuestion";
        String Q3 = "AndEvenMoreQuestions";

        // Save the Strings to SharedPreferences
        SharedPreferences.Editor editor = context.getSharedPreferences("QuestionsSaver", 0).edit();

        editor.putString("Q1", Q1);
        editor.putString("Q2", Q2);
        editor.putString("Q3", Q3);

        editor.apply();

    }
}

And here is the Questions.class
public class Questions extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_questions);

        // storing string resources into Array
        String[] subjects = getResources().getStringArray(R.array.subjects);
        ListView lv = (ListView) findViewById(R.id.listView);
        // Binding resources Array to ListAdapter
        ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, subjects);
        lv.setAdapter(adapter);

        // listening to single list item on click
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

          // Invoke the saving Method
                try {
                    Class cls = Class.forName("com.test.QuestionPicker");
                    Object obj = cls.newInstance();
                    Method method = cls.getMethod("saveq");
                    method.invoke(obj);

                } catch(Exception ex){
                    ex.printStackTrace();
                }

            }
        });
    }
}

A: I agree with @Joni - what doesn't work?  The code below, for example, does "work".  I removed the Androidness from it but the concept should be the same.
package com.company;

public class QuestionPicker {
    public void saveq() {
        System.out.println( "saveq is called");
    }
}

and
package com.company;

import java.lang.reflect.Method;

public class Main {

public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.company.QuestionPicker");
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod("saveq");
            method.invoke(obj);
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
}


text:
Q: Need helping performing sentiment analysis on customer reviews and for a string of text This is a 2 part code question.
1.) Need to perform sentiment analysis on a csv file for customer reviews.
2.) Need to perform sentiment analysis on a harry potter book review saved as a .txt
1.) The name of this Dataframe is "reviews" and what I want to do is display the sentiment score for each of these 5 reviews under the "sent" column.  Thank you so much!!! If you can provide the code with the "sent" column filled  with its sentiment analysis score for each row that would be awesome!!
reviews.head()
 ID  Customer Name    Review                                       Sent

 1   Jack             Beautiful cover up. My only
                      feedback is that it is a tad larger
                      than expected, but since it's a cover
                      up, it doesn't need to be fitted. The
                      waist tassels also allow you to adjust
                      to fit your waist which is nice.
                      Otherwise, its exactly as expected!

 2   Rachel           This tunic is very cute in person. It's
                      more sheer than I'd like, but I imagine
                      I'll wear it a ton on vacation.

 3   Ryan             Just got this sweet little dress in
                      blue. It's a great little dress for a
                      pool cover up. I can envision myself
                      wearing it on our winter getaway for
                      breakfast or on a walk. I'm not sure how
                      see through it is. I think I could get
                      away wearing it as a dress. The length
                      is great, not too short. The quality is
                      great. I got a size S. Fits true to size.
                      I am usually a size 2, 34b, 129lb, slim
                      build. Very happy with this.

 4   Jennifer         Love this hat! Kept the sun off my face
                      and neck/chest in the intense tropical
                      sun! Choose white - so I stayed cool.

 5   Alex             What I like about bikinis is that they
                      always fit you perfectly. You won't
                      realize how gorgeous they are and how
                      attractive they make your body look
                      until you put one on. As for the bra-part
                      it gives good support and sits well. I
                      also like the fabric: it stretches well
                      without losing its shape, the color
                      doesn't fade. This bikini is no exception.
                      is far better at making bikinis than
                      anybody else, I would say!

For this string I just to know what the overall sentiment score is... thanks!!
2.)
"Parents need to know that Harry Potter and the Sorcerer's Stone is a thrill-a-minute story, the first in J.K. Rowling's Harry Potter series. It respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. It's the lightest in the series, but it still has some scary stuff for sensitive readers: a three-headed dog, an attacking troll, a violent life-size chess board, a hooded figure over a dead and bleeding unicorn, as well as a discussion of how Harry's parents died years ago."

A: Please keep in mind for any further questions that stackoverflow is not a code writting service and you should always provide some code you have tried by yourself.
TextBlob is a python package which has a sentiment analysis and returns you a polarity and subjectivity of a given text. To apply this sentiment analysis function to your dataframe you need to use the corrospondent function apply.
Have a look at the example below:
import pandas as pd
from textblob import TextBlob

df = pd.DataFrame([['1',   'Jack',    "Beautiful cover up. My only feedback is that it is a tad larger than expected, but since it's a cover up, it doesn't need to be fitted. The waist tassels also allow you to adjust to fit your waist which is nice. Otherwise, its exactly as expected!"],
['2',   'Rachel',  "This tunic is very cute in person. It's more sheer than I'd like, but I imagine I'll wear it a ton on vacation."],
['3',   'Ryan',    "Just got this sweet little dress in blue. It's a great little dress for a pool cover up. I can envision myself wearing it on our winter getaway for breakfast or on a walk. I'm not sure how see through it is. I think I could get away wearing it as a dress. The length is great, not too short. The quality is great. I got a size S. Fits true to size. I am usually a size 2, 34b, 129lb, slim build. Very happy with this."],
['4',   'Jennifer',    "Love this hat! Kept the sun off my face and neck/chest in the intense tropical sun! Choose white - so I stayed cool."],
['5',   'Alex',   "What I like about bikinis is that they always fit you perfectly. You won't realize how gorgeous they are and how attractive they make your body look until you put one on. As for the bra-part it gives good support and sits well. I also like the fabric: it stretches well without losing its shape, the color doesn't fade. This bikini is no exception. is far better at making bikinis than anybody else, I would say!"]], columns=['ID',  'CustomerName',   'Review'] )

df['sent'] = df['Review'].apply(lambda x:  TextBlob(x).sentiment)
#you can get the polarity and subjectivty values in separate columns by splitting
df['polarity'] =  df['sent'].str[0]
df['subjectivity'] =  df['sent'].str[1]

Regarding your second question, just execute the following:
TextBlob("Parents need to know that Harry Potter and the Sorcerer's Stone is a thrill-a-minute story, the first in J.K. Rowling's Harry Potter series. It respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. It's the lightest in the series, but it still has some scary stuff for sensitive readers: a three-headed dog, an attacking troll, a violent life-size chess board, a hooded figure over a dead and bleeding unicorn, as well as a discussion of how Harry's parents died years ago.").sentiment

A: Hi I have made a similar project on this in java as well as javascript

*

*you can run it "https://sentimentanalyservibhor.000webhostapp.com/"

*git repo: just extract and run index.html
https://github.com/dev-vibhor/SentimentAnalysis_JavaScript/blob/master/SentimentAnalysisJS.zip

*for analyzing different fields I have used n-gram algorithm
   "https://sentimentanalyservibhor.000webhostapp.com/ngram.html"

*ngram git repo :
https://github.com/dev-vibhor/SentimentAnalysis_JavaScript/blob/master/index.html
Bi Gram Implementation using JavaScript (N-GRAM)

N-grams of texts are extensively used in text mining and natural language processing tasks. They are basically a set of co-occurring  words within a given window and when computing the n-grams you typically move one word forward (although you can move X words forward in more advanced scenarios). For example, for the sentence "The cow jumps over the moon". If N=2 (known as bi-grams), then the n-grams would be:

the cow
  cow jumps
  jumps over
  over the
  the moon

for example:
text= the hotel food was good
If N=3(TRI-GRAM) and keyword== food
I will get a result as

*

*the hotel food  : neutral , discard it

*food was good   : positive

the overall sentiment of keyword 'food'=positive
youtube: https://www.youtube.com/watch?v=qMe8wB8sOds
mail: vibsin95@outlook.com


text:
Q: Typo3 Content-objet HTML doesn't display I'm beginner in typoscript, I understand the principle, but I have a small problem from the start.
On my homepage in the setup field of the template-tools, if I put:
page.10 = TEXT
page.10.value = Hello World

It works, I have my display,
however, if I put:
page.10 = HTML
page.10.value = Hello World

it does not show me the text anymore ...
What do not I understand?
page = PAGE
page.typeNum = 0

page.10 = HTML
page.10.value = Hello World

A: Since TYPO3 6.0 there no longer is a HTML object in typoscript. So there is no rendering.
Try to avoid examples from very old days as TYPO3 has changed a lot.
You could look for typoscript errors in the TSOB (TypoScript Object Browser) or Template Analyzer
(see: Web -> Templates -> ... drop down selection on top of page)

A: As mentioned above, the HTML Content object has gone.
Valid solution: just use the TEXT object for such HTML output.
Note the stdWrap.htmlspecialchars thing.
(Read more: https://docs.typo3.org/m/typo3/reference-typoscript/master/en-us/Functions/Stdwrap.html#htmlspecialchars)
If you use both in connection correctly, it is a save and recommended way.
Although maybe HTML output should sit better in a FLUID template or partial.
But still there are some usecases for our approach.


text:
Q: Find missing data indices using python What is the optimum way to return indices where 1-d array has missing data. The missing data is represented by zeros. The data may be genuinely zero but not missing. We only want to return indices where data is zero for more than or equal to 3 places at a time. For example for array [1,2,3,4,0,1,2,3,0,0,0,1,2,3] the function should only return indices for second segment where there are zeros and not the first instance.
This is actually an interview question :) challenge is to do most effeciently in one line

A: Keep track of the count of zeros in the current run.  Then if a run finishes that has at least three zeros calculate the indexes.
def find_dx_of_missing(a):
    runsize = 3 # 3 or more, change to 4 if your need "more than 3"
    zcount = 0
    for i, n in enumerate(a):
        if n == 0:
            zcount += 1
        else:
            if zcount >= runsize:
                for j in range(i - zcount, i):
                    yield j
            zcount = 0
    if zcount >= runsize: # needed if sequence ends with missing
        i += 1
        for j in range(i - zcount, i):
            yield j

Examples:
>>> a = [1,2,3,4,0,1,2,3,0,0,0,1,2,3]
>>> list(find_dx_of_missing(a))
[8, 9, 10]

>>> a = [0,0,0,3,0,5,0,0,0,0,10,0,0,0,0,0]
>>> list(find_dx_of_missing(a))
[0, 1, 2, 6, 7, 8, 9, 11, 12, 13, 14, 15]

Edit: Since you need a one liner here are two candidates assuming a is your list and n is the smallest run of zeros that count as missing data:
[v for vals in (list(vals) for iszeros, vals in itertools.groupby(xrange(len(a)), lambda dx, a=a: a[dx]==0) if iszeros) for v in vals if len(vals) >= n]

Or
sorted({dx for i in xrange(len(a)-n+1) for dx in xrange(i, i+n) if set(a[i:i+n]) == {0}})


text:
Q: How can I pass arguments to Module without being reinterpreted each time they appear inside it? I'm trying to understand how to save time when calling functions in Mathematica. I wrote this example,
mat1 = RandomInteger[{-100, +100}, {200, 200}];
mat2 = RandomInteger[{-100, +100}, {200, 200}];
Timing[Inverse[mat1]][[1]]
matrixOp1[mat_?MatrixQ] := Module[{lm = mat}, lm + mat2]
Timing[matrixOp1[Inverse[mat1]]][[1]]
matrixOp2[mat_?MatrixQ] := Module[{lm = mat}, lm + lm]
Timing[matrixOp2[Inverse[mat1]]][[1]]

I thought that since module uses local vars, matrixOp2 will work at the same speed as matrixOp1. But this is what I found - the output is as such
Out[134]= 0.0312002
Out[136]= 0.0780005
Out[138]= 0.764405

It looks to me like the Inverse operation occurs many times inside matrixOp2 and I don't understand why. Can anyone please explain?
Thanks
Tamir

A: Fred's answer explains why Timing is a poor indicator of how much internal computation is taking place. This is an extended comment to point out that the real timing differences you see are just due to the different arithmetic problem in each case.
Note that the inverse of your integer matrix is a matrix of rationals with large numerators and denominators. Mathematica can add integer + rational faster than it can add rational + rational. Here's a simplified version of your code without any Modules:
lm = Inverse @ RandomInteger[{-100, +100}, {200, 200}];
mat2 = RandomInteger[{-100, +100}, {200, 200}];

AbsoluteTiming[lm + mat2][[1]]
(* 0.0290076 *)

AbsoluteTiming[lm + lm][[1]]
(* 1.12371 *)

So you can see that the difference between matrixOp1 and matrixOp2 is nothing to do with global vs local symbols, but simply that matrixOp1 is doing a faster operation (adding rationals and integers) than matrixOp2 (adding rationals and rationals)

A: It seems to me that your results have to do more with strange behaviour of Timing than with Module. See the answers on my question here for more information. In absolute timings, the results are as expected. I included also Nasser's modification.
Here are the definitions:
mat1=RandomInteger[{-100,+100},{200,200}];
mat2=RandomInteger[{-100,+100},{200,200}];
matrixOp1[mat_?MatrixQ]:=Module[{lm=mat},lm+mat2]
matrixOp2[mat_?MatrixQ]:=Module[{lm=mat},lm+lm]
matrixOp3[mat_?MatrixQ]:=Module[{lm=mat},2 lm]

And here my results:
Timing[Inverse[mat1]][[1]]// AbsoluteTiming
(* {5.65742,0.0312002} *)

Timing[matrixOp1[Inverse[mat1]]][[1]] // AbsoluteTiming
(* {5.71078,0.0624004} *)

Timing[matrixOp2[Inverse[mat1]]][[1]] // AbsoluteTiming
(* {7.002,1.37281} *)

Timing[matrixOp3[Inverse[mat1]]][[1]] // AbsoluteTiming
(* {5.83677,0.109201} *)

The big difference between Timing and AbsoluteTiming is at least remarkable.


text:
Q: $safeprojectname$ isn't safe within the IWizard.RunStarted method I've implemented the IWizard interface and I want to get $safeprojectname$. So, I use the following code:
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
    var safeProjectName = replacementsDictionary["$safeprojectname$"];
}

But in this case safeProjectName is a string that contains spec symbols like -, + etc. For example, if a user set project name as My-Project-1 $safeprojectname$ will be My-Project-1. I expect My_Project_1.
Should I replace all unsafe symbols manually?
According this article it should work without any manipulation, but it doesn't:

safeitemname - The name provided by the user in the Add New Item dialog box, with all unsafe characters and spaces removed.

PS:
Reproduces in VS Professional 2015 and VS Professional 2017.

A:
For example, is a user set project name as My-Project-1 $safeprojectname$ will be My-Project-1. I expect My_Project_1.

You could replace '-' to '_', like this:
 var safeProjectName = replacementsDictionary["$safeprojectname$"];

 replacementsDictionary["$safeprojectname$"] = replacementsDictionary ["$safeprojectname$"].Replace("-", "_");


text:
Q: Auto-covariance in a stationary time series I am trying to calculate the auto-covariance of time series $Z_t$. Given  a weakly stationary process $Y_t$; $t \in \mathbb{Z}$: $$Z_t=a+Y_t$$ Now, my goal is to show that $Z_t$ is also a stationary process. I know that $\mathbb{E}[Y_t]$ should be constant, and it is, $\mathbb{E}[Y_t] = a + m$. Then, I need to prove that the auto-covariance $\newcommand{\cov}{\rm Cov} \cov(Z_t, Z_{t+h})$ depends only on $h$.
I am trying to prove it by calculating the covariance as: $$\cov(Z_t, Z_{t+h}) =\mathbb{E}[Z_tZ_{t+h}] - (m+a)^2$$ but I am not getting anywhere. I am not sure what should I show.
I hope I was clear. If you have any insight please let me know.

A: I assume your goal is to show that $Z_t$ is also a weakly stationary process.
First, you showed ${Z_t}$ has a constant mean:
$$
\mu(Z) = E(Z_t) = E(a + Y_t) = a + E(Y_t) = a + \mu(Y),
$$
where $\mu(Y)$ is constant given that $Y_t$ is weakly stationary.
Then, you show that $\gamma_k(Z)$ the covariance the process of ${Z_t}$ only depends on the lag $h$, and not on time $t$:
$$
\gamma_h(Z) = cov(Z_t, Z_{t+h}) = cov(a + Y_t, a + Y_{t+h}) = cov(a, a) + cov(a, Y_{t+h}) + cov(Y_t, a) + cov(Y_t, Y_{t+h}) = cov(Y_t, Y_{t+h}) = \gamma_h(Y),
$$
where the last equality is true given that $Y_t$ is weakly stationary.
I believe the answer is complete, unless somebody can point out something missed out.


text:
Q: Point subdomain without changing parent domain can anyone help me how to solve this problem.
So I bough domain www.example.com , what I want to create next is to "point" demo.example.com via ROUTE 53 without touching parent domain DNS ( because parent domain will be hosted on another hosting)
So far I try to create new hosted zone and I add host record (A ) and put public ip address of my instance but nothing happens.Can anyone suggest me what to do  ?


text:
Q: What is the number of ring isomorphisms from $\mathbb{Z}^n$ to $\mathbb{Z}^n$. Yesterday, I faced the problem : what is the number of ring isomorphisms from $\mathbb{Z}^2$ to $\mathbb{Z}^2$. And I got $6$. After then, I found that if $n=3$, the number is $3! \times 29$. Suddenly, I wondered what is the number of isomorphisms from $\mathbb{Z}^n$ to $\mathbb{Z}^n$. I have tried to solve it but failed. What's more, I couldn't find any answers about that on google. Is it easy to solve? I tried to solve the problem by using recursive relation. But it looks difficult.
One of my friends gave me a suggestion to find the number of $n \times n$ invertible matrices with components $1$ or $0$. At first, we thought that it is exactly $(2^n-1)(2^n-2) \dots (2^n-2^{n-1})$. But this equation doesn't work because the construction of the equation discards some cases. For example, $n=3$, the equation discards $ (\begin{smallmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1 \end{smallmatrix} )$. The equation only works on a finite field. I found that it is a lower bound and upper bound $((n+1)!)^2 2^\frac{n(n+1)}{2}$ by a recursive relation. But I don't know until now what is the exact number of that.
+
Due to Perter Franek, I solved it. The answer is $n!$.
Idempotent elements should go idempotent elements and if $\phi$ is an isomorhpism, then $\phi(0)$ implies $0$. The candidates of $e_i=(\delta_{ij})_j$ are each or sum of $\{e_i\}$'s. But if some $e_i$ goes to sum of $e_i's$, $0=\phi(e_i e_j)= \phi(e_i) \phi(e_j) \not =0$ for some $i \not = j$.

A:
One of my friends gave me a suggestion to find the number of $n×n$ invertible matrices with components $1$ or $0$.

This is OEIS A055165; there appears to be no simple formula for it.

A: Any ring homomorphism $\phi$ sends idempotents (elements $e$ satisfying $e^2=1$) to idempotents. The idempotents of $\mathbb{Z}^n$ are the vectors with coordinates all $0$ or $1$. These correspond to subsets of $\{1,\cdots,n\}$ (to describe where the $1$s occur in the coordinates). Thus, if $e_1,\cdots,e_n$ refer to the standard basis vectors of $\mathbb{Z}^n$, there are subsets $A_1,\cdots,A_n\subset\{1,\cdots,n\}$ for which
$$ \phi(e_i)=\sum_{a\in A_{\Large i}}e_a. $$
Moreover, ring homomorphisms preserve zero division. That is, $e_ie_j=0$ (when $i\ne j$) implies
$$ 0=\phi(e_i)\phi(e_j)=\Big(\sum_{a\in A_{\Large i}}e_a\Big)\Big(\sum_{b\in A_{\Large j}} e_{b}\Big)=\sum_{c\in A_{\Large i}\cap A_{\Large j}}e_c.  $$
This implies the $A_1,\cdots,A_n$ are disjoint. They must be nonempty, else $\phi$ would have a kernel, so
$$ n=1+\cdots+1\le |A_1|+\cdots+|A_n|=|A_1\cup\cdots\cup A_n|\le n. $$
The only way this inequality is squeezed so tightly is if $|A_i|=1$ for each $i$. Thus, $\phi$ simply permutes the standard basis vectors $e_1,\cdots,e_n$, and there are $n!$ such permutations!


text:
Q: How to add a link to view history How do I add to the tables that I create this link "history" to display the history. According to this picture.
https://i.gyazo.com/a1671799cccfe5334ba918ec4c0fdb90.png
I wish I could add this same link to my tables.

A: Like this, just the style is different. I tried to change the style, but this didn't work.Hope its help you.enter image description here
Note: Its only use in view recordMode,not applicable edit/create mode
There are two points:
1: Add lineField type is inline HTML;enter image description here
2: Using userevent script (beforeLoad Fun) to set the href,like this

for (var i = 0; i < linenum; i++) {
    var url = "you want link";
    var url_href = "history";
    recObj.setLineItemValue('item', 'fieldId', i + 1, url_href);
}


text:
Q: Find Affine transformation matrix between two Shapes(SVG Paths) I have two Shapes, each defined as a single SVG Path. I want to find if Shape A is an Affine Transform of Shape B and also compute/find the Affine transform matrix.
My current approach computes the consecutive Angles between off curve and on curve points to find if they are transformed shapes. This works for translate,scale,rotate operations. But does not work for sheared Shapes.
Any proper mathematical approaches are available?

A: You can find matrix of affine transform between any triplet of non-collinear points P1,P2,P3 and their translated twins P1',P2',P3'
A * P = P'

   |x1  x2  x3|    |x1' x2' x3'|
A *|y1  y2  y3| =  |y1' y2' y3'|
   |1   1   1 |    |1   1    1 |

To calculate A, it is needed to multiply both sides by inverse of P matrix
A * P * P-1 = P' * P-1
A * E = P' * P-1
A = P' * P-1
Then check that the same A works for other triplets of points (for random subset or for all points, if possible)
There are sophisticated methods to evaluate affine transform for the whole point cloud, but they are more complex.


text:
Q: How to hide specific table columns on button click using jquery? So here is my code:

          lt

          en

            ID
            Code lt
            Code en
            Value lt
            Value en

                ID
                code1_lt
                code2_en
                value1_lt
                value2_en

So for example when i click on first button i want to hide columns with en (so its the 3rd and 5th ones)
And do same with other button to hide lt columns
Nvm fixed it myself. Thanks all who helped
Here is how i did it:
jQuery(document).on('click', '.button', function(e) {
      var value = jQuery(this).attr('data-value');

      if(value == 'lt')
      {
          jQuery('.lt').show();
          jQuery('.en').hide();
      }

      if(value == 'en')
      {
          jQuery('.en').show();
          jQuery('.lt').hide();
      }

  });

A: Do like this  , this will hide column no 2
  $('#btnid').click(function() {
    $('td:nth-child(2),th:nth-child(2)').hide();
  })

or you can do this assing calss .en and .lt to columns and hide it
      $('#btnlt').click(function() {
        $('.lt').hide();
      })

      $('#btnen').click(function() {
        $('.en').hide();
      })

            ID
            Code lt
            Code en
            Value lt
            Value en

                <?php echo $row->id; ?>
                <?php echo $row->code_lt; ?>
                <?php echo $row->code_en; ?>
                <?php echo $row->value_lt; ?>
                <?php echo $row->value_en; ?>

A: You can use class with index to hide column.

$(".button").on("click", function() {
 $('td').removeClass('ab');
 $('th').removeClass('ab');
  var btn = $(this).val();
  $('table tr th').each(function(index, element) {
    var str = $(this).text();

    if (str.indexOf(btn) !== -1) {
      $(this).addClass('ab');
      $("td:nth-child(" + index + ")").addClass('ab');
    }
  });

});
.ab {
  display: none;
}

  <input type='button' value="lt" class="button" />

  <input type='button' value='en' class="button" />

    ID
    Code lt
    Code en
    Value lt
    Value en

    1
    2
    3
    4
    5


text:
Q: if else statement and dictionary in python I just started programming. I am making a project where I count how many words occur in an article or a novel and the program prints the word and how many times it is repeated in the article. I use dictionaries in the program.
After that, i prompt the user to insert a word and the program will attempt to find how many times that word occurred if any. However, I have a problem with my last else statement.  If the word does not exist, the "print("the word does not exist in the file inserted")" is repeated again and again. How can I solve it so it only is printed once?
Here is my code:
from string import *
import codecs

def removePunctuation(sentence):

    new_sentence = ""
    for char in sentence:
        if char not in punctuation:
            new_sentence = new_sentence + char
    return new_sentence

def wordFrequences(new_sentence):
    wordFreq = {}
    split_sentence = new_sentence.split()
    for word in split_sentence:
        wordFreq[word] = wordFreq.get(word,0) + 1
    wordFreq.items()
    return (wordFreq)

#=====================================================

def main():

    fileName = open("arabic.txt","r")

    #fileName = open("arabic.txt","r",encoding="utf-8")

    new_sentence = removePunctuation(fileName)
    D = wordFrequences(new_sentence)
    #print(D)

    excel = open("file.csv", "w")
    excel.write("words in article" + "\t" + "frequency" + "\n\n")

    for i in D:
        #print(i , D[i])
        excel.write(i + "\t" + str(D[i]) + "\n")

    prompt = input("insert a word for frequency: ")

    found = True
    for key in D:
        if key == prompt:
            print(key, D[key])
            break

        else:
            print("the word does not exist in the file inserted")

main()

A: I should point out that you actually don't need this loop at all. The whole point of a dictionary is that you can look things up by key directly. So:
try:
    print(prompt, D[prompt])
except KeyError:
    print("the word does not exist in the file inserted")

But let's look at how to fix your existing code.
The problem is that you're doing the if/else once for each key in the dictionary, and printing that output every time any key fails to match, instead of only if no key fails to match.
You can fix this by using a for/else instead of an if/else:
for key in D:
    if key == prompt:
        print(key, D[key])
        break

else:
    print("the word does not exist in the file inserted")

This way, the else only triggers if you get through the whole loop without hitting a break, instead of triggering each time through the loop that you don't break.
This is a tricky concept for some people to get at first (especially people coming from other languages that don't have this feature), but the tutorial section break and continue Statements, and else Clauses on Loops explains it pretty well.

Alternatively, you have that Found flag; you could actually use it:
found = False
for key in D:
    if key == prompt:
        print(key, D[key])
        found = True
        break
if not found:
    print("the word does not exist in the file inserted")

However, that's more code, and more places to get something wrong.


text:
Q: Erro em detalhes da ordem em magento Olá. Estou com um erro no magento que não consegui resolver de forma alguma. A página de detalhes da ordem está sendo exibida desta maneira:

Tentei diversas soluções, como substituir o core do magento, alterar permissões e diversas outras soluções, todavia, nada funcionou.
O log de erros:
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 107: parser error : Double hyphen within comment: <!--<catalog_product_view>
        <reference name="pr  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():                 <!--action method="setLogoType"><value>wePrefer_150x60</value></  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():                   ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 108: parser error : Opening and ending tag mismatch: layout line 30 and block  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():             </block>  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():                     ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 109: parser error : Extra content at the end of the document  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():         </reference>  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:54:17+00:00 ERR (3): Warning: simplexml_load_string():         ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 107: parser error : Double hyphen within comment: <!--<catalog_product_view>
        <reference name="pr  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():                 <!--action method="setLogoType"><value>wePrefer_150x60</value></  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():                   ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 108: parser error : Opening and ending tag mismatch: layout line 30 and block  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():             </block>  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():                     ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string(): Entity: line 109: parser error : Extra content at the end of the document  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():         </reference>  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
2017-02-17T13:56:41+00:00 ERR (3): Warning: simplexml_load_string():         ^  in /home/site/public_html/app/code/core/Mage/Core/Model/Layout/Update.php on line 450
Como devo proceder para solucionar este problema?


text:
Q: Python - Error populating values to spreadsheet (using xlsxwriter) I have pulled some data from a xml file that looks as below:
Parent

Child

Action
new

ID
54467

Type
None

Group

Name
None

ID
ab

COMMENTS

HTRER

REMARKS
LKO

CUSTOMER
HELLO

In the above sample, the first row represent the header while the row below that represents the corresponding value. I am trying to have these written to a spreadsheet such that each header is written on first row with the corresponding value in the subsequent row. I am trying to do that using the code below but see that some of the values do not get written.
Given below is the code I am using to write it to a spreadsheet using xlsxwriter:
row = 0
col = 0
row1 = 1
col1 = 0

for elem in tree.iter():
    worksheet.write(row, col, elem.tag)
    for subelem in elem:
        worksheet.write(row1, col1, subelem.text)
col +=1

Could anyone advice as to why the values are not getting correctly or does the code above needs some edit. Thanks


text:
Q: Parametrize a surface involving the intersection of a cylinder and a plane. In the question below, I am trying to understand how $S$ is a the graph of a function of two variables so that it can be parametrized $f(x,y) = (x,y,z(x,y))$. Note on the picture below, formula 1 is the dot product of a vector field with a parametrized surface, parametrized as in $f$ above.

A: The points in the solid cylinder can be written as $(r\cos(\theta), r\sin(\theta), z)$ for $r\in [0, 1]$, $\theta\in \mathbb{R}/2\pi\mathbb{Z}$, and $z\in \mathbb{R}$. The points in the plane are exactly the points $(x, y, z)$ that satisfy $z = 1-x-y$. Therefore, the surface of intersection can be parametrized as $$S : [0, 1]\times \mathbb{R}/2\pi\mathbb{Z}\to \mathbb{R}^3, (r, \theta)\mapsto (r\cos(\theta), r\sin(\theta), 1-r(\cos(\theta)+\sin(\theta)))$$


text:
Q: PHP unix timestamp compare I have an event date & time stored in my database that is being saved as a PHP unix timestamp. Im trying to check if today is greater than the event date and time.
The problem is - i'm trying to check it using local time (America/New_York), but im getting 2 different time zones. time() is displaying in EST and my database is displaying in UTC
Is there any way to check it correctly?
My Event Date from database:
1450447200 (December 18, 2015 2:00pm)
Im trying to compare it with php time()
am I maybe doing this wrong?
*UPDATE - ANSWER*
as per this answer I ended up doing this:
$utc_str = gmdate("M d Y H:i:s", time());
$today = strtotime($utc_str);

$event_datetime = $Event_timestamp;
date_default_timezone_set("America/New_York");
$utc_str_event = gmdate("M d Y H:i:s", $event_datetime);
$event_date = strtotime($utc_str_event);
if($today >= $event_date){
    //Do Something
}

A: You probably have wrong date on server(s). time() always should return epoch (epoch = UTC).
btw. saving date as int on database it isn't best practice

A: I don't know if this is correct but have you tried using date_default_timezone_set


text:
Q: How to replace string in all project with Visual Studio Code? I would like to replace one string with another in the whole project but I can't find anywhere how to enable the replace option in VSC (Visual Studio Code). Could someone tell me how I can enable this option?

A: I found it!
The command is Ctrl + Shift + H (ir in Edit>Replace in files)


text:
Q: Gridview Button Adapter context menu I have a phrasebook, with the ability to save the sample to SD. I use a Gridview set up with the following code in place for the button adapter:
public View getView(int position, View convertView, ViewGroup parent) {
    try {
        final Sample sample = board.getSamples().get(position);

        if (sample != null) {

            Button button = new Button(context);
            button.setText(sample.getName());
            button.setTextColor(Color.WHITE);
            button.setTextSize(12);
            button.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    context.play(sample);
                }

            });

            // TODO Implement this correctly.
             button.setOnLongClickListener(new OnLongClickListener() {
             public boolean onLongClick(View v) {

             return context.saveToSD(sample);

             }
             });

            return button;
        }
    } catch (IndexOutOfBoundsException e) {
        Log.e(getClass().getCanonicalName(), "No sample at position "
                + position);
    }

    return null;
}

I am looking to integrate a context menu here on a Long press, to give the option of where to save the sample. I don't seem to be able to register the button for the context menu within this method (ie registerForContextMenu(button), as it gives me errors.
I am a bit stumped here, any pointers would be a great help.
Thanks

A: I take it that this is an old post but I came across it today as I was looking for an answer on the same topic. Like the question here I have a grid of items and wanted to show a context menu on long click.
I am not using a contextmenu but instead I am using an AlertDialog.
gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id)
        {
            showOptionsMenu(position);
            return true;
        }

    });

public void showOptionsMenu(int position)
{
    new AlertDialog.Builder(this)
    .setTitle("test").setCancelable(true).setItems(R.array.myOptions,
              new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialoginterface, int i) {
                       //take actions here according to what the user has selected
                   }
             }
    )
.show();
}

Hope this helps.


text:
Q: Angular get dynamically created DOM Element I am creating a Video Element in Angular and attaching it to the DOM. I may add multiple videos to the DOM. However trying to retreive this element is proving difficult.
The Element is created as follows:
    const idObject = Math.round(Math.random() * 1000);
    const canvas =  this.canvasComponent.activeCanvas;
    const url = vid.src;
    const videoE = this.canvasRenderer.createElement('video') as HTMLVideoElement;
    videoE.width = vid.videoWidth;
    videoE.height = vid.videoHeight;
    videoE.crossOrigin = 'anonymous';
    videoE.controls = true;
    videoE.id = idObject.toString();
    videoE.hidden = true;
    const source = this.canvasRenderer.createElement('source') as HTMLSourceElement;
    source.src = url;
    source.type = 'video/webm';
    videoE.appendChild(source);

    this.canvasRenderer.appendChild(this.elem.nativeElement, videoE);

canvasRenderer is angular component Renderer2
I can easily retreive the elemnt using
   document.getElementById(elementid)

I cannot access the element with Renderer2, ElementRef or ViewChild. These seem to require the jquery selector(#) to be present.
Is it good prcatice to use 'document.getElementById' in Angular ?
Is it possible to add jquery selector to the element being created?
Is there another way to get the desired DOM element by id?


text:
Q: Python condition with regex I have a file with those data :
PAS_BEGIN_0009999
    T71_MANUFACTURER_4=98
    T71_COLOR_ID_7=000
    T71_OS_7=08
PAS_END_0009999

PAS_BEGIN_0009996
    T72_VAS_SERVICE_IDENTIFIER_6=
    T72_ORDER_NB_7=0003
    T72_TECHNOLOGY_7=01
PAS_END_0009996

TPV_BEGIN
    PAS_20819001=3600000
TPV_END

How can I simply isolate content betweenPAS_BEGIN_0009996 and PAS_BEGIN_0009996
Here is a link for the example : https://regexr.com/3vmeq
It finds something, but my python code doesn't find anything..
if re.match("PAS_BEGIN_0009999([\S\s]*)PAS_END_0009999", line):
    data.append(line)
    print(line)

Can anyone help me on this ? Thanks

A: You are reading a text file line by line, but your expected match is located on several lines. You need to read the whole file into a variable, then run a regex like yours, or, better, a pattern like a.*?b with re.DOTALL option so that . could match line break chars.
So, you may use something like
import re
fpath = 'your_file_path.txt'
data = ''
pattern=r'PAS_BEGIN_0009999(.*?)PAS_END_0009999'
with open(filepath, "r") as f:
    contents = f.read()
    m = re.search(pattern, contents)
    if m:
        data = m.group(1) # or `.group() if you need to include PAS_BEGIN_0009999 and PAS_END_0009999

If you need to find multiple occurrences, replace the re.search part (all lines after contents) with
data = re.findall(pattern, contents)

See the regex demo


text:
Q: How to update field in database from controller I have a user who must complete a field without to be logged in. The field is a email_field.
The database have two field : user email and a user_id the user_id is received it from a webhook so I need to update the field in my database after receiving the information from the webhook.
Here is my controller to insert data in my user email in my database :
class EmailsController < ApplicationController
  def index
    redirect_to root_path
  end

  def new
    @email = Email.new
  end

  def create
    @email = Email.create(email_params)
    respond_to do |format|
      if@email.persisted?
        format.html {redirect_to invoice_index_path, notice: 'Email created '}
      else
        format.html{render :new}
      end
    end
  end

  private

  def email_params
    params.require(:email).permit(:email, :id_user)
  end
end

My controller from where I receive the webhook :
class InvoiceController < ApplicationController
def webhooks
    render status: 200

    user = Email.last
    #id_user that I need to fill in my database
    puts user.user_id.inspect
    #id_user receive from the webhook
    id_user = params.dig('connection', 'id_user')

    if user.user_id == nil
        #POST the id_user in my database
    end
end

Here is my question, how can I update the file from user.user_id with the id_user ?

A: And the correct answer is :
user.update_attribute :user_id, params.dig('connection', 'id_user')

A: Adding this line before your if statement should work, it will update and automatically save the updated record.
user.update_attribute(user_id, id_user)


text:
Q: Append value to c.Json response I want to append a value to the returned response of my code, this is what I already have:
publisherShare := 25 // I also have this variable that want to append to the returned response.
c.JSON(http.StatusOK, nf) // nf is a row found and returned from database.

This returns such json:
{
    "id": 105324,
    "title": "test title",
    "last_update": "2021-03-10T12:50:37+03:30",
    "created_at": "2021-03-10T12:50:36+03:30",
    "updated_at": "2021-05-05T05:46:39.352859604Z"
}

I need to have a json result like this:
{
    "id": 105324,
    "title": "test title",
    "last_update": "2021-03-10T12:50:37+03:30",
    "created_at": "2021-03-10T12:50:36+03:30",
    "updated_at": "2021-05-05T05:46:39.352859604Z",
    "publisher_share": 25 // I want this to be added.
}

This is what I have tried so far, but it changes the schema and will not be backward compatible anymore:
c.Json(http.StatusOK, gin.H{"book": nf, "publisher_share": publisherShare})

but this is not the json result I want. I want publisher_share alongside other fields just like the json result I mentioned above.

A: You can add publisher share to the same type as
type nfType struct {
    // All of the db row fields
    PublisherShare int `json:"publisher_share,omitempty" db:"-"`
}

A: Simply create a struct that matches the structure of your json responce. Key is to add aditional fild to it like
type Responce struct {
   // other fields. They have to be written in same way to keep conventions
   // (Go-ish name and needed name as tag)
   PublisherShare int `json:"publisher_share"`
}

Then when you handle responce you can just unmarshal and marshal json.
responce := Responce{PublisherShare: 25}
err := json.Unmarshal(bytes, &responce)
if err != nil {
  //handle error
}
newResponce, err := jsom.Marshal(responce)
if err != nil {
  //handle error
}
// newResponce is now in form you want

A: Define a new type. It embeds the type of the db row, and it has a field for the extra value. E.G: if the type of the db row is DatabaseRow:
type CompleteReturn struct {
    DatabaseRow
    PublisherShare int `json:"publisher_share"`
}

Later use it as:
complete := CompleteReturn{
    DatabaseRow:    nf, // Serialize in json as before
    PublisherShare: 25, // Serialize in json as publisher_share
}
c.Json(http.StatusOk, complete)


text:
Q: java.lang.NoClassDefFoundError:org/springframework/web/util/UriTemplateHandler I have a basic SpringBoot application that I created using Spring Initializer. When I try to start the SpringBoot server( using the maven plugin (spring-boot:start) it gives the below error.

java.lang.NoClassDefFoundError:
  org/springframework/web/util/UriTemplateHandler   at
  java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.8.0_60]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
  ~[na:1.8.0_60]    at
  java.lang.Class.getDeclaredConstructors(Class.java:2020)
  ~[na:1.8.0_60]    at
  org.springframework.boot.context.properties.ConfigurationPropertiesBindConstructorProvider.findConstructorBindingAnnotatedConstructor(ConfigurationPropertiesBindConstructorProvider.java:62)
  ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]    at
  org.springframework.boot.context.properties.ConfigurationPropertiesBindConstructorProvider.getBindConstructor(ConfigurationPropertiesBindConstructorProvider.java:48)
  ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]    at
  org.springframework.boot.context.properties.ConfigurationPropertiesBean$BindMethod.forType(ConfigurationPropertiesBean.java:311)
  ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]    at
  org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.validate(ConfigurationPropertiesBeanDefinitionValidator.java:63)
  ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]    at
  org.springframework.boot.context.properties.ConfigurationPropertiesBeanDefinitionValidator.postProcessBeanFactory(ConfigurationPropertiesBeanDefinitionValidator.java:45)
  ~[spring-boot-2.2.4.RELEASE.jar:2.2.4.RELEASE]    at
  org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286)
  ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]     at
  org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:174)
  ~[spring-context-5.2.3.RELEASE.jar:5.2.3.RELEASE]

Here is is my pom file.
    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.cgtm</groupId>
    <artifactId>validator</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>validator</name>
    <description>Validator</description>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

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

</project>

Application.java file
 package com.cgtm.validator;

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

@SpringBootApplication
public class ValidatorApplication {

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

}

A: Spring boot is of version 2.2.4 it requires Spring 5 (basically it comes with a predefined version of spring
On the other hand you're using "hardcoded" spring web 4.1.4 which is wrong:
 <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.6.RELEASE</version>
 </dependency>

You should be using instead of that:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Make sure you don't have any of spring 4.x dependencies on your path (by running mvn dependency:tree)
In addition, you don't need to place:
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
  </dependency>

And one last thing, you're using lombok which is fine of course (I mean spring can play nicely with lombok), but spring boot maven plugin will still package it into the artifact despite the provided scope. If you wish to exclude it from the final artifact, you'll have to configure the spring boot maven plugin itself to do so.
Read this SO thread for more information


text:
Q: How to differentiate between auto-slide and click slide Bootstrap carousel? I have carousel control buttons that I am adding an active class to when a new slide is selected.
This is a simple task when someone clicks on one of these buttons, but if I want to incorporate autoplay, this suddenly becomes much more challenging.
Here is the problem:
I can bind slid to a function that adds the active class to my control buttons, and it will be functional, BUT there will be a delay between the start of the slide and the addition of the active class, because slid is fired when the slide is complete.
Fortunately, Bootstrap provides slide, which is fired when a slide is initiated. I could bind slide to a function that adds the active class to the next slide in the list, but then this would cause problems when I try to click a control button for a slide that is out of order.
slide is fired whenever a slide happens, so if someone clicks on a control button that is not in the normal slide order, I will end up with two active buttons.
The only solution I can see currently, is to somehow differentiate between a slide event that is automatically triggered, and one that is triggered by a click.
Any ideas?

A: Try this:
  $('.carousel').carousel({
  interval: 2000
});


text:
Q: How to tell mex to link with the libstdc++.so.6 in /usr/lib instead of the one in the MATLAB directory? Now mex in MATLAB 2012a only officially supports gcc 4.4.6 but I want to use gcc 4.7 at my own risk. Now If I compile something with mex directly, it will complain that
/usr/lib/gcc/i686-linux-gnu/4.7/cc1plus:
/usr/local/MATLAB/R2012a/sys/os/glnx86/libstdc++.so.6:
version `GLIBCXX_3.4.15' not found
(required by /usr/lib/i386-linux-gnu/libppl_c.so.4)

/usr/lib/gcc/i686-linux-gnu/4.7/cc1plus:
/usr/local/MATLAB/R2012a/sys/os/glnx86/libstdc++.so.6:
version `GLIBCXX_3.4.15' not found
(required by /usr/lib/i386-linux-gnu/libppl.so.9)

By strings /usr/lib/i386-linux-gnu/libstdc++.so.6 | grep 'GLIBCXX' I confirm that this libstdc++.so.6 has that version string. I reviewed mexopts.sh and modified the variable $RPATH and $MLIBS in that script, but it doesn't work. So if I don't use symbolic link, where can I config the path of the libstdc++.so.6 that mex uses? Thank you.

A: It's a late answer, but I believe the cleanest, most Mathworks-approved and least invasive solution is to edit the .matlab7rc.sh script. This is a script used by the matlab script when you start MATLAB under UNIX-like systems. (See http://www.mathworks.ch/ch/help/matlab/ref/matlabunix.html)
Copy that script (found under {matlabroot}/bin) to the root of your project, or to your home directory. Then tell MATLAB to first search in the system directories for the C++ libraries, instead of its own directories. On my system I changed line 191:
191c191
<       LDPATH_PREFIX='/usr/lib/x86_64-linux-gnu'
---
>       LDPATH_PREFIX=''

(Simply setting LD_LIBRARY_PATH to the empty string is not a good solution, because that will prevent you from loading other third-party libraries.)
When this is done you might get the following message when running mex:
/usr/bin/ld: cannot find -lstdc++

This usually means that g++ is not installed. On a Debian-like system, run:
sudo apt-get install g++

From here on, you might still get an annoying warning about using a version of gcc beyond what is officially supported, but that is harmless and can be ignored.

A: i tried both the answers.. but none worked for me.
however this worked for me. in matlab run this -
setenv('LD_LIBRARY_PATH', '');

just for anyone who is facing the same problem.
P.S: I found this solution here

A: You can modify ~/.matlab/R2012a/mexopts.sh that generated after doing mex -setup by adding a line in glnx86 section:
LD_LIBRARY_PATH='/usr/lib:$LD_LIBRARY_PATH'

or in glnx64:
LD_LIBRARY_PATH='/usr/lib64:$LD_LIBRARY_PATH'

A:
/usr/lib/gcc/i686-linux-gnu/4.7/cc1plus: /usr/local/MATLAB/R2012a/sys/os/glnx86/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

The problem is that when you are building with mex, it puts -L/usr/local/MATLAB/R2012a/sys/os/glnx86 on the link line, and so the linker picks up libstdc++.so from there.
If you can't convince mex to prepend -L/usr/lib/i386-linux-gnu first, then I think your only other choice is to remove /usr/local/MATLAB/R2012a/sys/os/glnx86/libstdc++.so (just rename it to e.g. libstdc++.so.bak).

A: You need to create a symbolic link to the gcc 4.7 library so matlab knows to use it. Something like:
ln -s {/path/to/file-name} {link-name}

If you don't want to use symbolic links, then just define this path in a terminal from which you launch matlab:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/libstdc++.so.6
./matlab

A: If you don't have root access then you can try,
LD_PRELOAD='path/to/libstdc++.so.6.0.21' matlab

A: I was not able to find where my libstdc++.so.6 is, so I was not able to fully test the solution given by geek_girl. However, a modification of th1rdey3's worked. I ran in the matlab console:
setenv('LD_LIBRARY_PATH', 'usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64/server:/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/amd64:/usr/local/MATLAB/R2011a/bin/glnxa64:/usr/lib/boost_1_54_0/libs/regex/build/gcc');

This is the value I use for 'LD_LIBRARY_PATH' when compiling my C++ code in Eclipse (I am not using mex files, instead I create an executable of my C++ code in Eclipse and later run it from matlab shell). In my case the value of 'LD_LIBRARY_PATH' is that long because my C++ code uses boost's regex, matlab libraries (libmat, libmx and so on), GSL library and Armadillo. If you don't use all these libraries, setenv('LD_LIBRARY_PATH','') should be enough, I guess.

A: On Matlab R2015b, I first relinked libstdc++.so.6 and then edited .matlab7rc.sh as described above by @lindelof. On my desktop, from terminal:
locate libstdc++.so.6

In my case, the system library is located in /usr/lib64. Then
cd /usr/local/matlab/sys/os/glnxa64
mv libstdc++.so.6 libstdc++.so.6.bak
ln -s /usr/lib64/libstc++.so.6 libstc++.so.6
cd /usr/local/src/matlab/bin/glnxa64/
mv libstdc++.so.6 libstdc++.so.6.bak
ln -s /usr/lib64/libstc++.so.6 libstc++.so.6

Then edit .matlab7rc.sh in {matlabroot}/bin. Delete in the same directory any mexopts.sh file. Restart Matlab. MEX your file from scratch (this will build a new mexopts.sh file with the new settings. Run it from Matlab console.


text:
Q: Cache SQL Update for daily reuse I have a big table with 40 million rows in a Table. I am having to update the entire table because I don't want anything to missed. The Update Command Is being used to get the value from a different table and using this to join on.
Update D
Set D.Key = S.Key
from Activity D with (NOLOCK)
inner Join Account S
on D.ID = S.ID
OPTION (HASH JOIN)

With Activity D being the Big Table 40 million and Account Table S being a 1.2 Million, that's why I have take the HASH Option Join.
Anyways I am having to do this update everyday in an Execute SQL task in my ETL Process,Just wondering since not much gets changed and no index exist to speed in the process up in the table. Is there a way to speed this process up at all, whether there is a way to cache this so everynight its not having to do the whole thing from scratch or would wrapping this in a Stored Proc speed things up rather than just using a SQL Script as I am doing at the moment?
Thank you

A: One simple approach to avoid that UPDATE could be to use a trigger on dbo.Activity table thus:
CREATE TRIGGER trgIU_Activity_UpdateKey
ON dbo.Activity
AFTER INSERT, UPDATE
AS
BEGIN

IF UPDATE(ID)
BEGIN
    UPDATE d
    SET D.Key = S.Key
    FROM dbo.Activity d INNER JOIN dbo.Account s ON d.ID = s.ID
    WHERE d.ID IN (SELECT i.ID FROM inserted i)
END

END

After every INSERT / UPDATE on Activity table, if there are any changes within dbo.Activity.ID column then it will update the Key column.


text:
Q: How can I upload and display file to html I'm trying to upload files to my html and display it, need something like an attachment, I choose my file (image,text,pdf,excel...) and display it.
I have already tried this code but it only show the text name I need something like it but also display content:
<!DOCTYPE html>

Click the button to create a File Upload Button.

<button onclick="myFunction()">Try it</button>

A: Your question isn't really clear, but for uploading a file you need a server-side language
and If you want to show your uploaded file you have to send the file via AJAX to a server-side language (like PHP, Node.js, Python and etc.)

something like this :
<!DOCTYPE html>

<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1">

  <input type="button" value="Upload File" onclick="uploadFile()">

</form>

upload.php :
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
    echo "test_uploads/$fileName";
} else {
    echo "move_uploaded_file function failed";
}

P.s : Styling isn't really great in this example you can append an img tag or something else, It's just an example for you to understand the concept

Hope this helps you

A: I have a resume on my personal site for example, its a PDF document.
I just linked to it with an anchor tag

Resume

Hope this helps. let me know if you have other questions and welcome to StackOverflow

A:

        <input name="file" type="file" id="file"/>


text:
Q: Removing GRUB from windows system after uninstalling Ubuntu from Windows 7 I have installed Ubuntu alongside Windows 7 (no separate partitions, I selected inside windows option).
I want to uninstall Ubuntu but last time I tried it and the Ubuntu is released but the GRUB remains. How do I remove GRUB?

A: *

*Put windows 7 disk and boot from it.

*Choose to repair windows now.

*It will ask to repair, select yes.  After restart if grub is still there, follow above    step.

*Select windows partition found by the recovery manager and click Next

*Now choose startup repair.
This internally uses command fixboot and fixmbr. You can google for more details.

A: You need Windows 7 installation disk, boot it, choose repair option when you are asked to menu.
It will check automatically for start up problems. Let it check it.

*

*It will not find any problem with start up.

*It will allow to choose options. Choose command prompt.

*In cmd you have to type just two following commands and grub will be removed.
bootrec /fixmbr
bootrec /fixboot

Close cmd and restart your machine.

A: Here's how.

*

*Download and burn the Super Grub Disk ISO to a CD.

*Boot from it.

*Select the Choose Language & HELP  :-)) entry.

*Select the English entry.

*Select the Windows entry.

*Select the Fix Boot of Windows entry.

*Reboot once the process is complete.

No more Grub! :)


text:
Q: Django Rest Framework ModelSerializer custom serializer field to_internal_value doesn't save to object I have model and serializer, there is ArrayField(postgres) in that model.
Now I wanted to create a serializer field that will receive list [1,2] and save it to object, but for a list and detail in serializer to show a list of JSON objects.
Model:
class User(models.Model):
    email = models.EmailField('Email', unique=True, blank=False)
    full_name = models.CharField(
        'Full name', max_length=150, blank=True, null=True)
    roles = ArrayField(
        models.PositiveSmallIntegerField(),
        default=list,
        blank=True
    )

Serializer:
class ArraySerializerField(ListField):

    def __init__(self, queryset, serializer_class):
        super(ArraySerializerField, self).__init__()
        self.queryset = queryset
        self.serializer_class = serializer_class

    def to_representation(self, value):
        if value:
            qs = self.queryset.filter(pk__in=value)
            return self.serializer_class(qs, many=True).data

        return []

    def to_internal_value(self, value):
        super(ArraySerializerField, self).to_internal_value(value)
        print(value)  # [1, 2]
        return value

class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = ArraySerializerField(queryset=Role.objects.all(), serializer_class=RoleSerializer)

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        print(validated_data)
        # {'email': 'test@test.com', 'full_name': 'Test', 'roles': []}
        user = super(UserSerializer, self).create(validated_data)

        return user

Now when I do list or detail request, everything is ok, I get a list of roles as JSON.
But when I try to POST data and send with this data:
{
  "email": "test@test.com",
  "full_name": "Test",
  "roles": [1, 2]
}

validated_data in create method shows roles always as [] and object is saved without roles, but print from to_internal_value shows [1, 2].
What am I doing wrong? It should save sent data because to_internal_value works fine.
EDIT:
GET and LIST response gives me right format:
{
  "id": 1,
  "email": "test@test.com",
  "full_name": "Test",
  "roles": [
    {
      "id": 1,
      "name": "Role 1"
    },
    {
      "id": 2,
      "name": "Role 2"
    }
  ]
}

A: Have you tried this?
class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, required=False)

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        # check validated_data here
        ...
Note
I'm not sure about the nature of SerializerExtensionsMixin class here. Also I'm not sure the intention behind the queryset and serializer_class arguments of your custom ListField

Django Shell Output
In [7]: from rest_framework import serializers

In [8]: class UserSerializer(serializers.Serializer):  # Created a simple serializer without model
   ...:     roles = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, required=False)
   ...:     email = serializers.EmailField()
   ...:     full_name = serializers.CharField()
   ...:

In [9]: data = { # your data
   ...:   "email": "test@test.com",
   ...:   "full_name": "Test",
   ...:   "roles": [1, 2]
   ...: }

In [10]: u = UserSerializer(data=data)

In [11]: u.is_valid()
Out[11]: True

In [12]: u.data  # got valid data
Out[12]: {'roles': [1, 2], 'email': 'test@test.com', 'full_name': 'Test'}

In [13]: data["roles"] = [] # change data to accept empty list

In [14]: u = UserSerializer(data=data)

In [15]: u.is_valid()
Out[15]: True

In [16]: u.data  # got validated data with empty list
Out[16]: {'roles': [], 'email': 'test@test.com', 'full_name': 'Test'}

In [17]: data["roles"] = ["foo","bar"]   #added string to the list

In [18]: u = UserSerializer(data=data)

In [19]: u.is_valid()  # validation failed
Out[19]: False

In [20]: u.errors
Out[20]: {'roles': {0: [ErrorDetail(string='A valid integer is required.', code='invalid')], 1: [ErrorDetail(string='A valid integer is required.', code='invalid')]}}

UPDATE-1
Create a RoleSerializer and use it in the UserSerializer
class RoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Role
        fields = ('id', 'name')

class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = serializers.ListField(child=serializers.IntegerField(), allow_empty=True, required=False)

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        # check validated_data here
        ...

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        rep['roles'] = RoleSerializer(Role.objects.filter(id__in=rep['roles']), many=True).data
        return rep

UPDATE-2
Using a custom array field
class ArrayField(serializers.ListField):
    def __init__(self, *args, **kwargs):
        self.queryset = kwargs.pop('queryset', None)
        self.serializer_class = kwargs.pop('serializer_class', None)
        super().__init__(*args, **kwargs)

    def to_representation(self, data):
        qs = self.queryset.filter(id__in=data)
        serializer = self.serializer_class(qs,many=True)
        return serializer.data

class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = ArrayField(queryset=Role.objects.all(), serializer_class=RoleSerializer)

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        # check validated_data here
        ...

A: Try switching to PrimaryKeyRelatedField. Though you'll need to change your user model to use an actual relation. Which is generally a good idea because it'll help enforce data integrity with your project.
class User(models.Model):
    email = models.EmailField('Email', unique=True, blank=False)
    full_name = models.CharField(
        'Full name', max_length=150, blank=True, null=True)
    roles = models.ManyToManyField(Role, blank=True)

class UserSerializer(SerializerExtensionsMixin, serializers.ModelSerializer):
    roles = serializers.PrimaryKeyRelatedField(
        many=True,
        queryset=Role.objects.all(),
    )

    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'roles')

    def create(self, validated_data):
        print(validated_data)
        # {'email': 'test@test.com', 'full_name': 'Test', 'roles': []}
        user = super(UserSerializer, self).create(validated_data)

        return user


text:
Q: Bootstrap Responsive turn list into a mobile menu I want to be able to turn a simple unordered list into a nice menu when on mobile:

Buttons

Select

Input

Checkboxes & Radios

Switches

So when I'm on mobile the above gets turned into a simple menu with the 3 bars when then folds down the links.
Similar to how the Bootstrap navigation menu works, but so it doesn't conflict with this.
I ideally want to use the built in stuff with Bootstrap for this, good example of what i am after:
http://ux.mailchimp.com/patterns/forms
If you shrink the browser you will see that list turn into a menu on mobile.
Thanks

A: Some simple modifications to your HTML, media-queries and Javascript should allow you to replicate this behaviour.
I would suggest that you begin by creating the media-query to alter the applied styles based on device width.
CSS - Mobile first
.list-inline {
  display: none;
  visibility: hidden;
}

.list-inline-active {
  display: block;
  visibility: visible;
}

.list-inline li {
  display: block;
}

@media (min-width: 600px) {
  .list-toggle {
    display: none;
  }

  .list-inline {
    display: block;
    visibility: visible;
  }

  .list-inline li {
    display: inline-block;
  }
}

HTML - Add toggle button/icon
<button class="list-toggle">Show list</button>

Javascript/jQuery
$('.list-toggle').click(function(){
  $('.list-inline').toggleClass('list-inline-active');
});

This method simply uses a button to toggle a class on the unordered-list element. The toggled class contains styles to make the list visible on mobile.
I've created a simple JSFiddle example to show this in action.
It's worth noting that this behaviour is almost entirely replicable without the use of Javascript at all. It would involve the use of checkboxes and the ':checked' pseudo selector. However Bootstrap 3 does use Javascript.
I hope this helps.


text:
Q: Download a GridView into PDF including English and Arabic text in C# Can anyone help me out with my subjected issue.
I've VS 2019 and I need to download my GridView into PDF. Where English is working fine but there issue with Arabic text. Please help me out.
My print and export to excel works just fine.
Help will be much appreciated.


text:
Q: Trying to run a hierarchical linear model using lme4::lmer and keep getting an error I am trying to run a hierarchical linear model for the first time in R, using the lmer function from lme4 package, and I keep getting errors that I don't know how to interpret.
regression2 =
  lmer(logSowRatio ~ History + Balance + Promotion +
                     History:Promotion +
                     logIncome:Promotion +
                     (1 + logSowRatio|Promotion),
  data = sow.data,
  control = lmerControl(optimizer = "bobyqa"))

But I keep getting this error:

Error in if (any(bgrad < 0)) { : missing value where TRUE/FALSE needed


text:
Q: How is Minecraft able to function without a META-INF folder? I really don't understand how this works. I'm trying to build a .jar right now. It consists of two classes: Test.class and Sayer.class. And it works just fine if I access Test.class directly, or properly pack Test.jar, but the only way I can get a jar to execute is if I pack it with a manifest (jar cfm Test.jar manifest Test.class Sayer.class).
If I don't do that, I get an error when trying to run the jar: Error: Invalid or corrupt jarfile Test.jar. This also happens if I build the "good" jar, and remove META-INF/
This perfectly makes sense on its own. After all, you need some way of telling Java where to look for the entry point...right? But then you have Minecraft's modding community, which routinely recommends removing META-INF to make a given mod work.
But, how is Minecraft able to function without a META-INF folder? According to my experiments, this shouldn't even be possible. Shouldn't this corrupt minecraft.jar just like it corrupted my Test.jar?

A: Since MineCraft is run from a launcher, the launcher itself can pass the appropriate startup class to Java directly without needing a META-INF folder.


text:
Q: template engine implementation I am currently building this small template engine.
It takes a string containing the template in parameter, and a dictionary of "tags,values" to fill in the template.
In the engine, I have no idea of the tags that will be in the template and the ones that won't.
I am currently iterating (foreach) on the dictionnary, parsing my string that I have put in a string builder, and replacing the tags in the template by their corresponding value.
Is there a more efficient/convenient way of doing this?
I know the main drawback here is that the stringbuilder is parsed everytime entirely for each tag, which is quite bad...
(I am also checking, though not included in the sample, after the process that my template does not contain any tag anymore. They are all formated in the same way: @@tag@@)
//Dictionary<string, string> tagsValueCorrespondence;
//string template;

StringBuilder outputBuilder = new StringBuilder(template);
foreach (string tag in tagsValueCorrespondence.Keys)
{
    outputBuilder.Replace(tag, tagsValueCorrespondence[tag]);
}

template = outputBuilder.ToString();

Responses:
@Marc:
string template = "Some @@foobar@@ text in a @@bar@@ template";
StringDictionary data = new StringDictionary();
data.Add("foo", "value1");
data.Add("bar", "value2");
data.Add("foo2bar", "value3");

Output: "Some  text in a value2 template"
instead of: "Some @@foobar@@ text in a value2 template"

A: How about a Regex and MatchEvaluator? Like so:
string template = "Some @@Foo@@ text in a @@Bar@@ template";
StringDictionary data = new StringDictionary();
data.Add("foo", "random");
data.Add("bar", "regex");
string result = Regex.Replace(template, @"@@([^@]+)@@", delegate(Match match)
{
    string key = match.Groups[1].Value;
    return data[key];
});

A: Here is sample code you can use as starting point:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program {
    static void Main() {
        var template = " @@3@@  @@2@@ @@__@@ @@Test ZZ@@";
        var replacement = new Dictionary<string, string> {
                {"1", "Value 1"},
                {"2", "Value 2"},
                {"Test ZZ", "Value 3"},
            };
        var r = new Regex("@@(?<name>.+?)@@");
        var result = r.Replace(template, m => {
            var key = m.Groups["name"].Value;
            string val;
            if (replacement.TryGetValue(key, out val))
                return val;
            else
                return m.Value;
        });
        Console.WriteLine(result);
    }
}

A: You could modify the mono string format implementation into accepting your stringdictionary. For instance
http://github.com/wallymathieu/cscommon/blob/master/library/StringUtils.cs


text:
Q: What is the difference between casting to `float` and adding `f` as a suffix when initializing a `float`? What is the difference between
float f = (float) 99.32 ;

and
float f = 99.32f ;

Both of them compiled and ran successfully.

A: float f = 99.32f ;

That is a float literal, which means a float variable being assigned with a float value directly.
float f = (float) 99.32 ;

That is a  float variable that is assigned a double value that is cast to float before being assigned.

A: The difference is that the literal 99.32 is of type double, while the literal 99.32f is of type float.
The first statement assigns the float literal to a float variable. Nothing special.
The second statement casts a double literal to a float, and assigns the result to a float variable.
As far as the standard is concerned, you can assign a double literal to a float variable, without explicitly casting it yourself. In that case implicit cast occurs. E.g. :
float f = 99.32;

You can even do :
float f = (double) 10.5f;

and the right hand side is still implicitly converted to a float.
Please note that most modern compilers optimize those away, so representing floats is usually matter of style and preference. Just be consistent.

A: The difference may be optimized away, but in the first case you have a double literal that is type casted to a float while you have a float literal in the second case.
If not optimized away you will get a typecast in the code in the second example.
However there are corner cases where the result could (depending on rounding mode) be slightly different. If your number can't be exactly represented you will in the first case get rounding twice - first when you round the decimal representation to a double and then when you round that to a float, while in the first case you round the decimal representation directly to a float.

A: In the first case without the cast 99.32 is interpreted as double not as a float.
A double literal is being casted to float.
In the second case you have a suffix f to make sure the compiler treats 99.32 as float.

A: In the line float f = (float) 99.32; the literal 99.32 is created as a double type by default and is then cast to a float.
In the line float f = 99.32f ; the literal is created as a float type due to the trailing f in 99.32f and no type casting is required.
The latter would be analogous to writing double f = 99.32; as you'd have a double type being assigned directly to a variable of a matching type.

A: Floating point literals without a suffix are by default of double type.
Thus, stating float f = (float) 99.32; you first cast explicitly literal 99.32 which is of type double to a float and then assign it to variable f.
Stating float f = 99.32; does the same thing but in this case the conversion between types is done implicitly.
If you want to avoid implicit conversion you should use the f suffix to define your literal (i.e., float f = 99.32f;)


text:
Q: PHP include statement not working? Just started learning PHP and Wordpress.
Why isn't my PHP include statement working in the following header.php file?
<!DOCTYPE html>
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<title>
<?php include 'functions.php';?>
<?php if( is_page(1406)): ?>
<?php wp_title(' - ', true, 'right'); ?> <?php get_1406_page_title(); ?>
<?php else: ?>
<?php wp_title(' - ', true, 'right'); ?> <?php bloginfo('name'); ?>
<?php endif; ?>
</title>
.
.
.

I need to call get_1406_page_title() which is located in the functions.php. The above code produces empty page, and when I remove the include line the title is empty.
Here is the get_1406_page_title() from functions.php:
function get_1406_page_title()
{
    $title = "Page title here";
    return $title;
}

A: From your current code you

*

*do not need to include functions.php, it is automatically done

*Because get_1406_page_title() returns it's output, you need to echo the result from the function if you need to display the result
echo get_1406_page_title();


text:
Q: glGetUniformLocation OpenGL ES 2.0 (wrong return result on ipad 3 iOS 7.0.3) This is my vertex shader:
attribute vec4 a_position;
uniform mat4 u_projection;
uniform vec4 u_origin_translation;
uniform vec4 u_translation;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;
uniform vec4 u_color;
varying vec4 v_color;
attribute vec4 a_color;

void main()
{
    vec4 pos = a_position + u_origin_translation + u_translation;
    gl_Position = u_projection * pos;
    v_texCoord = a_texCoord;
    v_color = a_color * u_color;
}

And pixel shader:
precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D s_texture;
varying vec4 v_color;
void main()
{
    vec4 texColor = texture2D(s_texture, v_texCoord);
    gl_FragColor = texColor * v_color;
}

I trying to render textured quad within OpenGL ES 2.0 context on Marmalade 7.1 platform;
Source code of sending matrix data (projection uniform "u_projection") into shader:
GLint projectionUniformLocation = glGetUniformLocation(m_ShaderProgram->GetHandle(), m_ShaderProgram->GetProjectionUniformName().c_str());

glUniformMatrix4fv(projectionUniformLocation, 1, 0, &m_Ortho[0]);

My tracing code:
glGetActiveUniform(m_ShaderProgram->GetHandle(), projectionUniformLocation, maxUniformLength, 0, &size, &type, &buffer[0]);

TRACE_OUT("Context::ApplyOrtho: type is matrix " << (type == GL_FLOAT_MAT4));
TRACE_OUT("Context::ApplyOrtho: type is " << type);
TRACE_OUT("Context::ApplyOrtho: buffer is " << &buffer[0]);
TRACE_OUT("Context::ApplyOrtho: projectionUniformLocation is " << projectionUniformLocation);

Entire program works well in simulator on Windows. It shows textured quad and from tracing my projectionUniformLocation is type of GL_FLOAT_MAT4 so it is right.
BUT!!! When I run it on ipad 3 the same code works by another way.
Tracing says that my projectionUniformLocation is NOT GL_FLOAT_MAT4, but it is GL_SAMPLER_2D and output buffer message contains "s_texture"!!! Visible result is black quad without texture.
Update: On Windows in simulator projectionUniformLocation index is 3, but on ipad it's index is 2;
Update2: Listing of active uniforms from simulator:
Context::PrintActiveUniforms: active is s_texture and it's location is 0
Context::PrintActiveUniforms: active is u_color and it's location is 1
Context::PrintActiveUniforms: active is u_origin_translation and it's location is 2
Context::PrintActiveUniforms: active is u_projection and it's location is 3
Context::PrintActiveUniforms: active is u_translation and it's location is 4

and listing from ipad:
Context::PrintActiveUniforms: active is u_origin_translation and it's location is 0
Context::PrintActiveUniforms: active is u_color and it's location is 1
Context::PrintActiveUniforms: active is s_texture and it's location is 7
Context::PrintActiveUniforms: active is u_projection and it's location is 2
Context::PrintActiveUniforms: active is u_translation and it's location is 6

Update3: More information about uniforms on ipad 3 (Andon M. Coleman thank you for source code):
eTB_GLSL__print_uniforms: (loc=0) type=vec4 name=u_origin_translation size=1
eTB_GLSL__print_uniforms: (loc=1) type=vec4 name=u_color size=1
eTB_GLSL__print_uniforms: (loc=7) type=sampler2D name=s_texture size=1
eTB_GLSL__print_uniforms: (loc=2) type=mat4 name=u_projection size=1
eTB_GLSL__print_uniforms: (loc=6) type=vec4 name=u_translation size=1

Why glGetActiveUniform says that my u_projection is not mat4 and why I do not see my texture?
Any ideas?

A: Fortunately this question helps me. I was not looking where it was necessary to look. Two lines of code solve my problem and texture appears:
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );


text:
Q: unitialized subscription while replicating database Getting this warning when trying to setup a transactional replication. This error occurs when setting up a subscription from sql server express using non impersonated login to the distributor. this works using sql server developer subscrption to sql server workgroup publication but not from sql express to sql workgroup. Im not sure if it is an issue with the agent or what not but the subscription setup is identical to my working subscription other than the ability to choose the login to the sql server agent.

A: If I'm reading this correctly, you're trying to use SQL Server Express as your publisher. SQL Server Express can only be a subscriber in a transactional replication.
http://www.microsoft.com/sqlserver/2005/en/us/compare-features.aspx#integration


text:
Q: add livereload to broccoli I'm trying to add livereload to broccoli
Unfortunately the live-reload plugin documentation is a bit short and I cannot get it to work. In the docs it is stated to do the following:
var injectLivereload = require('broccoli-inject-livereload');

var public = injectLivereload('public');

I figured that this should be placed inside the Brocfile.js (right?). But whatever I do nothing gets reloaded (I have to hit reload to refresh) I've also changed the 'public' part, which I think is representing a directory. Any help would be appreciated.

A: I'm using BrowserSync instead of "only" LiveReload. It also supports LiveReload (and LiveInject for CSS), but it has tons of other features as well (like ghosting).
Let's create a file called server.js and a folder called app next to it, where you put our index.html, .css and .js. This server.js contains:
var broccoli = require("broccoli");
var brocware = require("broccoli/lib/middleware");
var mergeTrees = require("broccoli-merge-trees");
var Watcher = require("broccoli-sane-watcher");
var browserSync = require("browser-sync");

var tree = mergeTrees(["app"]); // your public directory
var builder = new broccoli.Builder(tree);
var watcher = new Watcher(builder);

watcher.on("change", function(results) {
    if (!results.filePath) return;

    // Enable CSS live inject
    if (results.filePath.indexOf("css") > -1) {
        return browserSync.reload("*.css");
    }

    browserSync.reload();
});

browserSync({
    server: {
        baseDir: "./",
        middleware: brocware(watcher)
    }
});

Now fire the server (which will open the browser automatically):
node server.js

I know this isn't as straightforward as Gulp or Grunt at first sight, but it offers fine grained control over everything and it's really blazing fast, even if your app grows and grows.

A: Instead of Livereload I opted to use Browsersync via the Broccoli Browser Sync plugin
My final Brocfile.js was very similar to (pulled from plugins npm page):
var fastBrowserify = require('broccoli-fast-browserify');
var babelify = require('babelify');
var mergeTrees = require('broccoli-merge-trees');
var compileSass = require('broccoli-sass-source-maps');
var funnel = require('broccoli-funnel');
var BrowserSync = require('broccoli-browser-sync');

var optionalTransforms = [
  'regenerator'
  // 'minification.deadCodeElimination',
  // 'minification.inlineExpressions'
];

var babelOptions = {stage: 0, optional: optionalTransforms, compact: true};

// var browserifyOpts = {deps: true, entries: files, noParse: noParse, ignoreMissing: true};
var transformedBabelify = fastBrowserify('app', {
  browserify: {
    extensions: [".js"]
  },
  bundles: {
    'js/app.js': {
      entryPoints: ['app.js'],
      transform: {
        tr: babelify,
        options: {
          stage: 0
        }
      }
    }
  }
});

var appCss = compileSass(['piggy/frontend/app'], 'main.scss', 'css/app.css');

var staticFiles = funnel('frontend', {
  srcDir: 'static'
});

var browserSync = new BrowserSync([staticFiles, transformedBabelify, appCss]);

module.exports = mergeTrees([staticFiles, transformedBabelify, appCss, browserSync]);

With this solution I was able to continue using broccoli to serve my assets via broccoli serve and all my assets would be rebuilt then reloaded in the browser including my css.


text:
Q: What is causing my kafka log segments to be deleted? These are my settings
log.retention.check.interval.ms=300000 checks when logs can be deleted
log.retention.hours=168 how old a non active segment must be before it gets deleted
log.retention.ms=null how old a non active segment must be before it gets deleted
log.retention.bytes=-1 how big a non active segment must be before it gets deleted
segment.ms=30000 how old segments have to be before the log gets rotated.
from what I gather, a new log segment should be created every 30 seconds when possible(this is happening). But why are old segments deleted? Shouldn't it wait 168 hours(since log.retention.ms is null)?

A: there was a property I was not looking into "min.cleanable.dirty.ratio". After accounting for that, I was able to trigger compaction pretty regularly.


text: Q: should i make a data.js file in which i'll put the json data or any other method to proceed with this use case? building a Search result page hosting a json in a static npm http-server (a dummy) and build a search result page in react+redux (you ay use any other state management other than redux as well)


text:
Q: Fetching and mapping data with fp-ts and io-ts I'm struggling with "massaging" my fetched data into the shapes I want, using fp-ts for functional transformation and io-ts for data validation.
What I'm looking for
I want getSchools() to return either an Error describing what went wrong, or an array of validated Schools. The code I have somewhat works, but the problem is that if one of the schools in the fetched array of schools fails validation, everything fails. I would like to just filter out the ones that failed, and return the rest.
The code I have so far
/**
 * API route for all Schools
 */
export default async (_: NextApiRequest, res: NextApiResponse<unknown>) => {
  return new Promise(
    pipe(
      getSchools(),
      fold(
        (e) => of(res.status(400).end(e.message)),
        (v) => of(res.status(200).json(v))
      )
    )
  );
};

/**
 * Handler for fetching Schools
 */
export function getSchools(): TaskEither<Error, Array<School>> {
  return pipe(
    fetch(schoolQuery(schoolQueryBody)),
    chain(mapToschools),
    chain(decode(t.array(School)))
  );
}

function mapToschools(
  inputs: Array<any>
): TaskEither<Error, Array<School>> {
  try {
    return right(inputs.map(mapToschool));
  } catch (e) {
    return left(new Error("Could not map input to school"));
  }
}

export function mapToschool(input: any): School // Can throw Error

export const schoolQueryBody = `...`;

function fetch(query: string): TaskEither<Error, unknown>

export function decodeError(e: t.Errors): Error {
  const missingKeys = e.map((e) => e.context.map(({ key }) => key).join("."));
  return new Error(`Missing keys: ${missingKeys}`);
}

export const decode = <I, A>(Type: t.Decoder<I, A>) => (
  res: I
): TaskEither<Error, A> => {
  return pipe(fromEither(Type.decode(res)), mapLeft(decodeError));
};

A: I think that you have some options here for what you want to return, and I think that the default behavior of fp-ts / io-ts isn't fully lining up with what you want.
What's going on
When you parse a t.array, you will get a failure whenever one of the values fails to be decoded. It sounds to me like you want to individually attempt to decode each of the values instead of using t.array.
Suggestions
I think I would instead say something like:
import { pipe } from 'fp-ts/lib/function';
import * as ArrayFP from 'fp-ts/lib/Array';

const undecodedSchools: unknown[] = [/* ... school response */];
const schools: School[] = pipe(
  undecodedSchools,
  ArrayFP.map(schoolCodec.decode), // Array<Either<t.Errors, School>>
  ArrayFP.rights, // Takes an Array<Either<E, A>> -> Array<A>
);

That completely gets rid of the Either which may not be what you want. If you want to see the errors, it might be worth it to instead say:
const schools: {
  left: Error[],
  right: School[],
} = pipe(
  undecodedSchools,
  ArrayFP.map(schoolCodec.decode), // Array<Either<t.Errors, School>>
  ArrayFP.separate, // Takes an Array<Either<A, B>> -> Separated<A[], B[]>
);

Which pulls apart the two types of things from the array of eithers.