text:
Q: "Cannot find symbol" error with JDBC program When I compile my project file, the result is Cannot Find Symbol, I need help and this is my Java source code.
package com.uts.program;
import java.sql.*;
public class App
{
public static void main( String[] args )
{
    try
    {

      String myDriver = "org.gjt.mm.mysql.Driver";
      String myUrl = "jdbc:mysql://localhost:3360/universitas";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "");

      String query = "SELECT * FROM mahasiswa";

      Statement st = conn.createStatement();

      ResultSet rs = st.executeQuery(query);

      while (rs.next())
      {
        int id = rs.getInt("nim");
        String nama = rs.getString("nama");
        String jurusan = rs.getString("jurusan");
        String alamat = rs.getString("alamat");

        System.out.format("%s, %s, %s, %s, %s, %s\n", id, nama, jurusan, alamat);
      }
      st.close();
    }
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
}
}

And this is the result when I compile from the terminal on Ubuntu :

This is my folder structure:


text:
Q: Problem with associtedtype when referring to a protocol metatype Here is my problem:
Let's say I have a protocol with associatedtype referring to its metatype:
protocol TestMeta {
    associatedtype T

    var x : T.Type { get }
    var y : T { get }
}

If I create a struct with a concrete type, no problem:
struct AMeta : TestMeta {
    var x : Int.Type
    var y : Int
}

But if the associatedtype refers to a protocol, I've got the "Type 'BMeta' does not conform to protocol 'TestMeta'" error:
protocol P { }

struct BMeta : TestMeta {
    var x : P.Type
    var y : P
}

(even if I add the typealias definition to help the inference engine)
Of couse, if I do not refer to the metatype, everything works with concrete types and protocols, even if I have other variables of the metatype not defined within the protocol:
protocol TestNoMeta {
    associatedtype T

    var z : T { get }
}

struct ANoMeta : TestNoMeta {
    var z : Int
    var t : Int.Type
}

struct BNoMeta : TestNoMeta {
    var z : P
    var t : P.Type
}

So if anyone can explain what I do wrong? And how can I achieve my goal? Thanks in advance.
EDIT: But as @New Dev pointed out, I did not explain what I was looking for. I want to be able to do something like this:
struct S : P { }

let b = BMeta(x: S.self, y: S())

Knowing that's still compiling with the NoMeta protocol:
let bb = BNoMeta(z: S(), t: S.Type)

EDIT 2: In the end I wish to do something like this:
protocol P {
    init()
}

extension TestMeta {
    func build() -> P {
        return x.init()
    }
}

struct BMeta : TestMeta {
    var x : P.Type
    var y : P
}

struct S : P { }

let b = BMeta(x: S.self, y: S())
let c = b.build()

EDIT 3: Ok, ok, here is my real use case, I thought it was better simplifying things, but it seems not...
protocol Initializable {
    init()
}

protocol OptionListFactory {
    associatedtype Option : Initializable
    static var availableOptions: [Option.Type] { get }
}

extension OptionListFactory {
    static func build(code: Int) -> Option? {
        if code >= 0 && code < availableOptions.count {
            return availableOptions[code].init()
        }
        else {
            return nil
        }
    }
}

protocol Contract : Initializable {
    ...
}

struct Contract01 : Contract { ... }
struct Contract02 : Contract { ... }
...
struct Contract40 : Contract { ... }

struct ContractFactory : OptionListFactory {
    static let availableOptions: [Contract.Type] = [
        Contract01.self,
        Contract02.self,
        ...
        Contract40.self,
    ]
}

protocol Element : Initializable {
    ...
}

struct Element01 : Element { ... }
struct Element02 : Element { ... }
    ...
struct Element20 : Element { ... }

struct ElementFactory : OptionListFactory {
    static let availableOptions: [Element.Type] = [
        Element01.self,
        Element02.self,
        ...
        Element20.self,
    ]
}

Hope you'll understand better my aim...

