text:
Q: Check passed data with a view is not empty in laravel I am using laravel 4 and I want to pass a data with a view.
I have used this code in a controller.
$view = View::make('settings.editEvent');
$view->bounderyData = $bounderyData;

And I want to check whether this data exists or not in the view settings/editEvent.blade.php
Tried using this..
<script>
   if('{{$bounderyData.length()}}'!=null)
      console.log('exists');
</script>

Error :
Array to string conversion error

How can I check the existence ?

A: Do not assign the data to the View variable, but instead, pass it along using with as Laravel requests you to use:
$view = View::make('settings.editEvent')
    ->with('bounderyData', $bouderyData);

A: Actually both of the snippets work the same way. You can either pass data using with() method or by assigning it to view as property. So it doesn't really matter. But it looks like you are using some weird syntax because you are trying to access method length() using dot syntax inside Blade echo statement. Try:
if({{count($bounderyData)}}!=null)
  console.log('exists');

or something similar. Remember that everything inside {{}} is going to be echo'ed by PHP. So if you have some sort of array there you may either want to count number of elements or maybe cast it to JSON and then decode it inside Javascript. If you still have problem, let us know what is the issue.


text:
Q: How to wrap function call inside of Promise After exporting the required modules and setting up the variables
let AWS = require("aws-sdk");
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');

const USER_POOL_ID = 'us-east-1_vkXRQuP4U';
const CLIENT_ID = 'mipa4trls0l7323om33mlk80e8';

const poolData = {
  UserPoolId : USER_POOL_ID, ClientId : CLIENT_ID
};
const POOL = new AmazonCognitoIdentity.CognitoUserPool(poolData);

let email = "my.email@domain.com";
let password = "My.Password!";

I can go ahead and call signUp command:
POOL.signUp(email, password, [], null, function(err, result) {
  console.log('...result:', result);
});

And it works well. Next I want to wrap the POOL.signUp(email, password...) inside async function sign_up like so:
async function sign_up(email, password) {
  POOL.signUp(email, password, [], null, function(err, result) {
    console.log('...sign_up.result:', result);
    return result;
  })
};

async function main() {
  let signupData = await sign_up(email, password);
  console.log('...main.signupData:', signupData);
  return signupData;
};

main().then((error, data) => {console.log('...error, data:', error, data)});

While it works fine, the order of the calls that get executed is wrong as the main function doesn't wait for the sign_up() function to complete. In attempt to correct this behavior I wrap the POOL.signUp(email, password...) inside of Promise:
async function sign_up(email, password) {

  return await new Promise((resolve) => {
    POOL.signUp(email, password, [], null, {
      onSuccess: (result) => {
        console.log('...result:', result)
        return resolve(result);
      },
      onFailure: (err) => {
        return resolve(err.message);
      },
    });
  })
};

But I am getting the error message:
 UnhandledPromiseRejectionWarning: TypeError: callback is not a function

Is there a way to avoid this error?

A: *

*don't need to await the Promise you are returning (since we precisely want our function to be async, we want to defer the waiting to the caller)

*Promise constructor function needs to provide the second reject parameter to be able to access the callback in the function implementation

*pass a callback function as your POOL.signUp fourth argument, instead of an object

function sign_up(email, password) {
  return new Promise((resolve, reject) => {
    POOL.signUp(email, password, [], null, function(err, result) {
      if (err) {
        return reject(err.message);
      }

      console.log('...result:', result)
      resolve(result);
    });
  })
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOException when using loopj SyncHttpClient I have the need to use loopj's SyncHttpClient in a couple areas. When I use AsyncHttpClient, the request returns successfully. When I use the SyncHttpClient as shown in the accepted answer here: How to use loopJ SyncHttpClient for synchronous calls?, I hit a breakpoint in onFailure. The statusCode is 0, the errorResponse is null, and throwable is java.io.IOException: Unhandled exception: null.
Here is the relevant code. Again when I use Async it works fine:
        buttonTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                AsyncHttpClient httpClient = new AsyncHttpClient();
                SyncHttpClient httpClient = new SyncHttpClient();

                httpClient.get("http://10.0.1.6:3000/home/test_endpoint", new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        String stringResponse = response.toString();
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        String error = errorResponse.toString();
                    }
                });

                String temp = "got here";
            }
        });

I'm using compile 'com.loopj.android:android-async-http:1.4.9'

A: I did some debugging when I hit this, and I discovered that loopj is eating the following exception:
android.os.NetworkOnMainThreadException

I can't give a detailed stack trace because this exception doesn't seem to be logged properly (logcat is not picking it up at all for some reason)
However, it's located here:
AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:203)

I have been running my code like this:
Handler handler = new Handler();
Runnable r = new Runnable(){
  public void run(){
    SyncHttpClient client ....
    client.get(.....); // hit error here
  }
};

As you can see, I happen to be running my SyncHttpClient within a Handler.post() method, but apparently that implementation does not count as (Networking on a non-main thread)
The key thing that fixed it was the use of "new Thread(...)" that mikeorr85's code included. Like so ...
new Thread(Runnable r = new Runnable(){
  public void run(){
    SyncHttpClient client ....
    client.get(.....); // hit error here
  }
}).start();

A: You must still run it off the main thread. This is the code that worked for me and allowed me to hit a breakpoint set at - "String temp = 'got here'" after the request completed:
        buttonTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        AsyncHttpClient httpClient = new AsyncHttpClient();
                        SyncHttpClient httpClient = new SyncHttpClient();

                        httpClient.get("http://10.0.1.6:3000/home/test_endpoint", null, new JsonHttpResponseHandler() {
                            @Override
                            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                                String stringResponse = response.toString();
                            }

                            @Override
                            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                                String error = errorResponse.toString();
                            }
                        });

                        String temp = "got here";
                    }
                }).start();
            }

More code is available on their github page: https://github.com/loopj/android-async-http/blob/master/sample/src/main/java/com/loopj/android/http/sample/SynchronousClientSample.java

A: I use AsyncHttpClient and it work for me fine.


text:
Q: Псевдоклассы CSS, которые активируются при щелчке Есть, допустим, один элемент. Каким псевдоклассом можно сделать, чтобы при клике на этот элемент, появлялся border: 1px solid white и оставался на этом элементе, пока я не кликнул на другой? Кажется, при помощи active, но не получается.

A: Элементы DIV могут получить фокус, если установить атрибут tabindex.

.thumb-1:focus { border: 1px solid red; }

...

A: Можно через :focus попробовать, но не думаю что этот способ подойдет везде. Тот же jQuery toggleClass(), на мой взгляд, будет надежнее.

body {
  background: #555;
  color: #fff;
}

.thumb-1 {
  width: 97px;
  height: 67px;
  float: left;
}

div.thumb-1:focus {
  border: 1px solid white;
  /*Еще нужна эта строчка*/
  outline: -webkit-focus-ring-color auto 0px;
  ;
}

Нажми на меня

A: Один из возможных способов - использовать псевдокласс target.

#qwe:target {
    outline: 1px solid black;
}

Вот ваш элемент, щёлкните сюда


text:
Q: How to organize powershell class definition I run into issue when executing the following code snippet in ise by selecting all and click run:
Import-Module ActiveDirectory
class ADUtil
{
    [Microsoft.ActiveDirectory.Management.ADGroup] $Group
}

The type [Microsoft.ActiveDirectory.Management.ADGroup] is unknown. If I  execute Import-Module ActiveDirectory explicit at first, then I can run the class definition without any error.

A: Correct. Naturally, you have to import the module first, before using any types contained in it.
To make this more usuable, there are 2 possibilities off the top of my head:

*

*If it's a script, you can use the #Require statement:

#Require -Module ActiveDirectory

*If you use this in the console frequently, add the import to your $Profile
Import-Module ActiveDirectory


text:
Q: Is it possible to express values such as $\sin^{-1}(\pi/12)$ without inverse trig functions? Pretty self explanatory.

If I had for example something like $\sin^{-1}(\pi/12)$ in an expression, is it ever possible to express that expression without inverse trig functions?

A: If you have fixed arguments, the inverse trigonometric function (or any other, for that matter) is just a fixed value. Finding out what the value is (giving it a "name" that isn't just the expression to be replaced) might or might not be possible or simple to do. Or even desirable, if e.g. you want to apply trigonometric functions to your expression the inverse trigonometric functions can point to ways to simplify the result.

A: You can give your number a name or represent it explicitly e.g. as value of another function or of an integral, as limit of a series, or implicitly as solution of an equation.
$\ $
The numbers that are explicitly representable by finite terms are the explicit ones among the closed-form numbers.
Because $\sin^{-1}(\frac{\pi}{12})$ is the value of a named function ($\sin^{-1}$), it is an explicit closed-form number.
Because $\sin^{-1}$ is an explicit elementary function, $\sin^{-1}(\frac{\pi}{12})$ is an explicit elementary number, an EL-number (see below: [Chow 1999]).
Let $z_0\in\mathbb{C}$ and let $c$ denote a closed-form number. Your problem has the form:
$$\sin^{-1}(z_0)=c,$$
or
$$\sin(c)=z_0.$$
Your $z_0$ is also an explicit closed-form number, in your example in particular also an explicit elementary number.
1.) Algebraic numbers
a) If your $z_0$ is an algebraic number, look for the algebraic points of your function ($\sin^{-1}$) (or for the algebraic points of the inverse of your function ($\sin$)).
b) Otherwise look for the algebraic values of your function ($\sin^{-1}$).
We know, the explicitly representable algebraic numbers are the numbers that can be represented by radical expressions.
But $\sin^{-1}(\frac{\pi}{12})$ is not an explicit algebraic number.
2.) Elementary numbers
$\sin^{-1}(z)$ is an elementary function.
The function term of an elementary function can be represented as a term that contains only the variable and $\exp$, $\log$ and/or algebraic terms.
$$\sin^{-1}(z)=-i\log(\sqrt{1-z^2}+iz)$$
$$\sin^{-1}(\frac{\pi}{12})=-i\log(\sqrt{1-\left(\frac{\pi}{12}\right)^2}+i\frac{\pi}{12})$$
[Chow 1999] Chow, T.: What is a closed-form number. Am. Math. Monthly 106 (1999) (5) 440-448


text:
Q: What is the difference between JRE options java.awt.headless and java.awt.headlesslib? I have used the former many times (-Djava.awt.headless=true) in order to prevent the infamous "no DISPLAY found" error for some applications which used some graphics methods in the JRE.
But since then I have also learned of the existence of the second one. In spite of hours of searching around, I cannot find a difference between both.
And to make matters worse, I am no GUI expert at all... So, is there an actual difference? What code would work with one and not the other, or would require both etc?

A: java.awt.headlesslib is part of a temporary workaround added in 2001 in response of bug JDK-4407772.
If you download the source code of openjdk6, openjdk7 or openjdk8 and grep all the source files looking for java.awt.headlesslib you will see no results.
So the effect of setting java.awt.headlesslib is null and the effect of setting java.awt.headless is to activate the headless mode.


text:
Q: Properties of Adjoints Suppose we have a linear transformation $ T $ on some real inner product space $ V $, with adjoint $ T^{*} $.
How can we go about showing that
$$
(T^{n})^{*} = (T^{*})^{n}
$$
for a positive integer $ n $? Also, does this means that $ [f(T)]^{*} = f(T^{*}) $ for any polynomial $f$?
Any help would be appreciated.

A: We need the following result.

Theorem For any two linear transformations $ S $ and $ T $ on $ V $, we have $ (S \circ T)^{*} = T^{*} \circ S^{*} $.

Proof: By the definition of 'adjoint transformation', we have
\begin{align}
   \forall \mathbf{v}_{1},\mathbf{v}_{2} \in V: \quad
   \langle \mathbf{v}_{1},(S \circ T)(\mathbf{v}_{2}) \rangle
&= \langle \mathbf{v}_{1},S(T(\mathbf{v}_{2})) \rangle \\
&= \langle {S^{*}}(\mathbf{v}_{1}),T(\mathbf{v}_{2}) \rangle \\
&= \langle {T^{*}}({S^{*}}(\mathbf{v}_{1})),\mathbf{v}_{2} \rangle \\
&= \langle (T^{*} \circ S^{*})(\mathbf{v}_{1}),\mathbf{v}_{2} \rangle.
\end{align}
Therefore, $ (S \circ T)^{*} = T^{*} \circ S^{*} $. $ \quad \spadesuit $
To prove the identity in question, we induct on $ n \in \mathbb{N} $.
For each $ n \in \mathbb{N} $, let $ P(n) $ denote the statement
$$
(T^{n})^{*} = (T^{*})^{n}.
$$
The truth of $ P(1) $ is tautological. Next, suppose that $ P(k) $ is true for some $ k \in \mathbb{N} $. Then
\begin{align}
(T^{k + 1})^{*} &= (T^{k} \circ T)^{*} \\
                &= T^{*} \circ (T^{k})^{*} \quad (\text{By the theorem.}) \\
                &= T^{*} \circ (T^{*})^{k} \quad (\text{By the induction hypothesis.}) \\
                &= (T^{*})^{k + 1}.
\end{align}
Hence, $ P(k + 1) $ is true. By mathematical induction, $ P(n) $ is true for all $ n \in \mathbb{N} $.
By linearity, we conclude that $ [f(T)]^{*} = f(T^{*}) $ for any polynomial $ f \in \mathbb{R}[X] $.

Addendum
This part was prepared in response to the OP's question in his comment below. Let $ p $ and $ q $ be the minimal polynomials of $ T $ and $ T^{*} $ respectively. By the solution above, we have
$$
p(T^{*}) = [p(T)]^{*} = \mathbf{0}^{*} = \mathbf{0}.
$$
Hence, $ q $ divides $ p $. Next, we have
$$
q(T) = q((T^{*})^{*}) = [q(T^{*})]^{*} = \mathbf{0}^{*} = \mathbf{0}.
$$
Hence, $ p $ divides $ q $ also. Therefore, as both $ p $ and $ q $ are monic polynomials, we conclude that $ p = q $.


text:
Q: Why isn't tk.IntVar working for the second tk window? I'm trying to use tk.Scale to change a tk.IntVar. I can do it on the first tk window but I can't on the second one. Why?
Look this poor sample:
import tkinter as tk

# main root
root = tk.Tk()

myvar = tk.IntVar()

def on_change(*args):
   print("Value changed to {}".format(myvar.get()))

myvar.trace("w", on_change)

sc = tk.Scale(root, from_=1, to=10, orient=tk.HORIZONTAL, length=320, \
    variable=myvar)
sc.grid()

# second root
root2 = tk.Tk()

myvar2 = tk.IntVar()

def on_change2(*args):
   print("Value2 changed to {}".format(myvar2.get()))

myvar2.trace("w", on_change2)

sc2 = tk.Scale(root2, from_=1, to=10, orient=tk.HORIZONTAL, length=320, \
    variable=myvar2)
sc2.grid()

root.mainloop()

What am I doing wrong?
I'm using python 3.3 on Mac.

A: You cannot have two instances of tkinter.Tk running simultaneously in the same thread. They will not share the Tcl interpreter properly and the one that was created first will always act as the main window.
To fix the problem, make root2 an instance of tkinter.Toplevel:
root2 = tk.Toplevel()

The tkinter.Toplevel window will be dependent on the tkinter.Tk one, which means it will share the Tcl interpreter started for the latter.


text:
Q: Month auto increment using mktime and timegm functions in C++ I'd like to convert a string date (UTC) to a timestamp using C++.
It works fine except for the month, which is auto incremented by one.
If the string is 20221222074648, for 2022-12-22 07:46:48, the timestamp will be 1674373608, which is the timestamp of 2023-01-22 07:46:48.
I don't understand the reason of this auto-increment, because there's no changes of the month's variable in the code below.
    cout << "date : " << receivedDate << endl;
    struct tm t;
    time_t timestamp;
    size_t year_size = 4;
    size_t other_size = 2;
    t.tm_year = stoi(receivedDate.substr(0, 4), &year_size, 10) - 1900;
    t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10);
    t.tm_mday = stoi(receivedDate.substr(6, 2), &other_size, 10);
    t.tm_hour = stoi(receivedDate.substr(8, 2), &other_size, 10);
    t.tm_min = stoi(receivedDate.substr(10, 2), &other_size, 10);
    t.tm_sec = stoi(receivedDate.substr(12, 2), &other_size, 10);
    t.tm_isdst = -1;
    cout << "year : " << t.tm_year + 1900 << "\nmonth : " << t.tm_mon << "\nday : " << t.tm_mday << "\nhour : " << t.tm_hour << "\nminutes : " << t.tm_min << "\nseconds : " << t.tm_sec << endl;

    timestamp = timegm(&t);

    cout << "timestamp : " << timestamp << endl;
    cout << "asctime timestamp : " << asctime(&t);

A: Your problem is pretty simple !
the tm.tm_mom goes from 0 to 11, You need to add -1 on your month value
t.tm_mon = stoi(receivedDate.substr(4, 2), &other_size, 10) - 1;


text: Q: xampp control can't connect with apache and MySQL I have installed Xampp 32bit in windows 7. Also change the port number of apache. But still localhost is saying "Unable to connect". Can't figure out the problem. Anyone can help please ?


text:
Q: go/types finding if struct implements interface OK so looking at using go/types, go/parser... an so forth to generate some code; but need to identify all structs that implement a specific interface which I have figured out, however, if the struct definition on the struct function it does not match using types.Implements.
OK the code examples:
Getting the interface
package ifacepkg

const interfacePkg = `package ifacepkg

type MyInterface interface {
    MyFunction() error
}
`

func getIface() *types.Interface {

fset := token.NewFileSet()

f, err := parser.ParseFile(fset, "iface.go", interfacePkg, 0)
if err != nil {
    panic(err)
}

config := &types.Config{
    Error: func(e error) {
        fmt.Println(e)
    },
    Importer: importer.Default(),
}

info := types.Info{
    Types: make(map[ast.Expr]types.TypeAndValue),
    Defs:  make(map[*ast.Ident]types.Object),
    Uses:  make(map[*ast.Ident]types.Object),
}

pkg, e := config.Check("genval", fset, []*ast.File{f}, &info)
if e != nil {
    fmt.Println(e)
}

return pkg.Scope().Lookup("MyInterface").Type().Underlying().(*types.Interface)
}

Test File
package test

import "ifacepkg"

// User struct
type User struct {
    FirstName string
    LastName  string
}

func (u User) MyFunction() error {
    return nil
}

var _ ifacepkg.MyInterface = &User{}

Loading Test File & trying to see if User implements MyInterface
fset := token.NewFileSet()

pkgs, e := parser.ParseDir(fset, "./test", nil, 0)
if e != nil {
    log.Fatal(e)
    // return
}

var astf []*ast.File

for _, pkg := range pkgs {
    fmt.Printf("package %v\n", pkg.Name)
    for fn, f := range pkg.Files {
        fmt.Printf("file %v\n", fn)
        astf = append(astf, f)
    }
}

config := &types.Config{
    Error: func(e error) {
        fmt.Println(e)
    },
    Importer: importer.Default(),
}

info := types.Info{
    Types: make(map[ast.Expr]types.TypeAndValue),
    Defs:  make(map[*ast.Ident]types.Object),
    Uses:  make(map[*ast.Ident]types.Object),
}

pkg, e := config.Check(path, fset, astf, &info)
if e != nil {
    fmt.Println(e)
}

vIface := getIface()
fmt.Println(vIface)

scope := pkg.Scope()

    for _, name := range scope.Names() {

        obj := scope.Lookup(name)

        _, ok := obj.Type().Underlying().(*types.Struct)
        imp := types.Implements(obj.Type(), vIface)

        fmt.Println(obj.Name(), ok, imp)
    }