A: This is the standard "protocols do not conform to protocols" question. Contract is a protocol that requires conforming types to also conform to Initializable. It is not itself Initializable. In fact, this is a canonical example of why protocols can't conform to themselves in the most general case. If it did, I could write Contract.init() and get back a...what? There's no way to allocate memory for "an abstract Contract."
Since Contract does not conform to Initializable, it can't be Option directly. Swift today also lacks any mechanism to talk about protocol inheritance. You cannot say that Option must be a protocol that requires Initializable. It's just beyond the Swift type system.
That said, this is a pretty inflexible approach. It requires that every type accept a trivial init, which is very limiting to what kinds of types can conform. There are much better ways IMO to implement this kind of factory.
Get rid of Initializable, get rid of the static requirement (you'll see why later), and replace the type with a builder function.
protocol OptionListFactory {
    associatedtype Option
    var availableOptions: [() -> Option] { get }
}

That causes the extension to be tweaked this way:
extension OptionListFactory {
    // Remove `static`
    func build(code: Int) -> Option? {
        if code >= 0 && code < availableOptions.count {
            return availableOptions[code]()  // Call the builder function
        }
        else {
            return nil
        }
    }
}

And a simple factory:
protocol Contract {}

struct Contract01 : Contract {}
struct Contract02 : Contract {}

struct ContractFactory : OptionListFactory {
    let availableOptions: [() -> Contract] = [
        Contract01.init,   // init rather than self
        Contract02.init,
    ]
}

But what if you have some type you want to vend that needs some extra information to construct? Doing it this way makes that straightforward.
// Elements need a name
protocol Element {
    var name: String { get }
}

struct Element01 : Element { let name: String }
struct Element02 : Element { let name: String }
struct Element20 : Element { let name: String }

struct ElementFactory : OptionListFactory {
    let availableOptions: [() -> Element]

    // And now we can assign that name
    init(prefix: String) {
        availableOptions = [
            { Element01(name: prefix + "01") },
            { Element02(name: prefix + "02") },
            { Element20(name: prefix + "20") },
        ]
    }
}

let ef = ElementFactory(prefix: "local")
let e20 = ef.build(code: 2)
// e20?.name == "local20"

By making the factories instances rather than using static, they are much more flexible and can be configured. And by using functions, you can compose in ways you may not have considered. For example, you could add a debug print statement every time an option is created:
struct DebugFactory<Base: OptionListFactory>: OptionListFactory {
    let availableOptions: [() -> Base.Option]

    init(base: Base) {
        availableOptions = base.availableOptions.map { f in
            return {
                print("Creating object")
                return f()
            }
        }
    }
}

// Works exactly the same as `ef`, just prints.
let debugFactory = DebugFactory(base: ef)
debugFactory.build(code: 2)

redpajama_set_name: RedPajamaStackExchange


text:
Q: calculation of money account in a bank in recursive public static double capitalAfterYearsRecursive(double K0, int n, double i,double R) {
    double K1;
    if(n < 0)
    {
        return K0;
    }
    else
    return capitalAfterYearsRecursive(K0, n-1 ,i ,R)*(i+1);
}

So guys i need your help, it doesnt show up the correct balance :/
 K0 start capital
 n runtime (years)
 i interest rate
 R yearly rate

A: I believe that your initial problem is that base condition.  You run the recursion back to year -1, rather than year 0.  How about
if (n <= 0)

...
Try your code with a time period of 0: your result should be the original principal.

A: public static double capitalAfterYearsRecursive(double K0, int n, double i,double R) {

    //double K1;
    if(n <= 0)
    {
        return K0;
    }
    else
    return capitalAfterYearsRecursive(K0, n-1 ,i ,R)*(i+1)+R;
}

Ok, the problem was, i had to add the +R


text:
Q: What would be the 1990s equivalent of Wizard's currency to then-U.K. currency? For instance, how many US dollars or Pounds Sterling would one Galleon be worth?
Considering they are actual gold they should be fairly expensive, but is there some standardized exchange rate?

A: We know that there is an exchange rate; at the start of Chamber of Secrets, Hermione's parents are exchanging muggle money for wizarding money at Gringotts in Diagon Alley.

'But you're Muggles!' said Mr. Weasley delightedly. 'We must have a drink! What's that you've got there? Oh, you're changing Muggle money. Molly, look!' He pointed excitedly at the ten-pound notes in Mr. Granger's hand.

Harry Potter and the Chamber of Secrets
JK Rowling has said that the exchange rate at the time was around £5 to the Galleon.

Rebecca Boswell - What is the approximate value of a galleon?
  JK Rowling - About five pounds, though the exchange rate varies!

Comic Relief live chat transcript, March 2001. (http://www.accio-quote.org/articles/2001/0301-comicrelief-staff.htm)
Now, gold bullion prices in March 2001 were around £5.84 to the gram (https://www.bullionbypost.co.uk/gold-price/30-year-gold-price-history-pound-gram) - that means if a Galleon is solid gold, it should weigh less than a gram and be less than a twentieth of a cubic centimetre in size to remain consistent. Presumably they are instead some kind of gold coloured alloy, or Mr and Mrs Granger could easily become the richest dentists in Britain!


text:
Q: SQL Server - Replace money numbers with text I need to replace a money number with text. For example if it were 66.35 it would be displayed as 66 dollars and 35 cents.
This is what I got to display but I don't know how to replace the decimal with the word dollars.
SELECT Freight, CAST(Freight AS varchar) + ' cents' AS Expr1
FROM dbo.Orders

http://i.imgur.com/8Oe9omn.png

A: You can separate the parts before and after decimal, cast each as varchar and then add in the text, like so:
SELECT Freight,
cast(cast(floor(Freight) as decimal(2,0)) as varchar) + ' dollars and ' + cast(cast(100*(Freight - floor(Freight)) as decimal (2,0))as varchar) + ' cents'
FROM dbo.Orders


text:
Q: "Function" Is Not Defined Im trying to make a slider that changes images every 5 secondes. But in console it says
"changemementImages is not defined at new slider"

//change images every 5 sec
this.temps = setInterval(changemementImages, 5000);

this.image5Sec = changemementImages =()=>{
    if(this.i >= 2){
        this.i-=3;
        document.getElementById("images").src = this.slide[this.i];
    }
    else if (this.i = 0){
        document.getElementById("images").src = this.slide[++this.i];
    }

}

A: Arrow functions need to be initialized before using them unlike declared functions.
https://developer.mozilla.org/en-US/docs/Glossary/Hoisting
Try to initialize changemementImages before setInterval.
const changemementImages =()=>{
   if(this.i >= 2){
       this.i-=3;
       document.getElementById("images").src = this.slide[this.i];
   }
   else if (this.i = 0){
       document.getElementById("images").src = this.slide[++this.i];
   }

}

this.temps = setInterval(changemementImages, 5000);

this.image5Sec = changemementImages;


text:
Q: Quaternion product I am trying to figure out how to multiply 2 quaternions together. I learned back in school that you use the FOIL method when multiplying 2 binomials together, however when it comes to Quaternions, The FOIL distributive method does not apply:
Qa = [Sa,A]
Qb = [Sb,B]
QaQb = [Sa,A][Sb,B] =
(Sa + Xai + Yaj + ZaK)(Sb + Xbi+ Ybj + Zbk) =
(SaSb - XaXb - YaYb -ZaZb)+
(SaXb + SbXa + YaZb -YbZa)i+
(SaYb + SbYa + ZaXb - ZbXa)j+
(SaZb + SbZa + XaYb - XbYa)k
Is there a standard way of multiplying 2 Quaternions together similar to the FOIL method used for multiplying 2 binomials?

A: Not everything is a binomial. Do you know how to multiply $(a+b+c)(x+y)$ for example? It's still just an application of the distributive property, it's just that FOIL is an acronym invented so students could memorize what the terms would be at the end multiplying two binomials.
For instance, with $(a+b+c)(x+y)$ we would have
$$ \begin{array}{ll} (a+b+c)(x+y) & =a(x+y)+b(x+y)+c(x+y) \\
 & = ax+ay+bx+by+cx+xy. \end{array} $$
When there are $4\times 4=16$ terms to multiply out, it becomes cumbersome to keep everything on one line, so if you want you can make a $4\times 4$ array to keep track of it all:
$$ \begin{array}{|c|c|c|c|c|} \hline & a_2 & b_2\mathbf{i} & c_2\mathbf{j} & d_2\mathbf{k} \\ \hline a_1 \\ \hline b_1\mathbf{i} \\ \hline c_1\mathbf{j} \\ \hline d_1\mathbf{k} \\ \hline  \end{array} $$
In each entry, compute $uv$ where $u$ is the term at the left of the row and $v$ is the term at the top of the column. When done filling in the table, add up all of its entries (not including the  terms labelling the rows and columns) to get $(a_1+b_1\mathbf{i}+c_1\mathbf{j}+d_1\mathbf{k})(a_2+b_2\mathbf{i}+c_2\mathbf{j}+d_2\mathbf{k})$.
Another way is to write quaternions in the form $r+\mathbf{u}$, where $r$ is a scalar and $\mathbf{u}$ is a vector; in this case you can multiply two quaternions as if it were a product of binomials, then use the rule $\mathbf{u}\mathbf{v}=-\mathbf{u}\cdot\mathbf{v}+\mathbf{u}\times\mathbf{v}$ (where $\mathbf{u},\mathbf{v}$ are vectors, i.e. pure imaginary quaternions, $\mathbf{u}\cdot\mathbf{v}$ denotes the dot product and $\times$ denotes the cross product) and combine like terms to simplify.

A: Where does the FOIL method come from?  It's from the distributive law, which says that $$x(y+z) = xy+xz.$$
Here the right term $(y+z)$ is a sum and we've distributed the left term $x$ over the right term.   If the left term is a sum, we can do it in the other direction:
$$(y+z)x = yx+zx.$$
How do we get from this to FOIL? When we multiply two binomials, both sides are sums and we can distribute in both directions. The first step is to distribute the left term over the right term as before:
$$(a+b)(c+d) = (a+b)c + (a+b)d$$
Where we took $x = (a+b)$ and $y = c$ and $z=d$.
Then we distribute again, in the other direction, twice:
$$\color{darkred}{(a+b)c} + \color{darkblue}{(a+b)d} =
\color{darkred}{ac + bc} + \color{darkblue}{ad + bd}$$
At this point we might be able to  combine like terms, if there are any.  In this example, which is very general, there aren't any.  But if we had been multiplying $x+2$ and $x+3$ then $bc$ would be $2\cdot x$ and $ad$ would be $x\cdot3$ and we would have been  able to combine them to get $5x$.
Now let's move on to quaternions.  The idea is the same:
$$(a + bi + cj+ dk)(w+xi+yj+zk) $$
We distribute the left term over the right one:
$$(a + bi + cj+ dk)w \\
+ (a + bi + cj+ dk)xi \\
+ (a + bi + cj+ dk)yj \\
+(a + bi + cj+ dk)zk $$
Can you take it from there?

A: FOIL method is only a mnemonic for the distributive law, that can be useful for the product of two binomial expressions, but for the product of polynomial expressions  I don't know   a similar mnemonic and we simply use distributivity.
In the case of quaternions we have:
$$
(a_0+a_1 \mathbf i+ a_2 \mathbf j+a_3 \mathbf k) (b_0+b_1 \mathbf i+ b_2 \mathbf j+b_3 \mathbf k) =a_0(b_0+b_1 \mathbf i+ b_2 \mathbf j+b_3 \mathbf k)+a_1 \mathbf i (b_0+b_1 \mathbf i+ b_2 \mathbf j+b_3 \mathbf k)+a_2\mathbf j (b_0+b_1 \mathbf i+ b_2 \mathbf j+b_3 \mathbf k)+a_3\mathbf k (b_0+b_1 \mathbf i+ b_2 \mathbf j+b_3 \mathbf k)=
$$
and the distributive law  can be still applied but, since the product is  not commutative, it is also important to respect the order of the factors when we distribute the products over the sum.


text:
Q: How to make my shell implementation terminate Node.JS after two Ctrl+C signals? #include <stdio.h>
#include <sys/wait.h>

int main (int argc, char** args){
    char *buffer = (char*) malloc(2048);
    char *cmd = (char*) malloc(2048);
    pid_t pid;
    while(1) {
        printf("!! ");
        fgets(buffer, 1024, stdin);
        if( buffer[0] != '\n') {
            pid = fork();
            if( pid == 0){
                buffer[strlen(buffer)-1] = '\0';
                execvp(buffer, args);
                exit(1);
            }else if(pid > 0){
                waitpid(pid, 0, WUNTRACED);
            }
        }
    }
    return 0;
}

I know that above code is ugly but I would like to show simplified version of my original code so I made it simplified as it is possible but I show a problem as well.
Ok, so I am testing my shell:
1. I compiled.
2. I ran it and:
!! racket. It gives me:
!! racket
Welcome to Racket v6.2.
>

And it is ok. And, what is important, I am able to finish this process with Ctrl-C. When I put Ctrl-C:
!! racket
Welcome to Racket v6.2.
> ^C
user break
  context...:
   /usr/local/share/racket/collects/racket/private/misc.rkt:87:7
>
$ ( this dolar is from my bash)

So it also work as we are expecting. But the problem is with js. I mean
js = nodejs - Server-side JavaScript. Where is the problem? Let see:
   !! js
>

It look like OK. But, when I put: Ctrl-C:
!! js
>
(^C again to quit)
>

Ok, so I put again: Ctrl-C:
!! js
>
(^C again to quit)
>
>

and it doesn't finish a process. It sill works. And it is a problem. I don't understand this behaviour and I don't know how to repair it.
P.S In bash/zsh it works.


text:
Q: CAPSULE EXCEPTION while deployNodes task I am trying to deploy IRS demo application on windows server, I have installed java already:
C:\Users\Administrator>java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) Client VM (build 25.181-b13, mixed mode)

I am getting following exception for node:
CAPSULE EXCEPTION: Could not find Java installation for requested version [Min. Java version: 1.8.0 JavaVersion: null Min. update version: {1.8=171}] (JDK required: false). You can override the used Java version with the -Dcapsule.java.home flag. (for stack trace, run with -Dcapsule.log=verbose)

can you help with whats going wrong? In the same machine environment, I have previously developed and deployed many corDapps.

A: This was caused by forgetting to update the Windows environment variable after installing Java 1.8.181.
Forgetting to update the Windows environment variable has also been known to cause errors of the type:

CAPSULE EXCEPTION: Illegal char <"> at index 0: "C:\WINDOWS while
  processing system property java.library.path: C:\Program
  Files\Java\jdk1.8.0_191\bin;


text:
Q: Form submit event in a view I have a form inside a View. How and where can I handle the form submit event? Also where can I write the code for handling events on elements present in this form. I tried handling it at:
//Instantiating a view with a template name signup
var signup = Ember.View.create({
templateName: "signup",
name: 'Sign Up',
click: function()
{
alert('click triggered from signup template');
},
submit: function()
{
alert('submit triggered');
},
signup: function()
{
alert('signup triggered');
}
});

When I click anywhere on the button, only click event is triggered. How do I get access to the submit event?

A: My answer includes, two solutions. The first being a method using views correctly. The second solution uses an Ember Component, which I think is closer to what you were looking to do.

Ember View Method:
I have created a working demo here, for you to look at.
The are a few things you need to do:
Your template code:
You need to be careful that you create clean and valid code. You have not closed the class name on your
 tag nor have you included the closing
 tag. This is the cleaned up template:
<form class="form-horizontal" {{action "signup" on="submit"}}>

                First Name
                {{input value=firstName class="controls" type="text"}}

                Last Name
                {{input value=lastName class="controls" type="text"}}

        <button class="btn btn-primary" type="submit">Register</button>

</form>

Using your view:
You cannot add actions to a view like that. Actions of the view must be handled either on the Route or the Controller. See here for examples on how to use actions with a view.
Essentially, your action handler would be trying to pass the action to the controller, or route that was including your view. Notice in my demo, that the IndexRoute has the model, and the action to take, and that the index template referenced the view:
{{view App.SignUpForm}}

Ember Component Method:
If you want to keep the action inside your view, then you need to use a component. See this demo, for use as a component.
App.SignUpFormComponent = Ember.Component.extend({
  templateName: "signup",
  actions: {
    signup: function(){
      alert("SignUp Clicked");
    }
  }
});

It's usage is slightly different, but now the action is self contained, and does not need to be included in the Route or Controller which is perhaps more what you were looking for.
To use it you can do:
{{sign-up-form data=this}}

Your model data is now accessible in the component by doing data.firstName and data.lastName, so the template is slightly modified too. You can see this in the HTML section of the JSBin demo I included.
I hope this helps.


text:
Q: Is BehaviorSubject the same as shareReplay(1)? In these two examples, does subject$ behave in exactly the same way?
import { BehaviorSubject, Observable } from 'rxjs';

let source: Observable<number>;
let subject$: Observable<number>;

subject$ = new BehaviorSubject(0);

source.subscribe(x => {
  subject$.next(x);
});

import { Observable } from 'rxjs';
import { shareReplay, startWith } from 'rxjs/operators';

let source: Observable<number>;
let subject$: Observable<number>;

subject$ = source.pipe(
  startWith(0),
  shareReplay(1)
);

A: The basic difference is that the 0 value may be re-emitted to the upstream when all subscribers unsubscribe and similar subtleties when no subscribers are active.
e.g.:
import { BehaviorSubject, Subject } from 'rxjs';

const source = new Subject<number>();
const subject$ = new BehaviorSubject(0);
source.subscribe((x) => {
  subject$.next(x);
});

source.next(1);
source.next(2);

let subscription = subject$.subscribe(console.log);

source.next(3);
source.next(4);

subscription.unsubscribe();

source.next(5);
source.next(6);

subscription = subject$.subscribe(console.log);

source.next(7);
source.next(8);

// Prints: 2 3 4 6 7 8

import { Subject } from 'rxjs';
import { shareReplay, startWith } from 'rxjs/operators';

const source = new Subject<number>();
const subject$ = source.pipe(startWith(0), shareReplay(1));

source.next(1);
source.next(2);

let subscription = subject$.subscribe(console.log);

source.next(3);
source.next(4);

subscription.unsubscribe();

source.next(5);
source.next(6);

subscription = subject$.subscribe(console.log);

source.next(7);
source.next(8);

// Prints 0 3 4 6 7 8

A: They replay behavior is the same but number of emission replay can be configured with shareReplay but not with BehaviorSubject. The main difference is shareReplay is an operator which can be add into pipe and convert any source stream to replay value and it doesn't replay any value until first emission happen.
BehaviorSubject is a class which only replay one value and need to be instantiated with a default value and thus when subscribe it always return one cached value.


text:
Q: Why is Lord Alfred Tennyson often written as Alfred Lord Tennyson? Why is Lord Alfred Tennyson often written as Alfred Lord Tennyson? This occurs with and without a comma after Alfred: Alfred, Lord Tennyson and Alfred Lord Tennyson. Should Lord precede the entire name, and not just the last name?

A: The simple answer is...
Alfred Tennyson was created a hereditary baron, 1st Baron Tennyson. Barons are known by their title, Lord Tennyson, preceded if necessary by their Christian name.
The same applies to current Life Barons, who are not created with hereditary titles. Thus it's John, Lord Prescott of Kingston-upon-Hull.
Sons of hereditary peers are given a courtesy title. The sons of barons, that being the lowest order of the peerage, are simply known as The Honourable. Alfred's son was The Hon Hallam Tennyson until Alfred died, after which he became Hallam, 2nd Baron Tennyson, or simply Hallam, Lord Tennyson.
The eldest sons of higher ranks of the peerage generally get a courtesy title (the eldest son of a Duke will be granted the use of an Earl's title, and so on). Subsequent sons are known as Lord, using the family surname. The second son of one of the Dukes of Devonshire would be [for example] Lord James Cavendish. It's not correct to call that person "Lord Cavendish".
Thus it's possible to distinguish between Lord James Cavendish as coming from a higher rank of the peerage than Alfred Lord Tennyson.
For a more complicated answer with all the intricacies of the peerage, you will need to consult a reference like Debrett's.

A: Alfred Tennyson should be known as Lord Tennyson, or as the 1st Baron (or lord) Tennyson if one want to make sure that it is him.
If the present 6th (Baron) Lord Tennyson, also was named Alfred, that name would be of no help.
The title (in England the title baron is always substituted by lord) should be used. The use of forename and designation title and then surname is meant for a totally different use.
He is known by this erratic designation because he was a snob, he said no to a baronetcy, but accepted the barony.
Rather vainly he put a "humble" envelope on his lordship, and called himself Alfred, the Lord Tennyson.  A king-like designation, kind of like Alfred, the king of the Tennysons.
The newspapers and press accepted his own way to titulate himself, instead the correct Lord Tebnnuson, without the forename.
He liked to claim that he was humble, a rather ordinary claim by men that are not humble.


text:
Q: Git branches with completely different content Since Git has the ability to keep track (and keep it clean) of branches with completely different content from each other, in the same repository, some projects (like Git itself) have started to make use of it.
Git, for instance, uses one branch for the code itself, while keeping its documentation in a separate branch. Same repo, just different branches.
It might just be me, coming from a SVN background, but I find it confusing to have 'nothing in common' in those branches. Development/staging/production branches; those I understand. Branches for incomplete features; sure, I'm doing those too. Heck, have your documentation with one branch per language. But no files in common?
Is this just (perhaps an underused and/or undermarketed) feature in Git, that everyone should embrace and get used to, or a possibly dangerous misuse by someone being lazy of not differentiating two aspects of the same project enough?

A: The benefit to doing this, is that it's possible to pull only the docs branch if that's all you're interested in. Like jrockway said, you can do this using another repository and submoduling if necessary, but with this ability to create a 'naked' branch, you have the option not to.
Personally, I'm still on the fence about this. I understand why it could be beneficial, but I'm not wholly convinced it's the best way to go.

A: I think it depends on what your project is.
Git is obviously a community OSS project so having the docs in the (same) repository so everyone gets them makes sense (to me).
On the other hand I would not store the docs for my projects at work as I would rarley edit them except on 'let's update the docs' type of ticket.  At work I don't want my docs intermingled with my source, I just want the source (typical programmer view i know).
Others may want them all-together.  I think you just need to realize what it means (remember everyone has a full copy of the repository) and pick the best option for your project.

A: It's a little weird when you're used to the Subversion model of presenting the tree to users, but once you get used to the model it's a lot less confusing.
A git repository is just a tree of objects that explain how to transform a directory from one state to another.  Those objects have a parent.  Some objects have two (or more) parents; merges.  Some objects have no parent; the initial commit.
As I understand it, internally, Subversion's model is similar minus the concept of where merges came from.  Those are just new commits with a handy command (svn merge) for getting a patch of the differences between two other commits.
I actually use this feature rather often to manage config files that started from the same directory on separate hosts, like /etc/apache2.  It's like saying, "this is the alternate start of this stuff, but it's been abandoned".  It allows me to stash the state of some files before I overwrite them, but without having to worry about whether they merge right, or are even related to the master branch at all.
In Subversion I'd have to stow that backup in some un-related place (zip file somewhere) or in a subdirectory in the repository.  Plus, in subversion, if I delete any reference to those files in the current view of the tree it becomes very hard to find them again.

A: I personally would not store different content in different branches; in the case of docs and code, I would just make a myproject.git and a myproject-docs.git (and sub-module the docs into the code if it was necessary for the build process).
On the other hand, nothing bad will happen if you do this.  Git is not going to tell you what to do, so you are free to make your own decision on how you want to use it.  So to answer your question, it's neither a killer feature, nor something that will bowl you over if you are not careful.  It's just how someone choses to use it.

A: Git tracks coordinated changes in (text) files within a project, so it doesn't know or care whether branches are mergable or not. Having independent branches in a Git repo is similar to having independent projects in a Subversion repo, which is a common practice (because of svn's overhead).
Because Git's data structure is very different than SVN's, you can do different things with them.  In SVN a feature branch is somewhat unusual, and a feature branch which is not often merged to the trunk might be a "bad smell", a sign that the programmer has "gone dark" and is creating code that may never be able to be integrated into the project. In Git, a feature branch is a perfectly safe and sensible workflow.
So they can be used in different ways  because Git is not SVN even though both have repositories and branches and commits, and serve the same general function of source control.
As I got more experience of Git, what had been weird just became different. Then I got curious about what I could do with that different tool.

A: I'd say it's more like a lazy workaround for the fact that Git can't currently handle having multiple projects stored in the same repository. You can do it, but there's no way to pull down just the one you want.
I say "lazy", because it wouldn't have been too horribly tough to add the feature when the git developers themselves discovered a need for it (for storing docs). Since they used this weird branch hack, their incentive to fix the issue for everyone else has abated significanly.


text:
Q: Handling uuid pk column in yii I'm using UUID's as PK in my tables. They're stored in a BINARY(16) MySQL column. I find that they're being mapped to string type in YII. The CRUD code I generate breaks down though, because these binary column types are being HTML encoded in the views. Example:
<?php echo
        CHtml::link(CHtml::encode($data->usr_uuid), /* This is my binary uuid field */
        array('view', 'id'=>$data->usr_uuid)); ?>

To work around this problem, I overrode afterFind() and beforeSave() in my model where I convert the values to/from hex using bin2hex and hex2bin respectively. See this for more details.
This takes care of the view problems.
However, now the search on PK when accessing a url of the form:
http://myhost.com/mysite/user/ec12ef8ebf90460487abd77b3f534404
results in User::loadModel($id) being called which in turn calls:
User::model()->findByPk($id);

This doesn't work since the SQL is being generated (on account of it being mapped to php string type) is
select ... where usr_uuid='EC12EF8EBF90460487ABD77B3F534404'

What would have worked is if I could, for these uuid fields change the condition to:
select ... where usr_uuid=unhex('EC12EF8EBF90460487ABD77B3F534404')

I was wondering how I take care of this problem cleanly. I see one possiblity - extend CMysqlColumnSchema and override the necessary methods to special case and handle binary(16) columns as uuid type.
This doesn't seem neat as there's no support for uuid natively either in php (where it is treated as string) or in mysql (where I have it as binary(16) column).
Does anyone have any recommendation?

A: If you plan using it within your own code then I'd create my own base AR class:
class ActiveRecord extends CActiveRecord
{
  // ...
  public function findByUUID($uuid)
  {
    return $this->find('usr_uuid=unhex(:uuid)', array('uuid' => $uuid));
  }
}

If it's about using generated code etc. then customizing schema a bit may be a good idea.

A: I used the following method to make working with uuid (binary(16)) columns using Yii/MySQL possible and efficient. I mention efficient, because I could have just made the column a CHAR(32) or (36) with dashes, but that would really chuck efficient out of the window.
I extended CActiveRecord and added a virtual attribute uuid to it. Also overloaded two of the base class methods getPrimaryKey and setPrimaryKey. With these changes most of Yii is happy.
class UUIDActiveRecord extends CActiveRecord
{
    public function getUuid()
    {
        $pkColumn = $this->primaryKeyColumn;
        return UUIDUtils::bin2hex($this->$pkColumn);
    }

    public function setUuid($value)
    {
        $pkColumn = $this->primaryKeyColumn;
        $this->$pkColumn = UUIDUtils::hex2bin($value);
    }

    public function getPrimaryKey()
    {
            return $this->uuid;
    }

    public function setPrimaryKey($value)
    {
            $this->uuid = $value;
    }

    abstract public function getPrimaryKeyColumn();
}

Now I get/set UUID using this virtual attribute:
$model->uuid = generateUUID();  // return UUID as 32 char string without the dashes (-)

The last bit, is about how I search. That is accomplished using:
$criteria = new CDbCriteria();
$criteria->addCondition('bkt_user = unhex(:value)');
$criteria->params = array(':value'=>Yii::app()->user->getId()); //Yii::app()->user->getId() returns id as hex string
$buckets = Bucket::model()->findAll($criteria);

A final note though, parameter logging i.e. the following line in main.php:
'db'=>array(
    ...
    'enableParamLogging' => true,
    );

Still doesn't work, as once again, Yii will try to html encode binary data (not a good idea). I haven't found a workaround for it so I have disabled it in my config file.


text:
Q: Newly assigned Sequence is not working In PostgreSQL, I created a new table and assigned a new sequence to the id column. If I insert a record from the PostgreSQL console it works but when I try to import a record from from Rails, it raises an exception that it is unable to find the associated sequence.
Here is the table:
\d+ user_messages;
                                                  Table "public.user_messages"
   Column    |            Type             |                         Modifiers                          | Storage  | Description
-------------+-----------------------------+------------------------------------------------------------+----------+-------------
 id          | integer                     | not null default nextval('new_user_messages_id'::regclass) | plain    |

But when I try to get the sequence with the SQL query which Rails uses, it returns NULL:
select pg_catalog.pg_get_serial_sequence('user_messages', 'id');
 pg_get_serial_sequence
------------------------

(1 row)

The error being raised by Rails is:
UserMessage.import [UserMessage.new]
NoMethodError: undefined method `split' for nil:NilClass
    from /app/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.3/lib/active_record/connection_adapters/postgresql_adapter.rb:910:in `default_sequence_name'

This problem only occurs when I use the ActiveRecord extension for importing bulk records,  single records get saved through ActiveRecord.
How do I fix it?

A: I think your problem is that you set all this up by hand rather than by using a serial column. When you use a serial column, PostgreSQL will create the sequence, set up the appropriate default value, and ensure that the sequence is owned by the table and column in question. From the fine manual:

pg_get_serial_sequence(table_name, column_name)
  get name of the sequence that a serial or bigserial column uses

But you're not using serial or bigserial so pg_get_serial_sequence won't help.
You can remedy this by doing:
alter sequence new_user_messages_id owned by user_messages.id

I'm not sure if this is a complete solution and someone (hi Erwin) will probably fill in the missing bits.
You can save yourself some trouble here by using serial as the data type of your id column. That will create and hook up the sequence for you.
For example:
=> create sequence seq_test_id;
=> create table seq_test (id integer not null default nextval('seq_test_id'::regclass));
=> select pg_catalog.pg_get_serial_sequence('seq_test','id');
 pg_get_serial_sequence
------------------------

(1 row)
=> alter sequence seq_test_id owned by seq_test.id;
=> select pg_catalog.pg_get_serial_sequence('seq_test','id');
 pg_get_serial_sequence
------------------------
 public.seq_test_id
(1 row)


text:
Q: Use ID instead of IRI in show/edit-URL I'm using Symfony with API Platform on a server for my REST API.
The client uses React-admin with the Hydra data provider.
My problem is that the pages for viewing or editing resources have a very ugly URL, because it uses the IRI instead of just the ID.

Instead of tags/%2Fapi%2Ftags%2F8/show, the path should be tags/8/show.
How do I accomplish that?


text:
Q: Match e-mail addresses not contained in HTML tag I need to highlight an email addresses in text but not highlight them if contained in HTML tags, content, or attributes.
For example, the string example@example.com must be converted to example@example.com
But email addresses in the string example@example.com must not be processed.
I've tried something like this regexp:
(?<![":])[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}(?!")
but it doesn't work properly.

A: I'll guessing that your source text is an HTML file which is missing anchor tags for only some of the contained e-mail addresses. If this is true, then you will not be able to use a regexp to reliably match only untagged e-mail addresses. For example, given the input:
...

You'll find a lot more written by

SvartaIF@example.com
.

...

it becomes impossible to lexically associate the href with the address and also exclude an@sign.org. You need to use an HTML parser; BeautifulSoup is pretty popular.


text:
Q: Find the possible range of values of $g$ if the total distance traveled is more than 4H. For a ball falling from rest at height $H$, the coefficient of restitution $0< e<1$ of this surface wrt the ball is defined as the square root of the ratio of the height of one bounce to that of the previous bounce. Simply put, the ball will rebound to a height of $e^2H$.
If $e = 0.8$, and after 5 bounces, the ball is damaged and the coefficient of restitution is reduced to $g$. Find the possible range of values of $g$ if the total distance traveled is more than 4H.
I am quite confused as what the question mean by total distance travelled.
Nonetheless, here are the values I got for some key ideas.
We know that if the coefficient of restitution is $e$, then the distance travelled by the ball just before the $n$ th bounce is $$Sn = (\dfrac{1+e^2-2e^{2n}}{1-e^2})H$$
And i also calculated out if the we use $e$ as the coefficient of restituition, the sum to infinity distance will be $$S_{\infty} = \dfrac{1+e^2}{1-e^2}H$$
And I also know that the total distance travelled just before the 5th bounce to be $$3.95903H$$
However i tried a few ways to get the range and failed to do so, any suggestions

A: Before the 5th jump, ball is at the height $e^8 H$. With the new coefficient $g$, at infinity, the total distance traveled is $\frac{1+g^2}{1-g^2}e^8H$ and it is given that total distance is larger than $4H$. i.e.
\begin{equation}
\frac{1+g^2}{1-g^2}e^8H > (4-3.79126)H \implies 0.329862 < g < 1\quad (g \text{ positive})
\end{equation}
Since $g<e$,
\begin{equation}
0.329862 < g < 0.8
\end{equation}


text:
Q: Changing C source code in an R package I am pretty new to R.
If I want to change a C source code in an R package, do I need to uninstall and install the R package every time I change the C code? Thanks.

A: No, you do not need to explicitly uninstall a package. You can install only the C library (provided there are no changes in the R code), e.g., R CMD INSTALL --libs-only MyPkg or R CMD INSTALL --libs-only --no-test-load MyPkg. Likely you'll start a new R session, typically with some kind of test script R -f my_test.R. See R --help and R CMD INSTALL --help.


text:
Q: Apache is crashing when executing my PHP script I currently have around 34k pins/auths generated in my database, and when I run this it just says This webpage is not available and says that apache crashed. I'm not sure what's causing it to crash because it generated 34k so far without problems. If I could get pointers or anything on what's causing my script to crash that would be great. Thanks. Also I'm running this on a local wamp server. So it gave me an apache crash popup, but I can't seem to get it to show again.
EDIT Here's the crash pop up info:
C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_httpd.exe_7bb4b47e7db260ba266dfdf76b7ba24f8a5e099_cab_175bb644\WERB55A.tmp.appcompat.txt
      C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_httpd.exe_7bb4b47e7db260ba266dfdf76b7ba24f8a5e099_cab_175bb644\WERB56A.tmp.WERInternalMetadata.xml
      C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_httpd.exe_7bb4b47e7db260ba266dfdf76b7ba24f8a5e099_cab_175bb644\WERB5E9.tmp.mdmp
error log:
[Sat Apr 12 19:17:01.362346 2014] [core:notice] [pid 3124:tid 412] AH00094: Command line: 'c:\\wamp\\bin\\apache\\apache2.4.4\\bin\\httpd.exe -d C:/wamp/bin/apache/Apache2.4.4'
[Sat Apr 12 19:17:01.363346 2014] [mpm_winnt:notice] [pid 3124:tid 412] AH00418: Parent: Created child process 940
[Sat Apr 12 19:17:01.599360 2014] [mpm_winnt:notice] [pid 940:tid 308] AH00354: Child: Starting 150 worker threads.
[Sat Apr 12 19:17:04.302514 2014] [mpm_winnt:notice] [pid 3124:tid 412] AH00428: Parent: child process 940 exited with status 255 -- Restarting.
[Sat Apr 12 19:17:04.389519 2014] [mpm_winnt:notice] [pid 3124:tid 412] AH00455: Apache/2.4.4 (Win64) PHP/5.4.12 configured -- resuming normal operations
[Sat Apr 12 19:17:04.389519 2014] [mpm_winnt:notice] [pid 3124:tid 412] AH00456: Server built: Feb 22 2013 22:08:37
[Sat Apr 12 19:17:04.389519 2014] [core:notice] [pid 3124:tid 412] AH00094: Command line: 'c:\\wamp\\bin\\apache\\apache2.4.4\\bin\\httpd.exe -d C:/wamp/bin/apache/Apache2.4.4'
[Sat Apr 12 19:17:04.391519 2014] [mpm_winnt:notice] [pid 3124:tid 412] AH00418: Parent: Created child process 2996
[Sat Apr 12 19:17:04.647534 2014] [mpm_winnt:notice] [pid 2996:tid 308] AH00354: Child: Starting 150 worker threads.

code:
<?php
    ini_set('xdebug.max_nesting_level', 1000000); //this is to fix the recursion?
    ini_set('max_execution_time', 3000000); //300 seconds = 5 minutes
    ini_set('memory_limit', -1);
    ini_set('error_reporting', E_ALL);
    //Enter your database connection details here.
    $host = 'localhost';
    $db_name = 'pins';
    $db_username = 'root';
    $db_password = '';
    date_default_timezone_set('America/Los_Angeles');
    try
    {
        $pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
    }
    catch (PDOException $e)
    {
        exit('Error Connecting To DataBase');
    }
    $starttime = microtime(true);
    class lists
    {
        public $pdo;
        function __construct($pdo)
        {
            $this->pdo = $pdo;
        }
        function duplicateCode($code)
        {
            $query = $this->pdo->prepare("SELECT 1 FROM pins WHERE pins_pin = ?");
            $query->bindValue(1, $code);
            $query->execute();
            return $query->fetch();
        }
        function generateCode()
        {
            $code = "AA" . substr(str_shuffle('0123456789'), 0, 8);
            if($this->duplicateCode($code))
            {
                return $this->generateCode();
            }
            else
            {
                return $code;
            }
        }
        function generatePin($code)
        {
            $query = $this->pdo->prepare("INSERT INTO pins (pins_pin) VALUES (?)");
            $query->bindValue(1, $code);
            $query->execute();
            return;
        }
    }
    function post_to_url($url, $data) {
        $fields = '';
        foreach ($data as $key => $value) {
            $fields .= $key . '=' . $value . '&';
        }
        rtrim($fields, '&');

        $post = curl_init();

        curl_setopt($post, CURLOPT_URL, $url);
        curl_setopt($post, CURLOPT_POST, count($data));
        curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($post);

        curl_close($post);
        return $result;
    }
    $list = new lists($pdo);
    for($i = 0; $i < 100000; $i++)
    {
        $code = $list->generateCode();
        $pin = $list->generatePin($code);
    }
    $endtime = microtime(true);
    $duration = $endtime - $starttime; //calculates total time taken
    echo $duration;
?>

A: Chances are that you're exceeding an internal recursion limit by calling lists::generateCode() repeatedly.
An easy fix for this will be to eliminate the recursion:
function generateCode()
{
    do {
        $code = "AA" . substr(str_shuffle('0123456789'), 0, 8);
    } while ($this->duplicateCode($code));
    return $code;
}

However, there's a more fundamental issue at hand here. Your code is generating codes which begin with two As, then contain 6 digits, all of which must be different. There are only 10! ÷ (10 - 6)! = 151,200 possible codes which fit this pattern - once you have generated all of them, no more will be available, and even this corrected code will loop endlessly. (Additionally, if str_shuffle() does not visit all of the possible permutations — which is entirely possible — the set of possible outputs will be even smaller than this.)
Unless you have a hard requirement that all six digits be different, I would strongly recommend that you instead use any sequence of six digits, e.g.:
  $code = sprintf("AA%06d", rand(0, 999999));


text:
Q: Fastest way to compute k largest eigenvalues and corresponding eigenvectors with numpy I have a large NxN dense symmetric matrix and want the eigenvectors corresponding to the k largest eigenvalues.  What's the best way to find them (preferably using numpy but perhaps in general using blas/atlas/lapack if that's the only way to go)?  In general N is much much larger then k (say N > 5000, k < 10).
Numpy seems to only have functions for finding the k largest eigenvalues if my starting matrix is sparse.

A: Actually the sparse routines work for dense numpy arrays also, I think they use some
kind of Krylov subspace iteration, therefore they need to compute several matrix-vector
products, which means that if your k << N, the sparse routinescould be (marginally?)
faster.
Check out the docs
http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html
and the following code (go to take a good coffee with friends until it ends)
import numpy as np
from time import clock
from scipy.linalg import eigh as largest_eigh
from scipy.sparse.linalg.eigen.arpack import eigsh as largest_eigsh

np.set_printoptions(suppress=True)
np.random.seed(0)
N=5000
k=10
X = np.random.random((N,N)) - 0.5
X = np.dot(X, X.T) #create a symmetric matrix

# Benchmark the dense routine
start = clock()
evals_large, evecs_large = largest_eigh(X, eigvals=(N-k,N-1))
elapsed = (clock() - start)
print "eigh elapsed time: ", elapsed

# Benchmark the sparse routine
start = clock()
evals_large_sparse, evecs_large_sparse = largest_eigsh(X, k, which='LM')
elapsed = (clock() - start)
print "eigsh elapsed time: ", elapsed

A: In SciPy, you can use the linalg.eigh function, with the eigvals parameter.

eigvals : tuple (lo, hi) Indexes of the smallest and largest (in
  ascending order) eigenvalues and corresponding eigenvectors to be
  returned: 0 <= lo < hi <= M-1. If omitted, all eigenvalues and
  eigenvectors are returned.

Which in your case should be set to (N-k,N-1).


text:
Q: Input value is not clearing based on another input field I can achieve the "field2" read-only if the "field1" value is null.
But In another condition "field1" having value and I entered the "field2" value, afterward, I have removed the "field1" value in that scenario I need to empty my "field2".
How to make that one possible?
Field1: <input type="text " class="form-control" formControlName="degree" #degree/>

Field2: <input type="text " class="form-control" formControlName="subject" [readonly]="degree.value == ''" />


text:
Q: Number of units in the ring of matrices I want to know about the number of units in the ring of all matrices of order $n\times n$ over the field of order $p$,
where $p$ is a prime.
I read in one my book that the order of $\mathit{GL}(n,\mathbb Z_p)$ is $(p^n-1)(p^n-p)(p^n-p^2)\dots (p^n-p^{n-1})$.
I think this is the required number of units in the group $M_n(\mathbb Z_p)$.
But I can't deduce it.
Also I have a question what will be the result if p is not prime i.e composite.?
Hope to get help.
Thanks.
Edit: My question for prime modulus $p$ is already been discussed here.
So I would like to know about the case when the modulus is composite.

A: Invertibility of $n\times n$ matrices over $\mathbb{Z}/m\mathbb{Z}$ is equivalent to checking the determinant of the matrix is coprime to $m$.  Note that the determinant can be computed as if the entries are integers, and then reduced mod $m$, since the determinant is a polynomial in the matrix entries.
This leads to a fairly simple analysis via Chinese remainder theorem when $m$ is a product of distinct primes.  See for example the previous Question about counting where $m=26$.  As Jyrki Lahtonen outlines in the Comments on that Question, any pairing of invertible matrix $A$ mod $2$ and invertible matrix $B$ mod $13$ can be combined per CRT to give invertible matrix $C$ mod $26$.  Thus the count of invertible matrices mod $m=pq$ where $p,q$ are distinct primes is the product of the counts for invertible matrices mod $p$ and mod $q$.
Indeed this reduction works for any factorization of $m$ into factors that are coprime (not necessarily prime factors), provided we know how to count the invertible matrices mod those coprime factors separately.  Chinese remainder theorem again allows us to piece together invertible pairs of matrices in the coprime factor moduli.
So the hard part of the counting for general moduli concerns the case of repeated prime factors, i.e. for $m = p^k$.  A short classroom note (on Linear Ciphers) that gives upper and lower bounds on the count is K. Pommerening's The Number of Invertible Matrices over a Residue Class Ring.
Formulas for the exact count of invertible matrices (with composite moduli) are developed in On the Keyspace of the Hill Cipher by Overbey, Traves, and Wojdylo (2005).
By the observations above it suffices to give their formula (Thm. 2.2.2) for a prime power modulus, with minor changes in notation for consistency:
$$ \text{When } m=p^k,\;\; |\mathit{GL}(n,\mathbb{Z}/m\mathbb{Z})| = p^{(k-1)n^2} \prod_{i=0}^{n-1} (p^n - p^i) .$$
Here $\mathit{GL}(n,\mathbb{Z}/m\mathbb{Z})$ is the "general linear" group of $n\times n$ invertible matrices with entries in $\mathbb{Z}/m\mathbb{Z}$.  So the order of that (multiplicative) group of matrices is precisely the count of invertible matrices under discussion.
Note that when $k=1$ the above formula simplifies immediately to the case already established for a prime modulus $\mathbb{Z}/p\mathbb{Z}$.


text:
Q: why android:layout_above="@id/mh01" is wrong when i use RelativeLayout in my layout why
android:layout_above="@id/mh01" is wrong when i use RelativeLayout !

I don't know why this is wrong
Update :
I have deal with the problem that the description of title. but I meet a new problem
This XML code have something wrong:
   <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:id="@+id/relativeLayout1">
            <ImageView
                android:id="@+id/mh011"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:background="@drawable/mh01"
                android:layout_centerInParent="true"
                />
            <ImageView
                android:id="@+id/mh022"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:background="@drawable/mh02"
                android:layout_above="@+id/mh011"
                android:layout_centerHorizontal="true"
                />
            <ImageView
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:id="@+id/mh033"
                android:background="@drawable/mh_03"
                android:layout_toLeftOf="@+id/mh011"
                android:layout_centerVertical="true"
                />
            <ImageView
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:id="@+id/mh044"
                android:background="@drawable/mh04"
                android:layout_toRightOf="@+id/mh011"
                android:layout_centerVertical="true"
                />
            <ImageView
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:id="@+id/mh055"
                android:background="@drawable/mh05"
                android:layout_below="@+id/mh011"
                android:layout_centerHorizontal="true"/>

>
            </RelativeLayout>

A: Update
Try set:
android:contentDescription="@null"

in all imageView
your  code after edit :
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:id="@+id/relativeLayout1">
        <ImageView
            android:id="@+id/mh011"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:background="@drawable/mh01"
            android:layout_centerInParent="true"
            android:contentDescription="@null"
            />
        <ImageView
            android:id="@+id/mh022"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:background="@drawable/mh02"
            android:layout_above="@+id/mh011"
            android:layout_centerHorizontal="true"
            android:contentDescription="@null"
            />
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/mh033"
            android:background="@drawable/mh_03"
            android:layout_toLeftOf="@+id/mh011"
            android:layout_centerVertical="true"
             android:contentDescription="@null"
            />
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/mh044"
            android:background="@drawable/mh04"
            android:layout_toRightOf="@+id/mh011"
            android:layout_centerVertical="true"
            android:contentDescription="@null"
            />
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:id="@+id/mh055"
            android:background="@drawable/mh05"
            android:layout_below="@+id/mh011"
            android:layout_centerHorizontal="true"
             android:contentDescription="@null"
               />

          >
        </RelativeLayout>


text:
Q: Delphi SQL Date reading issue I am currently creating a Delphi Application with SQL connections integrated.
SQL stores its date values in the format YYYY-MM-DD, however, when I read these values within my Delphi application, they are read in the format MM-DD-YYYY.
I have currently written the code to read the values of the dates from my database, however I am having trouble processing values which do not have 2 month integers or 2 day integers. For example, the date 17th of February 2013 would be read as '2/17/2013'
My current code separates the date into day, month and year. It works well for full dates (MM/DD/YYYY) as it reads the corresponding values within the text using the 'Copy' command within Delphi. When it reads a date which is in the format M/D/YYYY it does not copy the correct values from the string.
Is there any way to edit the string before I run my separation code, so that it forces the string into the format of MM/DD/YYYY. My idea is to write code to check the format of the string and then add any zeros which are missing: i.e change 2/17/2013 into 02/17/2013
I know I'm probably doing something to make things harder for myself, but this is my code at this point in time, so any help to fix my problem by adding to my current code would be much appreciated.
Thanks, A.

A: As a general rule, don't treat TDateTime values as strings, but as dates and times.
Don't get the value of a Date/Time field with the AsString method, use the AsDateTime method and assign it to a TDateTime variable.
If you want to know the date parts, use the provided functions to do so. For example the ones available in the DateUtils unit. The SysUtils unit also contains some Date/Time related functions.
uses
  DateUtils, SysUtils;

var
  MyDate: TDateTime;
  MyDay, MyMonth, MyYear: Word;
begin
  MyDate := MyQuery.Fields[3].AsDateTime;  //not AsString
  MyDay := DayOf(MyDate);
  MyMonth := MonthOf(MyDate);
  MyYear := YearOf(MyDate);
  ShowMessage(Format('Day: %d, Month: %d, Year: %d', [MyDay, MyMonth, MyYear]);

  //or also
  MyDate := EndOfTheMonth(MyDate);
  DecodeDate(MyDate, MyYear, MyMonth, MyDay);
  ShowMessage(Format('Day: %d, Month: %d, Year: %d', [MyDay, MyMonth, MyYear]);

The same applies to storing values to the database, rather than use a fixed date format, use parameters, like this:
uses
  DateUtils, SysUtils;

var
  MyDate: TDateTime;
  MyDay, MyMonth, MyYear: Word;
begin
  MyDate := EncodeDate(2013, 2, 17);
  MyQuery.SQL.Text := 'insert into myTable (MyDate) values (:MyDate)';
  MyQuery.Params.ParamByName('MyDate').AsDateTime := MyDate;
  MyQuery.ExecSQL();

It works with all the database access layers available that I know of.

A: I'm not familiar with Delphi, but if it's anything like .net, ColdFusion, php, or any other application technology, the principles are the same.
First, since you have a datetime datatype in your db, the only time format matters is when you display it.  Dates are numbers, not strings.
Next, query parameters are your friend for a variety of reasons.  If you can create a datetime variable in Delphi, and send it to MySql as a parameter, life will be very good.


text:
Q: How can I select elements outside of my component? I have two LWCs that I have put in a community page. I wanted to select an element of the other LWC from the other LWC, which I currently do not know how.
So, basically, my question is that, is there a way we can select an element in LWC1 from LWC2?
In native JavaScript, I believe this is how it's done:
document.querySelector('.some-classname');

But I've tried it in LWC and it didn't work.

A: By design, see e.g. Shadow DOM, that is not possible.
Edit your question to say exactly what you are aiming to do here between the two LWCs as how best to do that can depend on that.
Typically for LWCs that are not directly related, and assuming you have control over both LWCs, use the Lightning Message Service when the LWCs are running in the normal Salesforce desktop.
For Communities (AKA Digital Experiences), in the past you had to use a separate pub/sub library for this (works fine, just extra code to add), but LMS was in beta for Communities in May 2021, so may be GA by now or GA soon.


text:
Q: How to determine which database table columns need to be updated from modified struct? The problem that I am facing is more of a code design rather than specifically go related. I am building a simple CRUD application and everything seems to go nice and easy except the updating part: I have a struct type as simple as:
type User struct {
   ID string
   Name string
   Password string
}

and an interface for data storage layer:
type Store interface {
    ...
    Update(user *User) error
    ...
}

The problem is that with most database drivers you can't just pass the whole struct instance and hope the their system knows which fields were modified, the whole document/row gets replaced. How should I track which fields were modified (so that I could update them in the storage layer accordingly)? Maybe pass all the fields I would like to modify to the Update function as a map of interface{}?

A: There are plenty of ways to achieve that. For example you can use setters to change the values.So you can keep track of updated fields.
like so :
type User struct {
   ID string
   Name string
   Password string
   updateFields map[string]bool
}

func (u *User) SetName(name string) {
   u.Name = name
   updateFields["name"] = true
}

You can use more automated way by reflection.


text:
Q: Error "Too many return arguments are specified. Specify only one." I get this error "Too many return arguments are specified. Specify only one."
I understand what it means, but it does not make any sense. Since I have already two output blocks and scope in my simulink file.

What could be the reason for this error?
This my "error" code:
[tout,yout]=sim("TP_sub.slx")

A: There is no problem with your simulink model, the problem is how you call the sim function. If you look at the docs, you see that sim only returns one output:
simOut = sim(modelname)

In earlier versions of Matlab, it was possible to add the state and output as additional output arguments, but currently you can only output a simOut object.
This simOut object will contain some information, but by default it will not contain the simulation time and model outputs.
You can obtain this data by adding additional arguments to the sim call (complete list here). For example, using the 'vdp' model,
mdl = 'vdp';
load_system(mdl);
simOut = sim(mdl,  'SaveOutput','on','OutputSaveName','yout', 'SaveTime', 'on')

you will obtain
simOut =
  Simulink.SimulationOutput:

                   tout: [64x1 double]
                   yout: [64x2 double]

     SimulationMetadata: [1x1 Simulink.SimulationMetadata]
           ErrorMessage: [0x0 char]

from which you can get the simulation time, output 1 and 2 by
t = simOut.tout;
y1 = simOut.yout(:,1);
y1 = simOut.yout(:,2);

Another option to get the data in your workspace is to add To Workspace blocks, like you are already doing.

A:
I understand what it means, but it does not make any sense.
What could be the reason for this error?

Obviously you are not aware that a and b in the following example may be something completely different:
[x,y] = myFunction(someValue)
a = [x,y]

b = myFunction(someValue)

At least if the function myFunction is a "mex function" (and most Simulink-related functions are!), the function myFunction can be defined in a way that totally different values are returned depending on the number of return values given:
[x,y]=myFunction(someValue) may return two 10x20 matrices and b=myFunction(someValue) may return a single number (1x1 matrix).
You cannot just use [x,y]=someFunction(someValue) to "split" a single value returned by the function someFunction into two parts!
The sim function returns one single value.

A: Thanks for your Comments . But actually it si possible to get multiple outputs from sim function . You just shoulld change" Model Confugiration Settings > Data Import/Export pane and UNCHECK Single simulation"


text:
Q: causal effect and relationship I understand, in a correlation, r just signifies the relationship between two variables, and we CANNOT deduce that there is a causal relationship in the case of a correlation.
By contrast, we use a linear Regression analysis to predict y from x, using the equation y= mx+c. Can we discuss that there is a causal effect in this case?

A:
By contrast, we use a linear Regression analysis to predict y from x, using the equation y= mx+c. Can we discuss that there is a causal effect as well?

No. Consider the univariate regression where your coefficient m is intimately related to the correlation coefficient r.
You can study causality using linear regression, but in and of itself it doesn't say anything about causality. You can run and use regression when there's no causal relationship.

A: You are correct by saying you cannot deduce causal relationships when there is a statistically significant test of r=0, r being the Pearson correlation coefficient.
Statistical testing of the least squares regression slope (what you call m) is equivalent to tests of Pearson correlation coefficient: if one is non-zero, the other is non-zero. Tests of these hypotheses are asymptotically equivalent.
A necessary but insufficient condition to infer causality: you must either 1) randomize a cohort of participants to receive an experimental treatment or 2) control for confounding in a pseudoexperimental design using a multivariate model (estimating partial correlation or adjusted regression coefficients).
Suggested reading: Causality by Pearl 2nd ed, Causal Inference by Hernan, Robbins, Causal Diagrams for Epidemiologic Research by Greenland, Robins, Pearl.

A: First of all, as Aksakal pointed out as well, regression coefficients and (partial) correlation coefficients are linked, with the latter basically being a normalized version of the former.
Having noted that, you reason (I think) that because we can use a regression to "predict" y from x, this implies a kind of causality flowing from x to y. The problem is that prediction says nothing about causality. For example, the height of the sun in the sky is causally related to how light it is outside. Clearly, the sun being higher in the sky causes more illumination, and not the other way around. Yet, we can use our observation of how light it is outside to predict the height of the sun in the sky. I guess this can seem a bit misleading since the word "prediction" has a connotation of one event (causally) preceding another, but in this context the term is used more broadly to mean something similar to "inference".

A: Say your x variable is the dollar value of goods imported from year 2007 - 2017, and your y variable is private health spending for a person in year 2007 - 2017 as well. You plot x, y, and see a clear increasing and linear trend between x and y, and you can definitely fit a regression model to get the m. But there is no causal relationship in this case, rather a lurking variable (the common year). The association between x and y are just due to the fact that both imports and health spending grew rapidly in those years.
Reference: Introduction to the practice of statistics, chapter 2.4.


text:
Q: Mongoose - Validate array of different subdocuments types I have a schema which has an array of different sub document types.
Below schema is just an example:
VehicleSchema:
let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "bike" },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  type        : { type: String, required: true, default: "truck" },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [BikeSchema, TruckSchema],
});