OK so fmt.Println(obj.Name(), ok, imp) prints User true true all good! however if I change the source file function from
func (u User) MyFunction() error {

to
func (u *User) MyFunction() error {

it now prints User true false
so the function types.Implements is reporting that User does not implement MyInterface, which is not true.
So my question is: Is there an issue with the type.Implements method or is there something I have to do to my object prior to calling that function.
Answer
ok to solve my own issue changing final portion of code to
scope := pkg.Scope()

for _, name := range scope.Names() {

    obj := scope.Lookup(name)

    _, ok := obj.Type().Underlying().(*types.Struct)
    ptr := types.NewPointer(obj.Type())
    imp := types.Implements(ptr.Underlying(), vIface)

    fmt.Println(obj.Name(), ok, imp)
}

which works with both Pointer and non-pointer recievers

A: What your compiler is telling you is true. *Type != Type in Go. If you want *User to implement your interface then the methods receiver has to be *User and if you want it to be User then it needs to be User. I don't really know how else to explain it... Go's type system is strict and those aren't the same. You can see this more practically if you have (u *User) MyFunction() defined for the pointer type do ptr := &MyUser then check if MyUser and ptr implement the interface, ptr will, MyUser will not.


text:
Q: How to update a pirtucular column in a database?     $credit = $this->db->select('credits');
    $this->db->from('users');
    $this->db->where('refferal_code',$refferal_code);
    $data1 = array('credits'=>$credit + 10);
    $this->db->update('users',$data1);

I need to update a column in a database..
When a user signs up, he will give a referral code.
I need to check whether that code exists in the database and need to update the referral code for the user by giving him with 10 more credits.
The above code shows error, Can anyone help me me figure why?

A: Try this
$credit = $this->db->select('credits');
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$data = $this->db->get();
if($data->num_rows()>0)
{
     $res = $data->row_object();
     $this->db->where('refferal_code',$refferal_code);
     $update = $this->db->update('users',array('credits'=>$res->credits + 10));
}

OR
Simplest one as @Shaiful Islam mentioned in comment
$this->db->from('users');
$this->db->where('refferal_code',$refferal_code);
$this->db->set('credits', 'credits+10', FALSE);
$this->db->update('users');


text:
Q: Chart.js combined line and bar chart with differing data points I want to use chart.js to plot the daily generation of my solar panels combined with the month total in one chart, much like in the image below. Both graphs alone are easy to produce, but all examples I find for a combined chart have the same amount of datapoints for both charts. I have 12 for the bar chart and 365 or 366 for the line chart.
Is it possible to make this?

A: Using timeseries as x-Axis, applying additional trick:
Try following:

*

*set x-axis type to timeseries:
for each x-Axis scales: {'daily-x-axis': { type: 'timeseries' ...
for x-Axis type 'time' or 'timeseries' to work, you need additional libraries  (like moment.js and its adapter)

*Trick: for monthly totals in your data, use first day of month as x value, like x: "2021-01-01" etc ...

*style your bars and labels/ticks, adding backgroundColor: 'rgba(0,0,255,0.5)', x- and y-Axis label colors, color of ticks, etc ...

let dailyGeneration = [{x: '2021-01-01', y: 1},{x: '2021-01-02', y: 3},{x: '2021-01-03', y: 2},{x: '2021-01-04', y: 5},{x: '2021-01-05', y: 8},{x: '2021-01-06', y: 2},{x: '2021-01-07', y: 11},{x: '2021-01-08', y: 10},{x: '2021-01-09', y: 7},{x: '2021-01-10', y: 6},{x: '2021-01-11', y: 1.5},{x: '2021-01-12', y: 3},{x: '2021-01-13', y: 4},{x: '2021-01-14', y: 6},{x: '2021-01-15', y: 0.5},{x: '2021-01-16', y: 3},{x: '2021-01-17', y: 9},{x: '2021-01-18', y: 8},{x: '2021-01-19', y: 7},{x: '2021-01-20', y: 6},{x: '2021-01-21', y: 6},{x: '2021-01-22', y: 4},{x: '2021-01-23', y: 3},{x: '2021-01-24', y: 1},{x: '2021-01-25', y: 1},{x: '2021-01-26', y: 2},{x: '2021-01-27', y: 5},{x: '2021-01-28', y: 8},{x: '2021-01-29', y: 7},{x: '2021-01-30', y: 12},{x: '2021-01-31', y: 2},
{x: '2021-02-01', y: 1},{x: '2021-02-02', y: 3},{x: '2021-02-03', y: 2},{x: '2021-02-04', y: 5},{x: '2021-02-05', y: 8},{x: '2021-02-06', y: 2},{x: '2021-02-07', y: 11},{x: '2021-02-08', y: 10},{x: '2021-02-09', y: 7},{x: '2021-02-10', y: 6},{x: '2021-02-11', y: 1.5},{x: '2021-02-12', y: 3},{x: '2021-02-13', y: 4},{x: '2021-02-14', y: 6},{x: '2021-02-15', y: 0.5},{x: '2021-02-16', y: 3},{x: '2021-02-17', y: 9},{x: '2021-02-18', y: 8},{x: '2021-02-19', y: 7},{x: '2021-02-20', y: 6},{x: '2021-02-21', y: 6},{x: '2021-02-22', y: 4},{x: '2021-02-23', y: 3},{x: '2021-02-24', y: 1},{x: '2021-02-25', y: 1},{x: '2021-02-26', y: 2},{x: '2021-02-27', y: 5},{x: '2021-02-28', y: 8}];

let montlyTotals = [{x: '2021-01-01', y: 98},{x: '2021-02-01', y: 120}];

let yourData = {
  datasets: [{
    type: 'line',
    label: 'Daily Generation',
    data: dailyGeneration,
    borderColor: 'rgba(0,0,255,1)',
    xAxisID: 'daily-x-axis',
    yAxisID: 'daily-y-axis',
  },
  {
    type: 'bar',
    label: 'Monthly Totals',
    data: montlyTotals,
    borderColor: 'rgba(0,255,0,0.5)',
    backgroundColor: 'rgba(0,255,0,0.5)',
    xAxisID: 'monthly-x-axis',
    yAxisID: 'monthly-y-axis',
  }]
};

let yourOptions = {
  scales: {
    // x-Axis by their IDs
    'daily-x-axis': { // <-- v3.x now object "{", not array "[{" anymore
      type: 'timeseries', // <-- try "time" and "timeseries" to see difference
      time: {
        unit: 'day', // <-- set to 'day'
        displayFormats: {
          day: 'MMM DD, YYYY',
          month: 'MMM'
        },
        tooltipFormat: 'dddd, MMM DD, YYYY'
      },
      ticks: {
        minRotation: 80, // avoiding overlapping of x-Axis ticks
        maxRotation: 90,
        color: "blue"
      },
      position: 'bottom'
    },
    'monthly-x-axis': {
      type: 'timeseries', // <-- try "time" and "timeseries" to see difference
      time: {
        unit: 'month', // <-- set to 'month'
        displayFormats: {
          day: 'MMM DD, YYYY',
          month: 'MMM'
        },
        tooltipFormat: 'MMM, YYYY'
      },
      ticks: {
        color: "green"
      },
      position: 'bottom'
    },
    // y-Axis by their IDs
    'daily-y-axis': {
      position: 'left',
      title: {
        display: true,
        text: 'kWh / day',
        color: "blue"
      },
      ticks: {
        color: "blue"
      }
    },
    'monthly-y-axis': {
      position: 'right',
      title: {
        display: true,
        text: 'total kWh / month',
        color: "green"
      },
      ticks: {
        color: "green"
      }
    }
  }
};

const ctx = document.getElementById('chartJSContainer').getContext('2d');

const myChart = new Chart(ctx, {
  data: yourData,
  options: yourOptions
});
<!-- get the latest version of Chart.js, now at v3.5.1 -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- for x-Axis type 'time' or 'timeseries' to work, you need additional libraries -->
<!-- (like moment.js and its adapter) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>

<canvas id="chartJSContainer" width="600" height="400"></canvas>

A: Yes, just use object notation:

var options = {
  type: 'line',
  data: {
    datasets: [{
        label: '# of Votes',
        data: [{
          x: new Date('09-08-2021 12:04'),
          y: 10
        }, {
          x: new Date('09-08-2021 12:08'),
          y: 15
        }, {
          x: new Date('09-08-2021 12:12'),
          y: 5
        }, {
          x: new Date('09-08-2021 12:30'),
          y: 8
        }],
        borderColor: 'pink'
      },
      {
        type: 'bar',
        label: '# of Points',
        data: [{
          x: new Date('09-08-2021 12:04'),
          y: 4
        }, {
          x: new Date('09-08-2021 12:08'),
          y: 6
        }, {
          x: new Date('09-08-2021 12:12'),
          y: 12
        }, {
          x: new Date('09-08-2021 12:30'),
          y: 18
        }, {
          x: new Date('09-08-2021 12:022'),
          y: 10
        }, {
          x: new Date('09-08-2021 12:38'),
          y: 15
        }, {
          x: new Date('09-08-2021 12:52'),
          y: 5
        }, {
          x: new Date('09-08-2021 12:59'),
          y: 8
        }],
        backgroundColor: 'orange'
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: 'time',
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>


text:
Q: Windows Updates based restart - bypassing I have a powershell script that is working at Night in office PC - (wiht out admin privileges)- the problem is at night time Updates are getting pushed and system is restarting and script wont start since I do not have batch execution or other similar right.
There is a way to 'end task' windows updates though powershell in task manager.
However, I wanted to know if it is safe - I will restart pc once I am back to office.
I cannot disable the update service - no rights are there. Mainly wanted to know the difference between update service and update task.

*

*Update service is responsible for update downloads? or task is responsible?

*Is update service is responsible for installing the updates or the task is responsible?

*What while happen (cons) if I keep running a script to end task the windows update task every minute.

*I tried the 'shutdown -a' every minute but came to know it wont effect the updates based shutdown.

No admin privileges - so bye bye to gpedit, regedits etc based solutions.
Once the update is done - there will be a screen asking for restart (5-15 mins) or manual restart after an hour etc - but since no one will be there it is auto restarting.  Please advice. - It is really helpful to know more on it.

A: Please if possible contact your local IT dept and ask them to remove your device from the automatic reboot schedule.
Trying to circumvent automatic reboots may have other implications you're not aware of.
Within my company attempting to change a windows system application which is tied to compliance and security would be regarded as gross misconduct.

A: If you do not have administrative privileges you won't be able to stop/kill the windows update service or task. Even if you did have the appropriate permissions, interfering with windows update on a production server seems like a bad idea on a number of different levels.
Rather than fiddle with windows updates, I think that there is probably a better approach. It sounds like your script runs for a long time. Are updates being pushed at a known time? Include logic in your script to have it stop running right before the the updates will be installed. Output your script progress to a file. After the server reboots you can configure the same script to run again automatically upon startup/logon or as a scheduled task. The script can read in the script status from your output file and pick up where it left off before the reboot.
If you do not know the specific time when updates will be installed, you can include logic in your script to check periodically to see if the windows update client process is running (wuauclt). When the update process is detected, have your script stop running.
The obvious problem with this approach is that a startup script requires administrative privileges. Maybe the only thing you can do is configure the script as a logon script so that it will be run the following day automatically when you log in to the server.


text:
Q: How are explicit interface implementations implemented in IL? I've been having a look at explicit interface implementations in IL. The method Method in the following class (interface IA has a single Method() on it):
public class B : IA
    object IA.Method() {
        /* code */
    }
}

is compiled to the following IL method signature:
.method private hidebysig newslot virtual final instance object IA.Method() cil managed {
    .override IA::Method
    /* code */
}

My question is - why is the method name in IL IA.Method(), rather than just straight Method? What does this actually mean, and why doesn't it work if it's missed off? I can't find anything in the ECMA spec or google about it.

A: This is because this way you can have a method multiple times.
public class B : IA
{
    object Method() {    }
    object IA.Method() {    }
}

The first is a normal method. The second is the interface implementation. Without the prefix you could not have both because you could not differentiate between them.
new B().Method(); // calls the normal method
((IA)new B()).Method(); // calls the IA interface method

A: Here's the documentation you're looking for:
http://msdn.microsoft.com/en-us/library/ms173157.aspx
The reason for it is to handle this case:
public class C : IA, IB
{
    object IA.Method()
    {
        // Implementation!
    }
    object IB.Method()
    {
        // Implementation!
    }
}

If you've got two methods with the same signature that you want to implement, you need something to make them different so you can supply seperate implementations.  The name of the interface provides that.


text:
Q: How to validate phone number in spring mvc? I am using the @valid annotation for all the validations in a Spring MVC project. I want to validate a phone number, but I can't find a way.
I tried this, but it gives an error that I can't use @Size on int and long.
@Size(10)
private long phone;

I also tried this, but it gives an error that the maximum value is out of bounds as it can only take values as int.
@Min(1000000000)
@Max(9999999999)
private long phone;

I also tried regex in @Pattern, but it gives the same error that I can't validate a @Pattern as an int or a long.
@Pattern(regex="...")
private long phone;

If I don't write any annotations and try to enter an empty string, it gives an error when converting from a string to a long for an empty string, "". Is there any way I can validate a phone number without changing it to String?
Edit: Yes, I have used @Valid and BindingResult and I cannot change a phone number to string as it is connected with a database which has bigint in the table. Changing it here will affect everything else because I'm using Hibernate for auto saving in SQL.

A: You need to use String and @Valid annotation with regex pattern.


text:
Q: Why does using CONVERT(DATETIME, [date], [format]) in WHERE clause take so long? I'm running the following code on a dataset of 100M to test some things out before I eventually join the entire range (not just the top 10) on another table to make it even smaller.
SELECT TOP 10 *
    FROM Table
    WHERE CONVERT(datetime, DATE, 112) BETWEEN '2020-07-04 00:00:00' AND '2020-07-04 23:59:59'

The table isn't mine but a client's, so unfortunately I'm not responsible for the data types of the columns. The DATE column, along with the rest of the data, is in varchar. As for the dates in the BETWEEN clause, I just put in a relatively small range for testing.
I have heard that CONVERT shouldn't be in the WHERE clause, but I need to convert it to dates in order to filter. What is the proper way of going about this?

A: Going to summarise my comments here, as they are "second class citizens" and thus could be removed.
Firstly, the reason your query is slow is because of theCONVERT on the column DATE in your WHERE. Applying functions to a column in your WHERE will almost always make your query non-SARGable (there are some exceptions, but that doesn't make them a good idea). As a result, the entire table must be scanned to find rows that are applicable for your WHERE; it can't use an index to help it.
The real problem, therefore, is that you are storing a date (and time) value in your table as a non-date (and time) datatype; presumably a (n)varchar. This is, in truth, a major design flaw and needs to be fixed. String type values aren't validated to be valid dates, so someone could easily insert the "date" '20210229' or even 20211332'. Fixing the design not only stops this, but also makes your data smaller (a date is 3 bytes in size, a varchar(8) would be 10 bytes), and you could pass strongly typed date and time values to your query and it would be SARGable.
"Fortunately" it appears your data is in the style code 112, which is yyyyMMdd; this at least means that the ordering of the dates is the same as if it were a strongly typed date (and time) data type. This means that the below query will work and return the results you want:
SELECT TOP 10 * --Ideally don't use * and list your columns properly
FROM dbo.[Table]
WHERE [DATE] >= '20210704' AND [DATE] < '20210705'
ORDER BY {Some Column};

A: you can use like this to get better performance:
SELECT TOP 10 *
FROM Table
WHERE cast(DATE as date) BETWEEN '2020-07-04' AND '2020-07-04' and cast(DATE as time) BETWEEN '00:00:00' AND '23:59:59'

No need to include time portion if you want to search full day.


text:
Q: Jump to tag in vim (Windows, Parallels) I am using vim & gvim (version 7.4) in Windows under Parallels. I am trying to use CTRL+] to jump to tags under the cursor in help files but nothing happens. In gvim, I can double click on the tag and this works but I  would like to use CTRL+].
Does anybody have any ideas why this would not be working and how I can fix it? I would rather not remap CTRL+] to some other key combination.

A: I had this same issue. I fixed it by uninstalling parallels tools. I now run it headless and connect with Microsoft Remote Desktop.


text:
Q: wpf popup inside user control, button not respond to events or commands I have the following user control xaml
<UserControl x:Class="tgltestpopup"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <Popup  IsOpen="{Binding ElementName=tgl,Path=IsChecked}" StaysOpen="False">
        <Border Background="White">
            <StackPanel>
                <Button Click="showMsgEvent" Content="close"></Button>
                <Button Content="test me" Command="{Binding showMsgCommand,RelativeSource={RelativeSource AncestorType=UserControl}}"></Button>

            </StackPanel>
        </Border>
    </Popup>
    <ToggleButton Content="open popup" x:Name="tgl" HorizontalAlignment="Center" VerticalAlignment="Center"/>

</Grid>

this user control is used inside a datagrid Template column . How ever when i click the toggle button the popup displays but the buttons not respond to the events or commands . The buttons are highlighted when the mouse pass over them but when i click them do nothing!.even when i press the button the button state dose not change . Looks like don't recognize the button that i clicked it.
Any suggestion?

A: I got this working by using an EventTrigger and PreviewMouseDown. For some reason, MouseDown is not working and i think this is the reason the simple command fails too. Maybe the focus is changing and the button is not really clicked in fact.
But anyway, here is what I came up with:
<Window x:Class="TestPopupInDataTemplate.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestPopupInDataTemplate"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid AutoGenerateColumns="False"
              ItemsSource="{Binding Source}"
              CanUserAddRows="False">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="First">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <local:TestUserControl/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>

        </DataGrid.Columns>
    </DataGrid>
</Grid>

To get over it fast, i didn't add a separate view model for the Window:
public partial class MainWindow : Window
{
    public ObservableCollection<TestViewModel> Source { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        Source = new ObservableCollection<TestViewModel>() { new TestViewModel() { Name = "Test Name11" } };
        this.DataContext = this;
    }
}

Here is UserControl which is set on the DataTemplate:
<UserControl x:Class="TestPopupInDataTemplate.TestUserControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:TestPopupInDataTemplate"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="GridName">
    <ToggleButton Content="open popup" x:Name="tgl" HorizontalAlignment="Center" VerticalAlignment="Center"/>

    <Popup  IsOpen="{Binding ElementName=tgl,Path=IsChecked}"
            StaysOpen="False"                >
        <Border Background="White">
            <StackPanel>
                <!--<Button Click="showMsgEvent" Content="close"></Button>-->
                <Button Content="{Binding Name}"
                        Margin="5"
                        Width="90"
                        Height="30"
                        FontSize="20"                            >
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="PreviewMouseDown">
                            <i:InvokeCommandAction Command="{Binding ShowMsgCommand}"
                                                   CommandParameter="{Binding}"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Button>

            </StackPanel>
        </Border>
    </Popup>
</Grid>

Its view model :
public class TestViewModel
{
    public ICommand ShowMsgCommand { get; set; }

    public string Name { get; set; }
    public TestViewModel()
    {
        ShowMsgCommand = new OpenMsgCommand(this);
    }
    public void OpenMessage()
    {
        Console.WriteLine("test");
    }
}

And the command:
public class OpenMsgCommand : ICommand
{
    private TestViewModel _vm;

    public OpenMsgCommand(TestViewModel vm)
    {
        _vm = vm;
    }
    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        _vm.OpenMessage();
    }
}

Here is the result:

As you see, both the command and command parameter are working as expected.
You need to add a reference to System.Windows.Interactivity in order to use Interaction.Triggers.


text:
Q: Finding lines that include two or more words from a list I have written this code which checks which lines in an infile matches all of the keywords in a keyword file. Now, I want it instead to find all lines that just include two or more of the keywords in any combination.
infile = open('/Path/#input.txt', 'r')
outfile = open('/Path/#output.txt', 'w')

# Read a textfile containing keywords to find
# (and strip the newline character '\n')
keywords = [line.strip() for line in open('Path/#keywords.txt')]

# See which lines in the infile match ALL of the keywords
# and write those lines to the outfile
for line in infile:
    if all(k in line for k in keywords):
        outfile.write(line)

A: Here is one way
if len(set(line.split()).intersection(keywords)) > 2:

This splits the line into words with line.split() first
. Then uses sets intersection function to find the common elements of 2 sets


text:
Q: Existence of a unique solution. Consider the integral equation for some given function $y(t)\in C[0,1]$ and a given constant $\lambda$ with $|\lambda|<1$,
$$x(t)-\lambda\int_0^1 e^{t-s}x(s)ds=y(t).$$
Show that there exists a unique solution $x(t)\in C[0,1]$.

A: First, set $\displaystyle x_0(t) = y(t) + \frac{λ}{1 - λ} \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s$. Because$$\begin{align*}
y(t) + λ \int_0^1 \mathrm{e}^{t - s} x_0(s) \,\mathrm{d}s &= y(t) + λ \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s + λ \int_0^1 \mathrm{e}^{t - s} \left(\frac{λ}{1 - λ}\int_0^1 \mathrm{e}^{s- u} y(u) \,\mathrm{d}u\right) \,\mathrm{d}s\\
&= y(t) + λ \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s + \frac{λ^2}{1 - λ} \int_0^1 \int_0^1 \mathrm{e}^{t - u} y(u) \,\mathrm{d}u\mathrm{d}s\\
&= y(t) + λ \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s + \frac{λ^2}{1 - λ} \int_0^1 \mathrm{e}^{t - u} y(u) \,\mathrm{d}u \int_0^1 \mathrm{d}s\\
&= y(t) + λ \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s + \frac{λ^2}{1 - λ} \int_0^1 \mathrm{e}^{t - u} y(u) \,\mathrm{d}u\\
&= y(t) + \frac{λ}{1 - λ} \int_0^1 \mathrm{e}^{t - s} y(s) \,\mathrm{d}s = x_0(t),
\end{align*}$$
then $x_0(t)$ is a solution to the given equation.
Now suppose $x(t)$ is a solution to the given equation, then$$
x(t) = y(t) + λ \int_0^1 \mathrm{e}^{t - s} x(s) \,\mathrm{d}s = y(t) + λ \mathrm{e}^t \int_0^1 \mathrm{e}^{-s} x(s) \,\mathrm{d}s.
$$
Denote $\displaystyle c = λ \int_0^1 \mathrm{e}^{-s} x(s) \,\mathrm{d}s$, then $x(t) = y(t) + c\mathrm{e}^t$. Therefore,$$\begin{align*}
y(t) + c\mathrm{e}^t &= x(t) = y(t) + λ \mathrm{e}^t \int_0^1 \mathrm{e}^{-s} x(s) \,\mathrm{d}s = y(t) + λ \mathrm{e}^t \int_0^1 \mathrm{e}^{-s} (y(s) + c\mathrm{e}^s) \,\mathrm{d}s\\
&= y(t) + λ \mathrm{e}^t \left(\int_0^1 \mathrm{e}^{-s} y(s) \,\mathrm{d}s + c\right),
\end{align*}$$
which implies$$
c = λ \left(\int_0^1 \mathrm{e}^{-s} y(s) \,\mathrm{d}s + c\right),
$$
i.e.$$
c = \frac{λ}{1 - λ} \int_0^1 \mathrm{e}^{-s} y(s) \,\mathrm{d}s.
$$
Hence $x(t) = y(t) + c\mathrm{e}^t \equiv x_0(t)$, so the solution to the given equation is unique.


text:
Q: Android WebView loadDataWithBaseURL with link equals BaseURL works incorrectly I load HTML to my WebView with
this.webViewer.loadDataWithBaseURL(BASE_URL, completeNewsTemplate,
                "text/html", "UTF-8", null);

Where BASE_URL = "http://www.example.ru" i use it for WebView loading images with relative images src's
if in HTML soruce i got href link like
Example

Then it's just reload current webview, and target attribute does make anything for open new window.
How make webview open link in new window?

A: Here is solution.
If your link equals base url WebView think that you want work with current page only.
You can try catch it like
webViewer.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                System.out
                    .println("DetailViewActivity.onCreate(...).new WebViewClient() {...}.onPageStarted()");
                    super.onPageStarted(view, url, favicon);

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                            System.out
                    .println("DetailViewActivity.onCreate(...).new WebViewClient() {...}.onPageFinished()");
                super.onPageFinished(view, url);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out
                    .println("DetailViewActivity.onCreate(...).new WebViewClient() {...}.shouldOverrideUrlLoading()");
                return false;

            }

        });

But then you click to your link in webView you never get fired shouldOverrideUrlLoading or onPageStarted only onPageFinished with your base_url.
So my solition is use for base url another domain without www prefix.
Here example if you domain www.example.com use base url example.com


text:
Q: Kubernetes: Service External IP is not working I am deploying k8s in a private lab and using --external-ip option in the k8s service:
Name:              my-service
Namespace:         default
Labels:            <none>
Annotations:       <none>
Selector:          app=myapp
Type:              ClusterIP
IP:                10.98.4.250
External IPs:      10.10.16.21
Port:              http  80/TCP
TargetPort:        80/TCP
Endpoints:         192.168.237.3:80

Session Affinity:  None
Events:            <none>

user@k8s-master:~$ kubectl get svc
NAME         TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1     <none>        443/TCP   22h
my-service   ClusterIP   10.98.4.250   10.10.16.21   80/TCP    7m

But I can only curl the endpoint from the same node (k8s-master) via the External IP. If I use other node (which is the same subnet as k8s-master), curl will not work.
Running tcpdump and I can see the http request is coming thru but there is no reply.
How does External IP work in service?

A: If you check the kubectl source code in github, you would find that external-ip is only documented in kubectl expose with the description as following:

cmd.Flags().String("external-ip", "", i18n.T("Additional external IP
  address (not managed by Kubernetes) to accept for the service. If this
  IP is routed to a node, the service can be accessed by this IP in
  addition to its generated service IP."))

When adding external-ip parameters to a service, Kubernete would likely to do nothing as it does not manage the behavior of this IP nor its routing inside the cluster. It just assumes that this IP would be routed to a node in the cluster. It would be treated same as the generated service IP.
To have an external IP working, configurations similar to Service type LoadBalancer or NodePort should be applied. I think it is just more of an annotation purpose.


text:
Q: How to use DECIMAL(10,2) in prisma migrate tool? I need save DECIMAL(10,2) in database. In MySQL there is DECIMAL type.
MySQL docs:

https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html

Prisma 2.0 docs:

https://www.prisma.io/docs/reference/database-connectors/mysql

Possible Prisma 2.0 flows:

https://www.prisma.io/docs/understand-prisma/introduction#typical-prisma-workflows

*

*I am using Prisma Migrate flow and see that mapping is constrained.

*I see that it can be done in Introspection flow.

Are there any plans of support mysql data types like DECIMAL(10,2) in Prisma Migrate flow?

A: Full support for native types has been added in prisma/prisma@v2.15.0
datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Product {
  id Int @id @default(autoincrement())
  code String
  price Decimal @db.Decimal(9,2)
}

A: Currently prisma migrate doesn't support the Decimal type. You can track the issue for custom DB types here
As a workaround, you would have to use a custom migration tool and specify the Decimal field that you require and then run prisma introspect which will get all the fields from your DB and populate the schema.prisma.


text:
Q: Apache server configuration name resolution (virtual host naming + security) I have just setup a minimal (hopefully secure? - comments welcome) apache website using the following configuration file:
<VirtualHost *:80>
        ServerName foobar.com
        ServerAlias www.foobar.com
        ServerAdmin webmaster@foobar.com
        DocumentRoot /path/to/websites/foobar/web
        DirectoryIndex index.php

        # CustomLog with format nickname
        LogFormat "%h %l %u %t \"%r\" %>s %b" common
        CustomLog "|/usr/bin/cronolog /var/log/apache2/%Y%m.foobar.access.log" common

        LogLevel notice
        ErrorLog "|/usr/bin/cronolog /var/log/apache2/%Y%m.foobar.errors.log"

        <Directory />
                AllowOverride None
                Order Deny,Allow
                Deny from all
        </Directory>

        <Directory /path/to/websites/>
                Options -Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

I am able to access the website by using www.foobar.com, however when I type foobar.com, I get the error  'Server not found' - why is this?
My second question concerns the security implications of the directive:
<Directory /path/to/websites/>
        Options -Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
</Directory>

in the configuration above. What exactly is it doing, and is it necessary?. From my (admitedly limited) understanding of Apache configuration files, this means that anyone will be able to access (write to?) the /path/to/websites/ folder. Is my understanding correct? - and if yes, how is this not a security risk?

A: Regarding question 1, is the DNS for @ (ie. foobar.com) definitely pointing to the same site.
1) Check your DNS A records.
2) If you ping them, does it resolve to the same IP?
3) Is it your apache instances saying server not found?