Below is the json that I need to validate:
vehicle = {
  "name": 'abc',
  "vehiclesSelected": [
    {"type": "truck", doors: 2},
    {"type": "bike", tyres: 3},
    {"type": "bike"}
  ]
}

Now I need to validate the "vehiclesSelected" array based on the 'type' passed in the JSON. Can someone tell me how can I validate an
array of subdocuments based on a particular field (in this case 'type')?
Any help would be much appreciated.

A: You can make use of Mongoose's discriminator() function.
In your case, what you can do is:

let BikeSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 2}
});

let TruckSchema = new Schema({
  title       : { type: String, required: [true, 'title is required'] },
  tyres       : { type: Number, required: true, min: 4},
  doors       : { type: Number, required: true}
});

let typeVehicleSchema = new Schema({},
discriminatorKey: 'type', _id: false})

let VehicleSchema = new Schema({
  name: {type:String, required: [true, 'name is required']},
  vehiclesSelected: [typeVehicleSChema],
});

VehicleSchema.path('vehiclesSelected').discriminator('truck', new Schema(TruckSchema))
VehicleSchema.path('vehiclesSelected').discriminator('bike', new Schema(BikeSchema))

That way, depending on vehicle type, your schema will validate with the appropriate subType, both inheriting the parent schema (in this case, the typeVehicleSchema), based on the 'type' passed in.