text:
Q: Formatação/Quebra de linha de código no Android Studio Quando faço a reformatação automática Ctrl+L o código fica identado, porém as linhas não quebram, como acontece no Eclipse e no Netbeans, de modo que eu tenho ficar arrastando a janela constantemente para ver o final de uma linha maior, como no exemplo:
NtpTimeProvider ntpTimeProvider = new NtpTimeProvider(InetAddressFactory.newFromHostString("192.168.0.1"), nodeMainExecutor.getScheduledExecutorService());

Alguém saberia onde eu posso configurar isso para que as linhas quebrem e o código fique do tamanho da janela?

A: Você precisa ir em Files > Settings > Editor > Code Style > Java > wrapping and Braces > Marcar a opção: Ensure right margins is not exceeded


text:
Q: configure 'other users are able to view my desktop' via command line I am trying to get vino-server to work via ssh on an Ubuntu 17.04 machine. Specifically, I want to set the option that 'other users are able to view my desktop'. Ubuntu's documentation on vino states to set this option via the gui (i.e., Menu > Settings > Remote Access). However, I cannot access the gui on my remote machine, so I am looking for a configuration file where I can set this 'other users able to view my desktop' option. Does anyone know which configuration file this is?
An older post from 2010 states that I can access this configuration file via ~/.gconf, however there is no ~/.gconf folder, nor a gconf.xml file anywhere on my machine.

A: Try something like this?
gconftool-2 -s -t bool /desktop/gnome/remote_access/enabled true
Source: https://linuxexplore.com/tips-tricks/configure-remote-desktop-from-command-line/
Not sure where these things are actually stored, but gconf is generally modified by issuing commands via gconftool or some other CLI tool.

A: The relevant settings are not contained in a configuration file as such - but in the dconf database associated with the remote desktop session that you are trying to view. You can modify them using either
DISPLAY=:0 gsettings set org.gnome.Vino view-only 'true'
DISPLAY=:0 gsettings set org.gnome.Vino enabled 'true'

or
DISPLAY=:0 dconf write /org/gnome/desktop/remote-access/view-only  'true'
DISPLAY=:0 dconf write /org/gnome/desktop/remote-access/enabled 'true'

(adjust the DISPLAY value if :0 is not your remote physical desktop).


text:
Q: Read multiple lines from xml I am trying to fetch data from a xml file in java using sax parser. I successfully got small amount of data but when data becomes too large and in multiple lines it gives only two lines of data, not all the lines. I am trying following code-
InputStreamReader isr = new InputStreamReader(is);
InputSource source = new InputSource(isr);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader xr = parser.getXMLReader();
GeofenceParametersXMLHandler handler = new GeofenceParametersXMLHandler();
xr.setContentHandler(handler);
xr.parse(source);

And my GeofenceParametersXMLHandler is-
private boolean inTimeZone = false;
private boolean inCoordinate = false;
private boolean outerBoundaryIs = false;
private boolean innerBoundaryIs = false;
private String timeZone;
private List<String> innerCoordinates = new ArrayList<String>();
private String outerCoordinates;

public String getTimeZone() {
    return timeZone;
}

public List<String> getInnerCoordinates() {
    return innerCoordinates;
}

public String getOuterCoordinates() {
    return outerCoordinates;
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
    super.characters(ch, start, length);
    if (this.inTimeZone) {
        this.timeZone = new String(ch, start, length);
        this.inTimeZone = false;
    }

    if (this.inCoordinate && this.innerBoundaryIs) {
        this.innerCoordinates.add(new String(ch, start, length));
        this.inCoordinate = false;
        this.innerBoundaryIs = false;
    }

    if (this.inCoordinate && this.outerBoundaryIs) {
        this.outerCoordinates = new String(ch, start, length);
        this.inCoordinate = false;
        this.outerBoundaryIs = false;
    }
}

@Override
public void endElement(String uri, String localName, String name) throws SAXException {
    super.endElement(uri, localName, name);
}

@Override
public void startDocument() throws SAXException {
    super.startDocument();
}

@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
    super.startElement(uri, localName, name, attributes);

    if (localName.equalsIgnoreCase("timezone")) {
        this.inTimeZone = true;
    }

    if (localName.equalsIgnoreCase("outerBoundaryIs")) {
        this.outerBoundaryIs = true;
    }

    if (localName.equalsIgnoreCase("innerBoundaryIs")) {
        this.innerBoundaryIs = true;
    }

    if (localName.equalsIgnoreCase("coordinates")) {
        this.inCoordinate = true;
    }
}

And the xml file is-
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2"
xmlns:gx="http://www.google.com/kml/ext/2.2">

<Placemark>
   <name>gx:altitudeMode Example</name>
   <timezone>EASTERN</timezone>
   <Polygon>
      <extrude>1</extrude>
      <altitudeMode>relativeToGround</altitudeMode>
      <outerBoundaryIs>
      <LinearRing>
         <coordinates>
        -77.05788457660967,38.87253259892824,100
        -77.05465973756702,38.87291016281703,100
        -77.05315536854791,38.87053267794386,100
        -77.05552622493516,38.868757801256,100
        -77.05844056290393,38.86996206506943,100
        -77.05788457660967,38.87253259892824,100
      </coordinates>
    </LinearRing>
  </outerBoundaryIs>
</Polygon>

I always got two line of data for coordinates. But when they are in single line I got complete data. How to fetch complete data in multiple line?
Thanks in Advance.

A: The characters() method won't necessarily give you all the text data in one go (this is a very common misconception, btw).
The proper approach is to concatenate all the data returned by successive calls to characters() (using a StringBuilder or similar). Once your endElement() method is called, you can then treat that text buffer as complete and process it as such.
From the doc:

The Parser will call this method to report each chunk of character
  data. SAX parsers may return all contiguous character data in a single
  chunk, or they may split it into several chunks

Often you see that for a small XML doc one call to characters() will suffice. However as your XML doc increases in size, you'll find that due to buffering etc. you'll start getting multiple calls. Consequently each call treated on its own appears to be incomplete.


text:
Q: Clojure Practice : Interleave - outOfmemoryError I am trying to implement 'interleave' for myself but get a outOfMemoryError
my version should be same as:
(interleave [1 2] [3 4])

Here is the code:
(defn myInterleav [col1 col2]
  (loop [r []
         c1 (first col1)
         c2 (first col2)]
    (if (and c1 c2)
      (recur (conj (conj r c1) c2)
        (next col1)
        (next col2))
      r)))

(myInterleav [1 2] [3 4])

Version 2 as 'noisesmith' suggested to rebind args, but get nullPointer error.
(defn myIL2 [col1 col2]
  (loop [m  []
         [e1 & c1] col1
         [e2 & c2] col2]
    (if (and e1 e2)

      (recur (conj m e1 e2)
             c1
             c2)
      m
    )))

A: Your function never returns if neither input is empty, because the bindings for col1 and col2 cannot change. You need to rework your loop to rebind to the next of the previous binding each time, rather than the next of the initial function input. Something like this should work:
  [...
  [e1 & c1] col1
  [e2 & c2] col2]
(if (and (seq col1) (seq col2))
    (recur (conj r e1 e2)
           c1
           c2)
...)


text:
Q: Select view depending on screen resolution I have a WPF application made for an LCD display with a specific resolution. The WPF application is fixed size. The view is bound to its view model by DataTemplates like this:
<DataTemplate DataType="{x:Type vm:IdleViewModel}">
    <v:IdleView/>
</DataTemplate>

Now I would like to make this application available for a second LCD display type. The view will be totally different. Is there any way to bind the view model to a different view depending the resolution?

A: There is more than one way to do this depending on your requirements. Let me focus on two different approaches that might work for you. How to find out the screen resolution is another topic, see:

*

*How to get the size of the current screen in WPF?
Data Template Selector
You can create a data template selector that returns a DataTemplate based on screen resolution. The mechanism to determine the screen resolution is take from the question above.
public class ResolutionDependentTemplateSelector : DataTemplateSelector
{
   public DataTemplate InvalidResolutionTemplate { get; set; }
   public DataTemplate Resolution1Template { get; set; }
   public DataTemplate Resolution2Template { get; set; }

   public override DataTemplate SelectTemplate(object item, DependencyObject container)
   {
      if (IsTargetResolution(480, 576))
         return Resolution1Template;

      if (IsTargetResolution(720, 480))
         return Resolution2Template;

      return InvalidResolutionTemplate;
   }

   private bool IsTargetResolution(double width, double height)
   {
      return Math.Abs(SystemParameters.PrimaryScreenWidth - width) < 1 &&
             Math.Abs(SystemParameters.PrimaryScreenHeight - height) < 1;
   }
}

You can assign this selector in XAML. Since I do not know which control you are using, this example uses a simple ContentControl. The property to assign it to may vary.
<ContentControl>
   <ContentControl.Resources>
      <DataTemplate x:Key="Resolution1Template">
         <!-- ...your markup. -->
      </DataTemplate>
      <DataTemplate x:Key="Resolution2Template">
         <!-- ...your markup. -->
      </DataTemplate>
   </ContentControl.Resources>
   <ContentControl.ContentTemplateSelector>
      <local:ResolutionDependentTemplateSelector Resolution1Template="{StaticResource Resolution1Template}"
                                                 Resolution2Template="{StaticResource Resolution2Template}"/>
   </ContentControl.ContentTemplateSelector>
</ContentControl>

Resource Dictionaries
You could create separate resource dictionaries that contain the data template for each different screen along with other specific resources that only apply to a certain screen size. Then on startup (e.g. in the Apps OnStartup method), merge the resource dictionary that fits the screen resolution into the application resources (App.Resources).

Depending on the size and complexity of your application you could separate the controls for each distinct screen resolution into its own project, similar to the resource dictionary approach. If the application is always run on a specific LCD type and never on another, it would also be possible to create targets for each, so each "platform" contains only the resources it needs.

A:
Is there any way to bind the view model to a different view depending the resolution?

Not using a single view model type and a corresponding DataTemplate alone.
You could either

*

*Use two different view model types and views

*Implement the view to adopt itself according to the view model (which should then know about the current screen resolution)

*Use a DataTemplateSelector to select the appropriate view based on some logic other than just the type of the view model


text:
Q: $\operatorname{Hom}_R(F,R)$ is isomorphic to $F$ where $F$ is a free $R$-module of finite rank
[Dummit and Foote, Exercises 10.3, problem 13] Suppose $R$ is a commutative ring with $1$. Suppose $F$ is a free $R$-module of finite rank. Then show that $\operatorname{Hom}_R(F,R) \cong F$.

Suppose the basis of $F$ is $\{a_1, a_2,\dots,a_n\}$. I want to show that $\operatorname{Hom}_R(F,R)$ is a free $R$-module of rank $n$. Suppose we define $\{e_i\mid i=1,2,\dots,n\}\subseteq \operatorname{Hom}_R(F,R)$ such that $e_i(a_j)=1$ when $i=j$, and $e_i(a_j)=0$ when $i\neq j$. I am guessing that any homomorphism from $F$ to $R$ can be written as an element of the linear span of $\{e_i\mid i=1,2,...n\}$, but I am stuck here.
Any help would be appreciated. Thank you.

A: This is the correct idea. As a hint to help you finish, notice that any $v\in F$ can be written as $v=\sum r_ja_j$, for some elements $r_j\in R$. For each $1\le i \le n$, if we apply $e_i$ to $v$, we see $e_i(v) = r_i$, so we can write
$$
v = \sum e_j(v)a_j.
$$
Now let $\varphi\colon F\to R$ be an arbitrary homomorphism, and consider $\varphi(v)$...

As a side note, the basis for $\operatorname{Hom}(F,R)$ you have described is commonly called the dual basis for $\operatorname{Hom}(F,R)$ given the basis $\{a_1,\dots,a_n\}$ for $F$, and people will also sometimes use the notation $a_i^*$ for the elements $e_i$ you defined.

A: Well, any $f\in F^*$ can obviously be written as
$$f=\sum_{i=1}^n f(a_i)e_i.$$


text:
Q: Refresh token with Graph OAuth v2.0 I'm requesting a user's info via Microsoft Graph. I use the 2.0 endpoint.
This is my login function:
login() {
    hello('msft').login({scope: Configs.scope}).then(
      () => {
        this.zone.run(() => {
          this.meService.getMe().subscribe(data => {
              localStorage.setItem('username', data.mail);
              localStorage.setItem('jobtitle', data.jobTitle);
              localStorage.setItem('loggedin', 'yes');
            },
            err => {
            console.log(err);
            },
            () => {
              this.router.navigate(['/home']);
            });
        });
      },
      e => console.error(e.error.message)
    );
  }

This is my init function:
initAuth() {
    this.redirect_uri = window.location.href;
    hello.init({
        msft: {
          id: Configs.appId,
          oauth: {
            version: 2,
            auth: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
          },
          scope_delim: ' ',
          form: false
        },
      },
      {redirect_uri: window.location.href}
    );
  }

And here I am getting the access token:
getAccessToken() {
    const msft = hello('msft').getAuthResponse();
    console.log(msft);
    const accessToken = msft.access_token;
    return accessToken;
  }

I get an access token, via which I can login. However, I get no refresh token. From what I read, you get the refresh and the access token via the /token endpoint. As far as I can see, I only use the /authorize endpoint and it works?
This poses a problem. I can't refresh my token!
A response looks like this:
access_token:
"This is private, but it's a very long string"
client_id:"e6c987d2-8bdc-4f1a-bafc-04ba3d51f340"
display:"popup"
expires:1524649746.548
expires_in:3599
network:"msft"
redirect_uri:"http://localhost:4200/"
scope:"basic,User.Read"
session_state:"89a68bd2-5ae5-4df2-88d0-d28718fd10bc"
state:""
token_type:"Bearer"

Any help would be appreciated!

A: Since you're using the Implicit grant, you cannot use Refresh Tokens. They're only supported using the Authorization Code grant.
In order to use Refresh Tokens, you'll need to switch to the Authorization Code grant and implement the server-side code to process the authorization code into an access token. You'll also need to request the scope offline_access which triggers the generation of a refresh_token.