text:
Q: How can I tell if a given Linq-to-Sql object is attached to a datacontext? I use linq 2 sql for my ORM.
For performance reasons, I serialize some of them, and throw them into memcached.
When they're deserialized, they're of course not attached to a datacontext, which is 100% fine, as they're only used for reading from in those scenarios.
For sanity reasons however, I'd like to be able to tell whether a given object is attached to a datacontext (fetched from the db), or not (fetched from memcached).
Any ideas?
Thanks.

A: Use GetOriginalEntityState. Here's a test.

Customer cust = new Customer();
ctx.Customers.Attach(cust);

Customer orig = ctx.Customers.GetOriginalEntityState(cust);

//test if orig is null


text:
Q: How to figure out the intercept of a xgboost model with gblinear I used the xgboost library in R to build a model; gblinear was used as the booster.
The coefficient (weight) of each variable can be pulled using xgb.importance(); however, I could not find the intercept of the final linear equation. Could anyone tell me where it is, please?
Thank you.

A: As you mentioned, only if model uses gblinear:
Try this:
model.fit(X_train,y_train)

print(model.coef_)
print(model.intercept_)


text:
Q: I am trying to install eclipse in my windows system, I am unable to install due to an issue I am trying to install eclipse neon package in my windows system.
i have downloaded successfully, but, while i am trying to install it's showing a message.I am unable to install eclipse.
I am sharing error image:


text:
Q: Updating a caption of a text box when something is changed in the userform I have a userform that has a dropdown of choices and each choice has different information related to it. to make sure the user has selected the correct Item that they want I have created a sentence in the spreadsheet which updates with the relevant information. I would like this sentence to be displayed on the userform when anything is updated on the userform i.e. if a different item is selected from the dropdown, the caption of the textbox will also update.
is there a way of doing this? I am currently using the following but it seems to only update some of the time:
Private Sub Item_No_TB_Change()

        Confirm_Info_Update.Caption = ThisWorkbook.Sheets("Email").Range("B60").Value

End Sub


text:
Q: Copy sqlite table with mixed column order I am trying to copy all data from sqlite table to another one (reason being changing primary key and recommended way is to create new table, copy data, rename, etc).
Something along:
insert into new_table select * from old_table;
drop old_table;
alter table new_table rename to old_table;

Now problem is, that sometimes when I create new table, it's order of columns is not the same and data is completely messed up. Not sure why, probably cause some people have brand new table and some have old table which lived trough lot of upgrade scripts. Anyway my point is, I need to make sure every column is inserted into correct column. I can for sure just name all the columns manually, but I'd like this to work even if I add some columns in future and also for other tables. I can probably somehow query name of columns and then construct query in language that I am using above (kotlin), but I'd like to do this on db level if possible.
It's on android, but not very relevant to the question :)
Thanks!

A: Sadly I had add 1 extra query to get columns.
Other queries had all columns specifically mentioned instead of using star to ensure correct order. My kotlin way:
        fun columns(db: SQLiteDatabase, tableName: String): List<String> {
            val sql = "pragma table_info($tableName)"
            return db.rawQuery(sql, arrayOf()).use { cursor ->
                (1..cursor.count).map {
                    cursor.moveToNext()
                    cursor.getString(cursor.getColumnIndexOrThrow("name"))
                }
            }
        }

        fun copyFromTableToTable(db: SQLiteDatabase, originalTableName: String, backupTableName: String) {
            val columns = columns(db, backupTableName).joinToString(separator = ",")
            db.execSQL("""INSERT INTO $backupTableName
                ($columns)
                SELECT $columns FROM $originalTableName
                """.trimMargin())
            //db.execSQL("DROP TABLE $originalTableName;")
            //db.execSQL("ALTER TABLE $backupTableName RENAME TO $originalTableName;")
        }


text:
Q: Using Rules in Scrapy to crawl specific links I am using scrapy to scrape airline review data from tripadvisor. First I am extracting all id and corresponding airline name. I am using following code to crawl only the links containing 'Airline_Review'.
import scrapy
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.contrib.spiders import Rule
from scrapy.contrib.linkextractors import LinkExtractor