text:
Q: Java Jackson: JSON value unknown I'm still learning how to use Jackson...
So I have a JSON object that has a value that sometimes is an Integer, a long String, or a List
Value: Integer
{
  "id":1,
  "active":1,
  "name":"name1",
  "value":155,
  ...

Value: String
{
  "id":2,
  "active":1,
  "name":"name2",
  "value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...",
  ...

Value: List
{
  "id":3,
  "active":1,
  "name":"name3",
  "value":[
    "One",
    "Two",
    "Three",
    "Four"],
  ...

So all together it looks like...
{
  {
      "id":1,
      "active":1,
      "name":"name1",
      "value":155,
      ...
  },
  {
      "id":2,
      "active":1,
      "name":"name2",
      "value":"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book...",
      ...
  },
  {
      "id":3,
      "active":1,
      "name":"name3",
      "value":[
        "One",
        "Two",
        "Three",
        "Four"],
      ...
  }
}

Here my POJO Model
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY)
public class OQScoresRows {
  private int id;
  private int active;
  private String name;
  private List<String> value;
  ... ...

Here's my mapper code
ObjectMapper mapper = new ObjectMapper();
try{
  POJO obj = mapper.readValue(<JSONOBJECT>, POJO.class);
}catch(JsonParseException e){
  return mapper.writeValueAsString(e);
}

The problem is when I execute my code, I get the following error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_NUMBER_INT token

It's clear to me that this is happening because "value" can contain one of three different types, how do I make my code flexible enough to accommodate the types...I can always in other methods detect if the value is an int, List, or String but I first need to model (don't I)...
My question is simple: how do I make my code flexible enough to accommodate the types...

A: If it can be either of Integer, List and String then you can declare it as an Object and cast it later with instanceof, e.g.:
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY)
public class OQScoresRows {
  private int id;
  private int active;
  private String name;
  private Object value;

After, deserializeing, you can write similar logic to the following:
if(value instanceof Integer){
    //do something after casting it to Integer
}else if(value instanceof List){
    //do something after casting it to List
}else if(value instanceof String){
    do something after casting it to String
}

A: If-else statement is fine for your question, but it's all string format in json objects, so you have to figure out a way to identity data types from values. For example, Integer.valueOf(value) to identity int; start with [ to identity list; another is string type. You can refer to this answer, which is a general way to convert the json string to an object or a list.


text:
Q: Doing curl POST request as an npm script I have a new script in my npm scripts in my package.json and the single quotes/double quotes are causing this to break. Namely the internal double quotes inside of the payload
"slack": "curl -X POST --data-urlencode 'payload={"channel": "#builds", "text": "New Build Incoming!"}' https://hooks.slack.com/services/abc/123/00000",
Any tips on how to get this working?

A: Just use \ before double quotes
"slack": "curl -X POST --data-urlencode 'payload={\"channel\": \"#builds\", \"text\": \"New Build Incoming!\"}' https://hooks.slack.com/services/abc/123/00000",


text:
Q: Spring hibernate type validation with multiple error messages I'm wondering if such a thing is possible.
I have a general DTO class called "Device". Device holds ID and IP.
I've set a inner regexp validation to verify if the IP is entered correctly.
But now I want to have another validation of type "verify if this IP is not used by another device"(for both update and create cases).
For this I have written a custom Type orientated ConstraintValidator, where I accomplish the task of checking if the is no other device with the given IP.
But from this point I wanted to go further, and to have several checks and several response error messages from one ConstraintValidator, doing random checks on the Device object.
On this point I couldn't find if I could redefine validator's error message. Is this possible?

A: You can do this using the following function I use for my own API :
public static void setNewErrorMessage(String newErrorMessage, ConstraintValidatorContext context) {

    context.disableDefaultConstraintViolation();
    context.buildConstraintViolationWithTemplate(newErrorMessage)
            .addConstraintViolation();
}

The context object here is passed in the isValid function of any ConstraintValidator implementing class.
This way you'll be able to do something like :
if(hasError1()) {
     setNewErrorMessage(ERROR1_MESSAGE, context);
     return false;
}

if(hasError2()) {
     setNewErrorMessage(ERROR2_MESSAGE, context);
     return false;
}

A: You should use the Hibernate Bean Validation API, to build something like the code below.
HibernateValidatorConfiguration configuration = Validation
        .byProvider( HibernateValidator.class )
        .configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( Car.class )
        .property( "manufacturer", FIELD )
            .constraint( new NotNullDef() )
        .property( "licensePlate", FIELD )
            .ignoreAnnotations( true )
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( RentalCar.class )
        .property( "rentalStation", METHOD )
            .constraint( new NotNullDef() );

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

Take a look at http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-programmatic-api


text:
Q: ¿Como realizar una consulta INNER JOIN mediante query Laravel 6? (htmlspecialchars() expects parameter 1 to be string, array given) estoy empezando a aprender laravel 6 y me gustaria saber como puedo realizar esta consulta.
Intente probando este código en el web.php (rutas de laravel):
$as = DB::select("SELECT tipovehis.tipo
                FROM tipovehis
                INNER JOIN vehiculos
                ON vehiculos.tipovehis_id = tipovehis.id
                WHERE vehiculos.tipovehis_id = 3");
return $as;

y me devuelve la información esperada. Sin embargo cuando quise probar el mismo codigo para mostrarlo en una tabla de la siguiente forma:
<td>
{{
  $as = DB::select("SELECT tipovehis.tipo
          FROM tipovehis
          INNER JOIN vehiculos
          ON vehiculos.tipovehis_id = tipovehis.id
          WHERE vehiculos.tipovehis_id = 3")
}}
</td>

Me aparece el siguiente error:
htmlspecialchars() expects parameter 1 to be string, array given

Podria alguien explicarme cual es el error? O es que estoy haciendo mal el inner join?.... Muchas Gracias de ante mano.
Edit
Dado que me han mencionado varias veces ya lo de los modelos lo explicare. He estado leyendo la documentacion e investigando pero todos los modelos relacionados que encuentro en hasManyThrough tienen el tipico ejemplo de:
Countrys 1:N Users 1:N Posts
y no pude encontrar un ejemplo de relaciones Countrys 1:N Users N:1 Post (entiendo que la relacion anterior no tiene sentido, pero es un ejemplo) y eso me trae problemas al intentar hacer la consulta desde mi modelo puesto que se como hacer la relacion hasManyThrough de los modelos en el caso:
Countrys 1:N Users 1:N Posts
Pero no se como hacer la relacion hasManyThrough en el caso:
Countrys 1:N Users N:1 Post
Pensandolo bien hubiese sido una mejor pregunta el edit...

A: Dado que usas laravel no es necesario o incluso bien visto que escribas tus consultas en SQL puro ya que estás desaprovechando todo el potencial de incluir a los modelos en conjunto con las relaciones de Eloquent; dado lo anterior propongo un par de respuestas.
Opción 1
Puedes implementar el uso del modelo TipoVehiculo para representar a la tabla tipovehis y posteriormente encadenar los métodos necesarios para complementar
tu JOIN de esta forma
$data = TipoVehiculo::select('tipovehis.tipo')
                  ->join('vehiculos', 'vehiculos.tipovehis_id', '=', 'tipovehis.id')
                  ->where('vehiculos.tipovehis_id', 3)
                  ->get();

Opción 2
Es nuevamente hacer uso de los modelos, pero esta vez declarar las relaciones que existen en cada uno de ellos.
En el modelo TipoVehiculo vas a declarar lo siguiente:
class TipoVehiculo extends Model
{
    public function vehiculos()
    {
        return $this->hasMany(Vehiculo::class);
    }
}

Posterior ahora en el modelo Vehiculo declara la siguiente clase
class Vehiculo extends Model
{
    public function tipoVehiculo()
    {
        return $this->belongsTo(TipoVehiculo::class);
    }
}

Finalmente en tu controlador puedes construir la siguiente consulta:
$data = TipoVehiculo::with(['vehiculos' => function($query){
    $query->where('vehiculos.tipovehis_id', 3);
}])->get();

Donde hacemos una carga ambiciosa del modelo con sus respectivas relaciones por medio de eager loading

A: Si lo intentas de esta forma
    $reporte = DB::table("tipovehis as ti")
    ->join('vehiculos as ve', 'ti.id', 've.tipovehis_id ')
    ->select(
        DB::raw("count(ti.tipo) as cantidad"),
        've.tipovehis_id',
        'ti.tipo as tipo'
    )
    ->where("ve.tipovehis_id",3)
    ->get();


text:
Q: Can a Child contract change values of a parent contract in Solidity If we have 2 contracts like so :
contract A {
  struct SampleA{
    uint id;
    bytes32 name;
    bytes32 toChange;
  }
  mapping (uint=> SampleA) public idToStruct;
}

contract B is A{
  function changeVar (bytes32 newVar) public {
    idToStruct[0].toChange = newVar;
  }
}

Can I update variable in Contract A from contract B like this?
Is this possible in solidity, if not is there a workaround?

A: Yes, you can modify properties of the parent contract, as long as the property is not private.
Docs: https://docs.soliditylang.org/en/v0.8.6/contracts.html#visibility-and-getters


text:
Q: Why does the program keep getting terminated when I'm copying vector data to another vector? This is one of the weirdest things I have ever seen in c++...after running this the program gets terminated. I tracked the source of the issue to the for loop that copies the data of the 1st vector to the 2nd vector, but I can't understand why the program auto terminates after I run it.
int main() {
    vector<string> vectorTest;
    vector<string> test;

    vectorTest.push_back("Data");

    for(unsigned int i = 0; i < vectorTest.size(); ++i){ //source of issue
        test[i] = vectorTest[i];
    }

    for(unsigned int i = 0; i < vectorTest.size(); ++i){
        cout << vectorTest[i] << "\n";
        cout << test[i] << "\n";
    }
}

A: vector test contains no items so test[i] will be accessing out of bounds. You should've resized this vector to proper size before iterating or used push_back.
test.resize(vectorTest.size());
for(unsigned int i = 0; i < vectorTest.size(); ++i){ //source of issue
    test[i] = vectorTest[i];
}

A: The vector test is empty so accessing test[i] is out of bounds and undefined behaviour.
There are a few ways to fix this, one:
for(unsigned int i = 0; i < vectorTest.size(); ++i){
    test.push_back(vectorTest[i]);
}

Two:
test.resize(vectorTest.size());
for(unsigned int i = 0; i < vectorTest.size(); ++i){
    test[i] = vectorTest[i];
}

And if all you want to do is copy the vector the following is far simpler:
test = vectorTest;

Or to add all of vectorTest to the end of test:
test.insert( test.end(), vectorTest.begin(), vectorTest.end() );


text:
Q: any option to show my answer above upvoted answers? I have answered a question. I would be the 25th to give the answer. My answer is shown at the last in the list. I am sure that my answer is correct and will solve the questioner's problem. How can my answer be shown on the top or near by so that others give a glance.

A: Time.
If your answer is indeed better and more correct than the others (and you should really think carefully before adding yet another answer when there are 24 others there already), it will get upvoted and over time will move up in the list.


text:
Q: Node.js hasOwnProperty does not work even when the property exists In my Node.js Express application, when the user is logged in via passport the user user object is saved in the request.
It looks something like this:
{
    "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad",
    "first_name": "Sam",
    "last_name": "Smith",
    "email": "sam@email.com",
    "password": "$2a$10$fXYBeoK6s.A8xo2Yfgx4feTLRXpdvaCykZxr7hErKaZDAVeplk.WG",
    "profile_uuid": "db172902-f3c9-456d-8814-53d07d4ea954",
    "isActive": true,
    "deactivate": false,
    "verified": true,
    "ProviderUuid": "7149f8f1-0208-41db-a78e-887e7811a169"
}

But not every user has the ProviderUuid key present. So before using its value I am trying to check if the ProviderUuid key is present in the user object
var user = req.user;
console.log('---- provider: ' + JSON.stringify(user));
console.log('--- prop: ' + user.hasOwnProperty('ProviderUuid')); //returns false
console.log('---- other method prop check: ' + Object.prototype.hasOwnProperty.call(user, "ProviderUuid")); //returns false
if('ProviderUuid' in user){
    //this returns true
}

So doing user.hasOwnProperty('ProviderUuid') and Object.prototype.hasOwnProperty.call(user, "ProviderUuid")) returns false, however 'ProviderUuid' in user returns true.
What am I missing here?

A: Since in works, the property must an inherited property, on one of user's prototype objects, rather than being on user itself. Here's a live example of such behavior:

const userProto = { foo: 'bar' };

// Create an empty object named `user` whose internal prototype is `userProto`:
const user = Object.create(userProto);

// False, user itself is an empty object, nothing's been assigned to it:
console.log(
  user.hasOwnProperty('foo')
);

// True, `foo` does exist on the *internal prototype* of the `user` object:
console.log(
  'foo' in user
);

// True, `foo` is a property directly on `userProto`:
console.log(
  userProto.hasOwnProperty('foo')
);

So, if you want to check for the existence of an inherited property named ProviderUuid, use the in operator like you're doing.

A: I tested code and all checks returned true.

var user = {
    "uuid": "caa5cb58-ef92-4de5-a419-ef1478b05dad",
    "first_name": "Sam",
    "last_name": "Smith",
    "email": "sam@email.com",
    "password": "$2a$10$fXYBeoK6s.A8xo2Yfgx4feTLRXpdvaCykZxr7hErKaZDAVeplk.WG",
    "profile_uuid": "db172902-f3c9-456d-8814-53d07d4ea954",
    "isActive": true,
    "deactivate": false,
    "verified": true,
    "ProviderUuid": "7149f8f1-0208-41db-a78e-887e7811a169"
};
console.log('---- provider: ' + JSON.stringify(user));
console.log('--- prop: ' + user.hasOwnProperty('ProviderUuid')); //returns false
console.log('---- other method prop check: ' + Object.prototype.hasOwnProperty.call(user, "ProviderUuid")); //returns false
if('ProviderUuid' in user){
    //this returns true
}

Try JSON.parse(), Maybe req.user saved as string


text:
Q: why is insert on table locked? I am trying something with transaction levels on mysql.
I have Session S1 and Session S2. S1 is working with default isolation lavel Repeatable Read. For S2 i set Isolation Level Serializable.
Here is the szenario:
S1:
set innodb_lock_wait_timeout = 5;
start transaction;

S2:
set session transaction isolation level serializable;
start transaction;
select count(*) from produkt;

S1:
select count(*) from produkt;
update kategorie set bezeichnung = 'Smartphone' where kategorieid = 1;

S2:
 insert into produkt(produktid, bezeichnung, kategorieid_fk) values (201, 'iPhone 8z', 1);

Can someone explain, why the insert into produkt from S2 is now blocked?
Here is the Tableschema:
    -- Exportiere Datenbank Struktur für transaktiondb
    CREATE DATABASE IF NOT EXISTS `transaktiondb`;
    USE `transaktiondb`;

    -- Exportiere Struktur von Tabelle transaktiondb.kategorie
    CREATE TABLE IF NOT EXISTS `kategorie` (
      `KategorieID` int(11) NOT NULL AUTO_INCREMENT,
      `Bezeichnung` varchar(255) NOT NULL,
      PRIMARY KEY (`KategorieID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    -- Exportiere Struktur von Tabelle transaktiondb.produkt
    CREATE TABLE IF NOT EXISTS `produkt` (
      `ProduktID` int(11) NOT NULL AUTO_INCREMENT,
      `Bezeichnung` varchar(255) NOT NULL,
      `KategorieID_FK` int(11) NOT NULL,
      PRIMARY KEY (`ProduktID`),
      KEY `fk_Produkt_Kategorie_idx` (`KategorieID_FK`),
      CONSTRAINT `fk_Produkt_Kategorie` FOREIGN KEY (`KategorieID_FK`) REFERENCES `kategorie` (`KategorieID`) ON DELETE NO ACTION ON UPDATE NO ACTION
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

A: You have a deadlock which MySQL describes as:

A situation where different transactions are unable to proceed, because each holds a lock that the other needs. Because both transactions are waiting for a resource to become available, neither will ever release the locks it holds.

Looking closer at the How to Minimize and Handle Deadlocks reads:

InnoDB uses automatic row-level locking. You can get deadlocks even in the case of transactions that just insert or delete a single row. That is because these operations are not really "atomic"; they automatically set locks on the (possibly several) index records of the row inserted or deleted.

Regarding the nature of innodb_lock_wait_timeout the documentation describe that it only applies to scenarios where inno_db_detect is disabled, which is not the default configuration:

The lock wait timeout value does not apply to deadlocks when innodb_deadlock_detect is enabled (the default) because InnoDB detects deadlocks immediately and rolls back one of the deadlocked transactions. When innodb_deadlock_detect is disabled, InnoDB relies on innodb_lock_wait_timeout for transaction rollback when a deadlock occurs. See Section 14.7.5.2, "Deadlock Detection and Rollback".

Also, as a general tip, you'll often want to use start transaction followed as quickly as possible by a commit or rollback and not leave the session "hanging" to minimize these issues.


text:
Q: Get parameters from a useState in Ionic React I'm trying to retrieve some data from a json to use later in a chart.
My issue is that using useState, it gets me a never type data, so I can't access fields.
const [myData, setData] = useState([]);

const url = 'url';

axios.get(url)
      .then(res => {
        setData(res.data);

        myData.forEach( e=> {
          console.log(e.name);
        })
      }).catch(function (error) {
        // handle error
      })

When i print the console.log the name results as an error because Property 'name' does not exist on type 'never'.
How could I fix this?
EDIT: I'm using Typescript

A: You should declare the type of useState to be any so that while accessing certain fields within it which can be undefined/null which misleads the compiler into thinking that myData array values won't be anything but undefined. You can explicitly define a type to avoid this
const [myData, setData] = useState<any[]>([]);


text:
Q: Trying to make my home-made WordPress website visible by public network Before creating this post I really did some thorough research, made few progress but now got stuck.

*

*LAMP wordpress setup in a Ubuntu box

*Local network behind a Humax firewall, which contains WAN with public IP address provided by ISP

*Managed to enable port forwarding pretty well for many ports including SSH and others for gaming, just that port 80 was absolutely not possible for some reason due to router or ISP protection.

*SO I had to adopt port 81 for Apache2, following the known procedures updating the conf files for Apache2.

*All working fine when accessing mysite.com:81 from internal 192.168.0.X....but when trying to reach from any public desktop or mobile hooked on public network, it keeps trying until a non response error comes out.

this is what I have in /var/www/html/wp-config.php:
efine('WP_HOME','http://192.168.0.19:81');
define('WP_SITEURL','http://192.168.0.19:81');
I switch UFW on/off and that doesnt change, even though I get UFW pretty open for now ( allowing almost everything).
My DNS settings are native as form LInux installation; I dont have a domain for time being; I am targeting all via IP address.
LAst and relevant: when trying 189.X.Y.Z:81/index.html from my mobile in a public network, I get the Apache2 HTML page perfectly.
thank you!
gustavo

A: I would imagine port 80 is being blocked by your ISP for your protection. ISPs often don't give you a fixed IP address so even if you get this working it might suddenly break one day if your public IP address changes so it would be worth checking this in advance and considering hosting online if you haven't already.
If you want to test if WordPress is the cause of the problem simply point apache at a different folder containing a basic index.html with some plain text in it, does that work? or same result?
If you want to test that port 81 is open use nmap to hit your IP (from a computer that is external to your network) nmap ip-address-here
I'm presuming you know this but I'm going to say it anyway, make sure your domain is pointed to your external IP not your internal IP (i.e. the IP that you get if you google "what's my IP", so nothing starting 192.168.0.X)
Basically narrow down the problem and check that it's actually a WordPress configuration issue because otherwise it could be any number of things. If it's not a WordPress issue you'll probably have better luck posting on another part of StackExchange like Server Fault
But in principle no you're not missing anything, point domain to your IP, allow exceptions in any firewalls and setup port forwarding, tell apache what port to listen on, tell WordPress what domain/port it's on.


text:
Q: Git merge library from another project We counter following problem we tried to solve for many hours
Let's have 2 projects in git... they are different repositories.
One is library and second is some new project that will use mentioned library.
Library project contains:

*

*directory /lib

*directory /plugins

New project contains:

*

*directory /www

*directory /lib

*directory /plugins

*directory /assets

*etc... whatever

What we want to achieve is "merge" library into our New project
We tried using submodules, subtrees but what it creates inside our new project is new git folder without merge...
Thank you

A: Since both your library project and new project have the folders lib and plugin, so you can pull changes from library project to new project. Then the files in lib folder and plugins folder of library project will add to lib folder and plugins folder of new project separately.
Steps as below:
# In new project repo
git remote add lib <URL for library project git repo> -f
git pull lib master --allow-unrelated-histories

Note: If there has conflicts when you pull changes from library project, you can modify and save the conflict files, and then use git add . and git commit.

A: *

*it's unclear whether or not the two libraries are in the same git repository or not?

*can you share how is the repository structured ? where do each of these libs is held ?

*is it a different location or is it simply importing this lib from a different branch.

*if it's a different branch you simply git cherry-pick the commit which added the lib.

*if it's a different location - use git-mv
anyway, it's one or the other or a combination of the two.

gl.


text:
Q: I'm trying to use jQuery to see if a div contains some text, and then add a class to that div if it does I think I'm on the right track. So what is going on here is i'm checking to see if the li has text that says "Private" if it does then it adds a class .private to the li element, but for some reason it not working i think it has something to do with the if statement.
Any help would be great. ;)
Bascily code is

private

blah blah blah

Jquery Code
$( "li" ).each(function() {

  if ($( this ).text("private");) {
     $( this ).addClass(".private");
  }

});

A: Try this:
if ($( this ).text() === "private")
You also had an extra semi colon in the if statement which would cause problems.
Note that I used 3 equal signs. Change to two if you don't want to use type/case matching.
Also you don't need the period when adding a class. Just use this:
$( this ).addClass("private");

A: $( this ).addClass(".private");

Should be
$( this ).addClass("private");

You do not need the . if you are already using the addClass() function.
Also, your if statement should be:
if ($( this ).text() === "private")

Your if statement $( this ).text("private"); would normally change the text of the selector so it is not a condition.
Change to this:
$("li").each(function () {
    if ($( this ).text() === "private") {
        $(this).addClass("private");
    }
});

JSFiddle Demo


text:
Q: Configuring solarized colorscheme in gnome terminal, tmux and vim I'm struggling to make the Solarized colorscheme correctly working on an Ubuntu 13.10 machine inside Vim inside tmux inside the gnome-terminal.
I've started configuring gnome-terminal using the script on this repository and it displays the colors correctly. The same goes if I run Vim (with the official Solarized colorscheme) inside the terminal, without tmux.
Then I tried to configure tmux using this. It happens that when I run Vim the syntax highlight for php or javascript code is wrong or, at least, different from the one I see running Vim without tmux. I've tried also running tmux as tmux -2. The colors are different, but still the syntax highlight is not correct.

A: These days GNOME Terminal comes with Solarized colours built in. To use it, you need to change two settings in the profile that you're using. The obvious one is the text and background colour. You also need to set the palette to Solarized, though. You can find this setting below the one for the text and background colour. At this point, setting t_Co or g:solarized_termcolors in Vim shouldn't be necessary.
The palette is the part that I missed at first, which caused me to puzzle why the text in Vim and other applications was bright blue.

A: I tested it out and got it working in the following way:

*

*Install gnome solarized colorscheme. You can get it from https://github.com/aruhier/gnome-terminal-colors-solarized.

*Install solarized colorscheme for vim. You can get it from https://github.com/altercation/vim-colors-solarized. In .vimrc you should add following settings:
set t_Co=256
set background=dark
colorscheme solarized

*Set correct TERM variable by adding following line to your .bashrc/.zshrc
export TERM=screen-256color-bce

*Run gnome-terminal, tmux, vim and profit.