URL = 'http://www.tripadvisor.com'

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
               'https://www.tripadvisor.com/Airlines'
               ]

        rules = (
                Rule(
                    LinkExtractor(allow = '.*Airline_Review.*'),
                    callback = 'parse',
                    follow= True
                    )
                )
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        for url in hxs.select('//a/@href').extract():
            if not ( url.startswith('http://') or url.startswith('https://') ):
            url= URL + url

            url = url.strip()
            with open('op.txt', 'a') as f:
                f.write(url)
                f.write('\n')

            yield Request(url, callback=self.parse)

But still I am getting links in my op.txt file that does not contain 'Airline_Review'. What is incorrect in my code?


text: Q: camel showing negative in flight exchanges in hawtio I am using camel version 2.24.1. I am reading a CSV and sending those records to the HTTP endpoint with the jetty client. the problem is on hawtio when I look at how many exchanges are in flight, it always shows a negative number. Does anyone why this is happening


text:
Q: Splitting one csv file according to different headers I have a csv file with content in 3 different headers.
Ex:
Name,city,email----file 1-need to create separate csv file with content
aaa,ccc,eee@e
bbb,ddd,eee@e

-blank lines

Name,group,status----file 2-need to create separate csv file with content
aaa,xyz,active
aaa,abc,active
bbb,abc,active
ccc,xyz,active

Name,fullname,org----file 3-need to create separate csv file with content
aaa,aaaxc,ghj
xxx,fguh,dguyfgu

How I can split this csv into different 3 csv files with different headers by using PowerShell?
I tried by giving the row numbers to split but the content will be different in different files

A:   $content =   Get-Content "your File" -Raw
  $nl = [System.Environment]::NewLine
  $parts = $content -split ("$nl$nl")
  $parts | % -BEGIN { $i=0} -PROCESS { $_ |  out-file "file_$($i++)).csv" -Append}


text:
Q: Handling missing data in Sequence Analysis (TraMineR) within the observation window I´m using sequence analysis. I have a question about how to deal with missing data within the observation window. The starting point of the analysis is when respondents leave secondary school (t0). I want to examine respondents' life course over a time-span of 36 month after leaving school. The dataset contains longitudinal information of repondents toward their educational histories. I arranged the data in the 'states-sequence' (STS) format. So in each month the dataset provides information on respondents' status (for example "employed" or "training"). For 58 % of the sample the data provides information over the whole observation window. So for this group I can tell in every single month what they are doing. The sequences of the rest of the sample are shorter. Thus, the length of the sequences is not the same for all respondents. How do I handle sequences of respondents that end before month 36. What would be the way the missing values should be handled in TraMineR?

A: (Sorry, not enough reputation to add a comment.)
Are you sure sequence analysis in required for your sort of problem? I'd suggest using time series analysis for interval variables (in case you're monitoring characteristics that can be projected on a numeric scale). This will help you to deal with missingness in an 'interval' way and apply various sorts of imputation methods like those mentioned here: Imputation methods for time series data .
If you deal specifically with ordinal data (say, switching from state to state monitored periodically), the recommended way is to convert your data to patterns (sequences of states) and model transitions between patterns, with methods like Discrete Autoregressive mentioned here: Analysis of Ordinal Value Time Series .


text:
Q: verifying my understanding about pointers I just want to make sure if I understand the properties of pointers. So if I have something like this:
#include <iostream>
using namespace std;

class Person
{
public:
  Person(){myBook = new Book(4);}
  void printPerson()
  {
    int i =0;
    while(i<n)
    {
        cout<<myBook[i].n<<endl;
        i++;
    }
  }

private:
   Book *myBook;
   int n;
};

class Book
{
public:
  Book(int num)
  {
      int n =0;
  }
  int n;
  };

Since the instance of Person class is a pointer, when I try to make a copy constructor and assignment operator=, I have to allocate a new Book for the new Person object. am I right? thx

A: There is a bug here:
Person(){myBook = new Book(4);}

allocates one Book object with num=4, if you mean to allocate 4 Book elements, do:
Person(){myBook = new Book[4];}

Otherwise when you access myBook[i] in while loop is undefined behavior:
while(i<n)
{
   cout<<myBook[i].n<<endl;
               ^^^ ouch
   i++;
}

Since the instance of Person class is a pointer, when I try to make a copy constructor and assignment operator=, I have to allocate a new Book for the new Person object. am I right?

Yes, make sure you follow rule of three
Other suggestions are, use std::vector instead of dynamic array, use smart pointers instead of raw pointers if you could.

A: (under the assumption, you meant instance of book, not of person)
In order to make a deep copy of a person, you need to create a new book instance as well.
Using a deep copy allows you to destroy the original person and its book while preserving the copy and the copied book.
There some use cases, where you actually want both persons to point to the same book object.
In such cases you need to keep track how many pointers are pointing at the book using somthing like a shared pointer.
Edit to clear it up:
If you have more than one Person with the same Book, and you have a valid destructor on the person:
class Person {
public:
  ~Person() {
    delete m_pbook;
  }
protected:
  Book *m_pbook;
}

class Book {
  int foo;
}

Person a = new Person();  // book pointer is something like 0x12345678
Person b = new Person(a); // book pointer is identical 0x12345678

// delete a yields
delete a; // memory in 0x12345678 is freed up
b->book;  // AccessViolation / Segmentation Fault, the memory in 0x12345678 does not belong to your program any more.


text:
Q: Telegram Bot - getChat - invite_link I have a very simple bot in python that runs this code:
def get_chat(chat_id=None):
    data = {
        'chat_id': str(chat_id)
    }
    resp = urllib2.urlopen(BASE_URL + 'getChat?'+urllib.urlencode(data)).read()
        return resp

My bot is an admin of the chat
It should receive the object chat as said here https://core.telegram.org/bots/api#getchat with the chat link inside of the object but the only thing i can receive is this:
{"ok":true,"result":{"id":#####,"title":"####","type":"supergroup"}}

why?

A: Try using exportChatInviteLink method. (documentation)
Also note that any previously generated link is revoked.

A: https://core.telegram.org/bots/api#chat
invite_link: String, Optional. Chat invite link, for groups, supergroups and channel chats. Each administrator in a chat generates their own invite links, so the bot must first generate the link using exportChatInviteLink. Returned only in getChat.


text:
Q: Matlab guide help, changing the string for a radiobutton from the workspace When using the guide function on MatLab, how do you change the string (name) of a radiobutton from the workspace, without requiring some sort of user input first?
For example,
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject    handle to radiobutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
handles = guidata(hObject);
buttonname = 'A'
set(handles.radiobutton1,'string', buttonname);
guidata(hObject,handles);

This changes the name of the radiobutton once it has been selected, but not before. How would I change the string from the start? Thanks in advance.

A: When working with GUIDE function called "Fun", there are three ways in order to change "initial" attributes of an object such as a radio button with the tag "radiobutton1".
The following functions run before it is displayed.

*

*Fun_OpeningFcn

*Fun_OutputFcn

*radiobutton1_CreateFcn
Therefore, you can simply add the new attributes in any part of the above functions. For example, by adding the following modifier to "Fun_OpeningFcn", the string value changes from the beginning:
set(handles.radiobutton1,'String','New_String')
On the other hand, if you want an attribute to get changed after a certain callback action, this modifier should be added to the related callback. When you add this part in the radio button callback function, it means, if the user selected this radio button the name of the radio button will be changed, Which is certainly not your purpose.


text:
Q: Dynamically Return Interface at Design-Time I'm attempting to write a fluent interface which is able to, at design time, detect the property type being passed as a Linq Expression and return an interface based on an evaluation of that type.
For example:
public class Searchable<Person>
{
    public Searchable()
    {
        CanSearch(x => x.Name)
            .Include(StringOperations.Contains);

        CanSearch(x => x.Age)
            .Exclude(NumericOperators.GreaterThan);
    }
}

Within the CanSearchMethod, I'd like to be able to do something like:
public IOperations CanSearch(Expression<Func<T, object>> expression)
{
    var type = (/* Code to pick apart expression */);

    if(type == typeof(int))
        return new ClassImplementingINumericOperations();
    if(type == typeof(string))
        return new ClassImplementingIStringOperations();
    if(type == typeof(IEnumerable))
        return new ClassImplementingIIEnumerableOperations();

    return null;
}

The Include and Exclude methods for the different interfaces differ only by an enum accepted as the argument:
public interface IOperations
{
}

public interface INumericOperations : IOperations
{
    INumericOperations Include(NumericOperationsEnum op);
    INumericOperations Exclude(NumericOperationsEnum op);
}

public interface IStringOperations : IOperations
{
    IStringOperations Include(StringOperationsEnum op);
    IStringOperations Exclude(StringOperationsEnum op);
}

public interface IIEnumerableOperations : IOperations
{
    IIEnumerableOperations Include(CollectionOperationsEnum op);
    IIEnumerableOperations Exclude(CollectionOperationsEnum op);
}

I suspect this is not possible but I can't it out completely since dynamics can do some funky magic.
I've looked at some other fluent interfaces but none seem to evaluate the expression in order to determine what types to return while designing.

A: You can do this with compile-time type-safety using overloads:
public IStringOperations CanSearch<T>(Expression<Func<T, string>> expression);
public IIEnumerableOperations<TItem> CanSearch<T, TItem>(Expression<Func<T, IEnumerable<TItem>> expression);

However, for numeric types, you'll either need a separate overload for each of the 7 numeric types, or a generic INumericOperations<TNumber> which will be annoyingly inflexible.

A: You can exploit overloading and type inference. Something like this:
IStringOperations CanSearch(
    Expression<Func<T, string>> expression)
{ /* ... */ }

INumericOperations CanSearch<TCompare>(
    Expression<Func<T, TCompare>> expression)
    where TCompare : IComparable<TCompare>
{ /* ... */ }

IIEnumerableOperations CanSearch<TSeq>(
    Expression<Func<T, IEnumerable<TSeq>>> expression)
{ /* ... */ }

Now, CanSearch(x => x.Name) will return a IStringOperations whereas CanSearch(x => x.Age) will return a INumericOperations object.


text:
Q: How do I set a background image from url in React (an outside url not a local file) I have the following code:
const UploadedImage = ({
    imageKey,
    url,
    clickHandler,
    deleteButtonHandler,
    isSelected}) => {
    return (
        <button
            className="placeholder-button rounded"
            type="button"
            style={{backgroundImage: url({url})}}
            onClick={() => clickHandler(imageKey, url)}
        >
            {isSelected && <div className="placeholder-overlay rounded" />}
            <UtilityButton
                className="delete-uploaded-image-utility-button"
                variant="delete"
                clickHandler={() => deleteButtonHandler(imageKey)}
            />
        </button>
    );
}

I am trying to set a background image in the button using a url from the web (not a local file). How do I do this? Current code doesn't work.

A: backgroundImage is expecting a string value which you currently aren't passing. You should change it to
style={{ backgroundImage: `url(${url})` }}


text:
Q: Manipulate a List in Python that Contains Other Lists I am trying to extract information from a list within a list within a list to end up with something like this from the information below:  ('h': '0.77584', 'l': '0.77292'), ('h': '0.77521', 'l': '0.77206')
print(dict)
[{'complete': True, 'volume': 2290, 'time': '2021-01-15',  'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}},  {'complete': True, 'volume': 2312, 'time': '2021-01-15',  'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]
Not sure how to go about it. I tried
something = list(list(dict.items())[0].items())[3][1]
print(something)
However, this returned {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}
How to get the requested data?

A: You can use the following list and dict comprehension
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15',  'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}},  {'complete': True, 'volume': 2312, 'time': '2021-01-15',  'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]

res = [{k:v for k, v in i['mid'].items() if k in 'hl'} for i in dict]

print(res)

Output
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]

A: First you can take the mid child from each parent dictionary in the list.
dict = [{'complete': True, 'volume': 2290, 'time': '2021-01-15',  'mid': {'o': '0.77540', 'h': '0.77584', 'l': '0.77292', 'c': '0.77440'}},  {'complete': True, 'volume': 2312, 'time': '2021-01-15',  'mid': {'o': '0.77436', 'h': '0.77521', 'l': '0.77206', 'c': '0.77206'}}]

old_dict = [dict[0]['mid'],dict[1]['mid']]

Then loop through those entries and filter based off the keys (i.e. remove o and c):
list_you_want = []

for i in [0,1]:
    list_you_want.append({ your_key: old_dict[i][your_key] for your_key in ['h','l'] })

Which gives you:
[{'h': '0.77584', 'l': '0.77292'}, {'h': '0.77521', 'l': '0.77206'}]


text:
Q: r - leaflet heatmap in rmarkdown Question
Can you plot a leaflet heatmap in an rmarkdown document?
Example working code
This code will generate a leaflet map with a heatmap when run directly from R
library(rCharts)

## data
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
              Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
              intensity = c(10,20,30,40,50,300))

## create JSON for heatmap
## - could also use jsonlite::toJSON
j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

## create leaflet map
leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## add heatmap plugin
leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

## heatmap layer
leaf_map$setTemplate(afterScript = sprintf("

    ", j
))

## output map
leaf_map

Output:

I have an example of this working in shiny too using tags$ and HTML().
rmarkdown chunk
Using Ramnath's example of embedding rCharts in R Markdown I can get close to creating this in a markdown document, but when this runs it displays the map, but not the heat.
```{r heatMapMarkdown, results='asis', comment=NA, cache=F}

## References
# - http://bl.ocks.org/ramnathv/raw/8084330/ - embedding rCharts in R Markdown

library(rCharts)

dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
              Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
              intensity = c(10,20,30,40,50,300))

## create JSON for heatmap
## - could also use jsonlite::toJSON
j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## Add circle:
# leaf_map$marker(c(47.5982623, -122.3415519))

leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

leaf_map$setTemplate(afterScript = sprintf("
    <script>
    var addressPoints = %s
    var heat = L.heatLayer(addressPoints).addTo(map)
    </script>
    ", j
))

## shows the map, but not the heat...
leaf_map$print('iframesrc', include_assets=TRUE, cdn=TRUE)

```

Is it possible to get the 'heat' to display on the map too?

A: I figured this out thanks to the answer to the question How to add an interactive visualisation to R Markdown
First, I create an html document for the  section to include a src to the heatmap plugin, and save it in the same directory as my .Rmd file with the name include_js_heatmap.html
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />

I can then include this in the header of the .Rmd, and write the html to generate the heatmap directly into the body of the document.
To make the heat interactive I can construct the JSON of heat points in a code chunk, then include it in the body of the document with the r ... notation
---
title: heatmapRMarkdown
output:
  html_document:
    self_contained: false
    keep_md: true
    includes:
      in_header: "include_js_heatmap.html"
---

```{r}
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
                  Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
                  intensity = c(100,20,30,400,50,3))

j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

```

Update
The
 method will create a directory alongside the .Rmd file with various .html, .js, .css files within it. Once this is created the standard rCharts code will work without the need for the
 html code any more:
## create leaflet map
leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## add heatmap plugin
leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

## heatmap layer
leaf_map$setTemplate(afterScript = sprintf("

    ", j
))

## output map
leaf_map

Update 2
A slight variation on this which avoids the include is to use the all the relevant html directly in the .Rmd document:
```{r baseMap, results='asis', echo=FALSE, comment=NA, cache=FALSE}
library(rCharts)
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
                  Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
                  intensity = c(100,20,30,400,50,3))

j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

```

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />


text:
Q: opengrok Index database(s) not found I'm using OpenGrok and get an issue when I try to search on a project.
I get the error "Index database(s) not found..."
It's a bit weird, because there are other projects on this instance and they work perfectly. It's only with the last project in my list that I have this problem...
Does anyone have any idea?

A: You will see this error, when there is a problem with indexing of given repository. opengrok creates a "dirty" file in such cases under index folder eg. /home/opengrok/data/index/
Please follow the below steps to solve such errors.

*

*Identify the repository on which this error is being appeared eg.
test

*Login to opengrok server

*cd /home/opengrok/data/index/
 eg. /home/opengrok/data/index/test

*Move the contents to a temp location
    eg. mkdir /tmp/test; mv /home/opengrok/data/index/test/*  /tmp/test

*Start indexing again.

A: Finally I found how to resolve it.
It was because the indexes where to big.
So I went in the OpenGrok directory and clear them.
Then I launched OpenGrok again and everything went fine.
Hope this can help someone else!