text:
Q: Scala "a" + _.toString not behaving like "a".+(_.toString) As far as I know, the infix operator usage in Scala should be equivalent to the invocation of a method. So:
scala> "a" + 3.toString
res0: java.lang.String = a3

Is the same as:
scala> "a".+(3.toString)
res1: java.lang.String = a3

I came across an occasion where this is not happening, when there is a placeholder. I was doing something more complex, but it can be distilled to:
scala> def x(f:(Int)=>String) = f(3)
x: (f: Int => String)String
scala> x("a" + _.toString)
res3: String = a3

So far so good. But...
scala> x("a".+(_.toString))
<console>:9: error: missing parameter type for expanded function ((x$1) => x$1.toString)
          x("a".+(_.toString))

What's the difference here? What am I missing?
Jordi

A: The _ placeholder can only appear at the topmost Expr in its function. That means
(_.toString)

is itself a function, and "a" + some function of unknown type doesn't make much sense to the compiler.

A: Your assessment of infix notation is correct, but your understanding of placeholder parameters is flawed.
When you use underscore as a placeholder parameter, you are creating a function. The question is what are the boundaries of that function: where does it start, where does it end? For example, consider this expression:
_ + _ + _

How should it be translated? Here are some alternatives:
(x, y, z) => { x + y + z }
(x, y) => { (z) => { x + y } + z }
(x) => { x + { (y, z) => y + z } }

Well, Scala rule is that the scope is the innermost parenthesis-delimited expression, or the whole expression otherwise. So, in practice, you wrote two different things:
x("a" + _.toString) // is the same thing as
x((y) => "a" + y.toString)

x("a".+(_.toString)) // is the same thing as
x("a".+((y) => y.toString))


text:
Q: Google Cloud Storage - Load Balancer - Host and path rules I have a website, with a Google Cloud Load Balancer, called santi.com
I have a Google Cloud Storage Bucket called santi-pictures
I have successfully setup a Host and path rule from this Load Balancer to this Bucket by entering this information in the Google Cloud Console.
+-----------+-------------+----------------+
| Hosts     | Paths       | Backends       |
+-----------+-------------+----------------+
| santi.com | /pictures/* | santi-pictures |
+-----------+-------------+----------------+

It works correctly when I access this url in the browser...
http://santi.com/pictures/me.jpg

... as long as there is a picture in this location in the bucket:
gs://santi-pictures/pictures/me.jpg

But how can I change my load balancer configuration so that I can instead get this following picture when I use the url mentioned above:
gs://santi-pictures/me.jpg

This is already a pictures bucket, so it doesn't make sense to me to have to put a folder called pictures in it.
Thanks for your help.

A: I tested with following host and path rules and verified with http://load-balancer-ip/file-name and was able to access the file present within the root of the bucket defined in backend configuration of the load balancer.
|        Hosts  |     Paths       | Backends    |
| WEB-SERVER-IP |  /*  | Backend-service-name |
Try copying the image within the root of the your bucket defined in backend configuration of Load balancer and add or change the "Host and path rules" to define path as "/*" (without quotes). You should be able to access the image using "gs://bucket-name/file-name" or "http://load-balancer-ip/file-name"
Hope it helps.

A: I was hoping to do the same thing as @santiago-arizti, but I don't believe it's possible as of writing this. According to the google docs:

The Cloud Storage object to serve is determined based on your URL map and the URL that you request. If the request path maps to a backend bucket in your URL map, the Cloud Storage object is determined by appending the full request path onto the Cloud Storage bucket that the URL map specifies.
For example, if you map /static/* to gs://[EXAMPLE_BUCKET], the request to https:///static/path/to/content.jpg will try to serve gs://[EXAMPLE_BUCKET]/static/path/to/content.jpg

A: Still, as of December 30th, 2019, this is not currently possible in Google Cloud CDN. It wasn't possible on AWS either, but with AWS' Lambda @ Edge offering from last year, you can rewrite URLs to your preference, as well as do any compute on the edge such as authentication or other custom workflows using Lambda functions. Even though the original poster was able to make it work without the URL rewrite, IMO it's a strong feature if you need compute at the CDN edge, actually. In fact it is one of Cloudflare CDN's big unique value proposition (called Cloudflare Workers). Google has been slow in making progress on their Cloud Function integrations with their other services, but I can imagine this integration existing on Google Cloud CDN in a couple years.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this post "locked" instead of removed? This (old) post about how to gain rep fast by essentially being anti-community seems like it should have been removed long ago. Why has it been allowed to stay around all these years? I'm assuming it's because the answers are legitimate, and seem to highlight ways of being a good member of this community, but if that's the case then shouldn't the question be edited heavily to remove the references to ridiculous practices which undermine Stack?
Is it just a big joke? If that's the case then it's not obvious enough to warrant not editing it.
For sure this gets found all the time and people think the community is encouraging them to answer questions fast, even at the expense of quality, and then downvote any other (better) answers just because it makes their answer look better.
Just wondering if some senior members of this community have some opinions here...

A: No, that question is not a joke. It was a valid question back when it was posted, and it's being kept because it has a useful answer that is still very legit and relevant these days.
Screenshot of the answer in case the question gets deleted at some point:

Some of those tips might not be great, but others are really good, and not trivial at all.
I do agree most comments and other answers are jokes, and won't be bothered if they're removed.

A: Well, in this specific situation - the locking reflects that the post has historic significance but no longer reflects how we do things. Being locked, its unlikely anyone's taken a good look at it lately, since it can't be bumped.
As such, no one's seen it since Jeff locked it in 2017, and while Jeff's had a great influence on the site in the early days (as the CEO for the first couple of years, and a pretty active user), he doesn't have a direct influence on site policy, and his views don't really reflect SE (the network) or SO policy these days.
If we do keep the post - it's an example of youthful silliness (and many,if not  all of us, have done silly things).
Stuff like that is tricky. We need to balance between having people find things that are relevant to the current norms and culture of the site, and the risk of erasing/losing our history, cause this was the sort of thing we did once.
The historical lock is a reasonable compromise that lets us keep our historical posts, while letting people know this isn't how we do things anymore. The latter is just as important. We might end up reviewing that (either us volunteer mods, or a passing community manager) and choosing to delete it, but at least for now, this kinda works for us.

A: I'm of the impression that the cynicism in the actual question itself is being drowned out by either angst or frustration in this present day and age.


text:
Q: Most efficient way to check if object is a String I get an object (msg.data) that is either a number or a string. If it is a string I don't want to use it, if it is a number I want to. I currently solved this problem with an ostringstream, though I think there are way better solutions:
void scan_cb(const sensor_msgs::LaserScan::ConstPtr& scan)
{
float dist = 0.0f;

std::ostringstream s;
s << scan->ranges[0]; // can be string (always "inf") or a float
if(s.str() != "inf"){
    dist += scan->ranges[0];
}
...

I care about efficiency, because this is part of a for loop running many times each second.
The basic structure is a ROS message, coming from a certain topic, and can have basically any data type.
In this case I use a LaserScan message, the documentation does not mention that range[x] can return "inf".

A: According to ROS documentation, scan->ranges is an array of float. That makes sense, because you add it to a float (dist) when the string representation of ranges[0] is not inf.
That means that (as MSalters guessed in its comment), you have a true float value, and you just want to make sure it is a real number and neither an infinite value nor a NaN (Not a Number) value.
So provided you include cmath (or math.h) you can use the C classifications macros to determine whether the number is finite (but subnormal values are allowed) or normal (even subnormal values are rejected):
void scan_cb(const sensor_msgs::LaserScan::ConstPtr& scan)
{
float dist = 0.0f;

if(isfinite(scan->ranges[0])){
    dist += scan->ranges[0];
}
...

(more references on IEEE-754 representation of floating point numbers on wikipedia)


text:
Q: How to concatenate a column after x rows? I have a table with columns
object varchar(255),
frequency tinyint(3) unsigned,

I want to concatenate the objects if the sum of frequencies reach a value. Currently I am doing this in PHP as
.. query loop {
$object .= $row['object'].",";
$frequency = $frequency+$row['frequency'];

if($frequency > 20) { // 20 is a given value
    $mysqli->query("INSERT INTO table2 (concatenated_column) VALUES ('$object')");
    $frequency=0;
    $object='';
    }
}

Is it possible to do this with a native query of mysql instead of bringing the data into PHP and returning back to mysql?
Since the process is simple, I think mysql has enough functions to do so, but I do not know how to do so.
In fact, I want to group concatenate the entire column and split it when sum of frequency reaches the given value (i.e. 20). This needs a loop of INSERTs in which the sum of frequency reset to 0 upon reaching 20.
UPDATE: The process with do as:
table1:
object    frequency
object1   7
object2   5
object3   6
object4   8
object5   2

table2:
concatenated_column
object1,object2,object3,object4
object5,....

A: Basically, you want to result the running total and group it
This requires iterative variable manipulation.
First, your sample data quadrupled:
mysql> drop database if exists all_db;
Query OK, 1 row affected (0.03 sec)

mysql> create database all_db;
Query OK, 1 row affected (0.00 sec)

mysql> use all_db
Database changed
mysql> create table table1
    -> (
    ->     object varchar(255),
    ->     frequency tinyint unsigned
    -> );
Query OK, 0 rows affected (0.06 sec)

mysql> insert into table1 values
    -> ('object1',7),('object2',5),('object3',6),('object4',8),('object5',2);
Query OK, 5 rows affected (0.05 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> insert into table1 select * from table1;
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> insert into table1 select * from table1;
Query OK, 10 rows affected (0.06 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> select * from table1;
+---------+-----------+
| object  | frequency |
+---------+-----------+
| object1 |         7 |
| object2 |         5 |
| object3 |         6 |
| object4 |         8 |
| object5 |         2 |
| object1 |         7 |
| object2 |         5 |
| object3 |         6 |
| object4 |         8 |
| object5 |         2 |
| object1 |         7 |
| object2 |         5 |
| object3 |         6 |
| object4 |         8 |
| object5 |         2 |
| object1 |         7 |
| object2 |         5 |
| object3 |         6 |
| object4 |         8 |
| object5 |         2 |
+---------+-----------+
20 rows in set (0.00 sec)

mysql>

Let's make the query that generates group values:
set @freq_limit = 20;
set @freq_count = 0;
set @freq_group = 1;
set @freq_sum   = 0;
select cc,GROUP_CONCAT(object) objects from
(
select * from
(
    select *,
        @freq_groupinc := IF(@freq_count >= @freq_limit,1,0)           bb,
        @freq_count    := IF(@freq_count >= @freq_limit,0,@freq_count) aa,
        @freq_group    := @freq_group + @freq_groupinc                 cc,
        @freq_count    := @freq_count + frequency                      dd
    FROM table1
) AA) A GROUP BY cc;

Would you believe it works?
First I'll let you see the inner subquery's output
mysql> select * from
    -> (
    ->     select *,
    ->         @freq_groupinc := IF(@freq_count >= @freq_limit,1,0)           bb,
    ->         @freq_count    := IF(@freq_count >= @freq_limit,0,@freq_count) aa,
    ->         @freq_group    := @freq_group + @freq_groupinc                 cc,
    ->         @freq_count    := @freq_count + frequency                      dd
    ->     FROM table1
    -> ) AA;
+---------+-----------+----+------+------+------+
| object  | frequency | bb | aa   | cc   | dd   |
+---------+-----------+----+------+------+------+
| object1 |         7 |  0 |    0 |    1 |    7 |
| object2 |         5 |  0 |    7 |    1 |   12 |
| object3 |         6 |  0 |   12 |    1 |   18 |
| object4 |         8 |  0 |   18 |    1 |   26 |
| object5 |         2 |  1 |    0 |    2 |    2 |
| object1 |         7 |  0 |    2 |    2 |    9 |
| object2 |         5 |  0 |    9 |    2 |   14 |
| object3 |         6 |  0 |   14 |    2 |   20 |
| object4 |         8 |  1 |    0 |    3 |    8 |
| object5 |         2 |  0 |    8 |    3 |   10 |
| object1 |         7 |  0 |   10 |    3 |   17 |
| object2 |         5 |  0 |   17 |    3 |   22 |
| object3 |         6 |  1 |    0 |    4 |    6 |
| object4 |         8 |  0 |    6 |    4 |   14 |
| object5 |         2 |  0 |   14 |    4 |   16 |
| object1 |         7 |  0 |   16 |    4 |   23 |
| object2 |         5 |  1 |    0 |    5 |    5 |
| object3 |         6 |  0 |    5 |    5 |   11 |
| object4 |         8 |  0 |   11 |    5 |   19 |
| object5 |         2 |  0 |   19 |    5 |   21 |
+---------+-----------+----+------+------+------+
20 rows in set (0.00 sec)

mysql>

Look at the cc column. It increments every time the sum exceeds @freq_limit (20) and resets.
Now just run GROUP_CONCAT on object, grouping by cc
mysql> set @freq_limit = 20;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_count = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_group = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_sum   = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> select cc,GROUP_CONCAT(object) objects from
    -> (
    -> select * from
    -> (
    ->     select *,
    ->         @freq_groupinc := IF(@freq_count >= @freq_limit,1,0)           bb,
    ->         @freq_count    := IF(@freq_count >= @freq_limit,0,@freq_count) aa,
    ->         @freq_group    := @freq_group + @freq_groupinc                 cc,
    ->         @freq_count    := @freq_count + frequency                      dd
    ->     FROM table1
    -> ) AA) A GROUP BY cc;
+------+---------------------------------+
| cc   | objects                         |
+------+---------------------------------+
|    1 | object1,object2,object3,object4 |
|    2 | object2,object3,object5,object1 |
|    3 | object4,object5,object1,object2 |
|    4 | object5,object1,object3,object4 |
|    5 | object2,object3,object4,object5 |
+------+---------------------------------+
5 rows in set (0.00 sec)

mysql>

Just set @freq_limit to whatever value you need.
To show it works for just the 5 rows you supplied:
mysql> drop database if exists all_db;
Query OK, 1 row affected (0.04 sec)

mysql> create database all_db;
Query OK, 1 row affected (0.00 sec)

mysql> use all_db
Database changed
mysql> create table table1
    -> (
    ->     object varchar(255),
    ->     frequency tinyint unsigned
    -> );
Query OK, 0 rows affected (0.05 sec)

mysql> insert into table1 values
    -> ('object1',7),('object2',5),('object3',6),('object4',8),('object5',2);
Query OK, 5 rows affected (0.06 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> set @freq_limit = 20;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_count = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_group = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> set @freq_sum   = 0;
Query OK, 0 rows affected (0.00 sec)

mysql> select cc,GROUP_CONCAT(object) objects from
    -> (
    -> select * from
    -> (
    ->     select *,
    ->         @freq_groupinc := IF(@freq_count >= @freq_limit,1,0)           bb,
    ->         @freq_count    := IF(@freq_count >= @freq_limit,0,@freq_count) aa,
    ->         @freq_group    := @freq_group + @freq_groupinc                 cc,
    ->         @freq_count    := @freq_count + frequency                      dd
    ->     FROM table1
    -> ) AA) A GROUP BY cc;
+------+---------------------------------+
| cc   | objects                         |
+------+---------------------------------+
|    1 | object1,object2,object3,object4 |
|    2 | object5                         |
+------+---------------------------------+
2 rows in set (0.00 sec)

mysql>

Give it a Try !!!

A: Unless I misunderstood you, it should work :
INSERT INTO table2(concatenated_column)
SELECT GROUP_CONCAT(object) FROM table1
HAVING SUM(frequency)>20;


text:
Q: How do I find the initials of the name entered in this string? Say the user enters "joe smith". I can find the J but I'm not sure how to find the S seeing that the length of the string can vary.
name=input("What is your name")
initials=(name[0],#not sure)
initials=initials.upper()
print(initials)

I had a question like this similar on a quiz and apparently I'm supposed to use indexing. Is that possible?

A: Use:
name = input("What is your name: ")
initials = ' '.join(map(lambda i: i.title(), name.split()))
print (initials)

or step by step:
name = input("What is your name: ")
splited_initials = name.split()  # ["joe", "smith"]
titled_initials = [item.title() for item in splited_initials]  # ["Joe", "Smith"]
initials = ' '.join(titled_initials)  # "Joe Smith"
print (initials)

A: This worked for me. It will print each inital on a new line so you may want to add to an array or something before printing:
name = input("what is your name?")
names = name.split()
for name in names:
  if name != "":
    print name[0]

A: name=input("What is your name")
initials=name.split(" ")
for word in initials:
  if word != "":
   print(word[0].upper())


text:
Q: Standardising dataset attributes across projects Background:
I have multiple old projects that I need to standardise (PRJ01-PRJ10). Each is stored under its own libname and each has around 30 datasets (note: not all studies have the same 30 datasets).
The variable names have remained consistent across the projects. However, over the years, the labels and formats that have been assigned to these variable names have changed in places - for example as below:

Attribute inconsistencies BETWEEN studies:
data PRJ01.users(label='user identifiers') ;
  attrib USERID label='Username' format=$20. ;
run ;

data PRJ02.users(label='User Identifiers') ;
  attrib USERID label='Name of user' format=$15. ;
run;

Attribute inconsistencies WITHIN studies:
data PRJ02.users(label='User Identifiers') ;
  attrib USERID label='Name of user' format=$15. ;
run;

data PRJ02.orders(label='Orders') ;
  attrib USERID  label='Name of User' format=$15.)
         ORDERNO label='Order number' format=8. ;
run ;

I have written a program to report all inconsistencies. However, I need to generate 'tidy' copies of all projects giving them all a standardised structure. My current thinking is that I should create a dataset of standard variables as below that we can add and adjust until we have everything defined in there:
data standards ;
  attrib USERID  label='Username                                ' format=$20.
         ORDERNO label='Order Number                            ' format=8.
;run ;

Question:
From this standards dataset, what is the best way to apply the attributes to where ever these variables exist?
I will write the output datasets to new libnames eg: PRJ01.users --> PRJSTD01.users and put errors to the log if there are any variables that are changed where the variable length is getting truncated.

A: Create a dictionary table containing your standards:
name     label         format
USERID   Username      $20.
ORDERNO  Order Number  8.

Join to dictionary table containing column names in your library:
proc sql;
create table standards2 as
select
  d.memname,
  s.name,
  s.label,
  s.format
from
  sashelp.vcolumn d
  inner join standards s
  on d.name = s.name
where
  libname eq 'PRJ01'
order by
  d.memname,
  s.name
;
quit;

To get this:
memname    name     label         format
users      USERID   Username      $20.
orders     USERID   Username      $20.
orders     ORDERNO  Order Number  8.

Then read this data set using put statements to create a proc datasets that performs your modifications.
filename gencode temp;
data _null_;
  set standards2 end=eof;
  by memname;
  file gencode;
  if _n_ = 1 then put       "proc datasets lib=PRJ01 nolist;";
  if first.memname then put "  modify " memname ";";
  put                       "  label " name "='" label "';";
  put                       "  format " name format ";";
  if eof then put           "quit;";
run;
%include gencode / source2;
filename gencode clear;

(stolen from this paper)
You should be able to modify to match the rest of your requirements (copying to new libraries, iterating over projects).


text:
Q: What are appropriate ways to represent relationships between people in a database table? I've got a table of people - an ID primary key and a name.  In my application, people can have 0 or more real-world relationships with other people, so Jack might "work for" Jane and Tom might "replace" Tony and Bob might "be an employee of" Rob and Bob might also "be married to" Mary.
What's the best way to represent this in the database?  A many to many intersect table?  A series of self joins?  A relationship table with one row per relationship pair and type, where I insert records for the relationship in both directions?

A: Create a separate many-to-many table for each type of relationship.
If you try to represent multiple types of relationships in a single many-to-many table, that's a violation of Fourth Normal Form.

Re comments:
Actually the violation of 4NF would be something like this:
Person1 Person2 Is_Employer Is_Teacher Is_Father
Tom     John     No          No         Yes

If you have a three-column table that lists two people and a relationship type, it's better, but you still have a problem with reciprocal relationships.
Person1 Person2  Rel_type
John     Ann     married

Some people get confused about whether to store two rows, or else store the two people in some kind of consistent order (e.g. lower ID value first).  But then there are relationships that are directed, like "employer" where the order means something.  And there are relationships with multiple people, like "siblings."
So another way to organize these relationships would be to create a table listing groups, one group per row, and then another table listing people in that group.
Group Rel_type    Group Person
123   siblings    123   Bobby
                  123   Peter
                  123   Greg
                  123   Cindy
                  123   Jan
                  123   Marsha

This works best for relationships that have variable numbers of members, and are reciprocal relationships.  Members of a sports team is another example.  It's essentially a many-to-many table between the group and the people.
You may need multiple ways to store relationships, to account for all the different types.

A: I know it's an old thread but still relevant.
Let's say Mary and John are married and have two children, Jane and Matt...
What about this table structure:
side1    | side1type    | side2type    | side2
----------------------------------------------------
Mary     | wife         | husband      | John
Jane     | child        | mother       | Mary
Jane     | child        | father       | John
Matt     | child        | mother       | Mary
Matt     | child        | father       | John
Jane     | sister       | brother      | Matt

When we are interested to find one person relatives we could run 2 queries looking for that person in column side1 and then in column side2...
Or maybe one query looking for that person in one or another column, than we use logic in our application and:
If that person has been found in side1 column
   we print side1, side1type, "of ", side2

Mary is wife of John

If that person has been found in side2 column
   we print side2, side2type, "of ", side1

Mary is mother of Jane
  Mary is mother of Matt

Or maybe more elegant...
If that person has been found in side1 column
   we print side2 (side2type)

John (husband)

If that person has been found in side2 column
   we print side1 (side1type)

Jane  (child)
  Matt  (child)

A: make sure you include dates in the link table. since a relationship does not last forever...
**person**
person_id
name

**person_person**
person_id_1
person_id_2
relationship_type_id
begin_date
end_date

**relationship_type**
relationship_type_id
name

A: You may design a table with the following structure,
person1, relation, person2

now when inserted values into it, for example, if john is husband of kelly, then
john, is husband of, kelly

and to apply same for kelly
kelly, is wife of, john

You will need to define relationship for both persons, but it will yield good result while fetching.

A: I ran into this situation recently and after trying out a couple different options ended up with something like this (pardon the pseudo-code model):
class Person {
    int Id;
    List<RelationshipMember> Relationships;
}

class RelationshipMember {
    int Id;
    Person RelatedPerson;
}

class Relationship {
    int Id;
    List<RelationShipMember> RelationshipMembers;
}

You can put properties on Relationship to model it's type and properties on the RelationshipMember to model the role within the relationship if that's required.
And of course, this allows for threesomes, too. :)
On this particular project, I'm using an ORM tool (nHibernate with Fluent Automapping), here's how the database tables are expressed:
TABLE Person (
   Id int NOT NULL
)

TABLE Relationship (
   Id int NOT NULL
)

TABLE RelationshipMember(
Id int NOT NULL,
Relationship_id int NOT NULL,
    Person_id int NOT NULL
)

A: @bill K :
"If you have a three-column table that lists two people and a relationship type, it's better, but you still have a problem with reciprocal relationships."
Does the solution you first suggested (one table per relationship type) NOT suffer from that very same problem ?
BTW your term ("reciprocal") is incorrect, imo.  You are talking of relations (mathematical sense) that have the property of being symmetric.  An area that theory leaves answered only very unsatisfactorily, as far as I know.
The three-column option is how it was done in my very first project, almost 30 years ago, and I believe it still is the best approach possible.  Especially since "the possible/relevant set of inter-persons relationship types" are, eurhm, a rather volatile kind of thing in any business I can imagine.


text:
Q: Problems assigning variable to output of command I am using wc -l < songs.txt to find out how many lines are in songs.txt
Then I want to store that as a variable. I've tried these:
OUT = $(wc -l < songs.txt)
OUT = "$(wc -l < songs.txt)"

I tried a lot from How to set a variable to the output from a command in Bash?
But I still get command not found error for OUT
wc -l < songs.txt works on its own
What simple thing am I missing here?

A: it's easy first of all don't use space after and before equal sign
OUT=$(wc -l < songs.txt)

second for call it you can write something like this :
echo $OUT

Good luck

A: Spaces should be avoided.
out=$(wc -l < songs.txt)


text:
Q: Simple linear regression vs Multiple Linear regression interpretation Suppose we have a multiple linear regression model with two predictors, $X_1$ and $X_2$:
$$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon.$$
We can interpret $\beta_1$ as the expected increase in $Y$ with a unit increase in $X_1$ when $X_2$ is held constant. This is because $\beta_1$ is the partial derivative of the expected value of $Y$ with respect to $X_1$.
Further, suppose that we also compute the simple linear regression of $Y$ against $X_1$:
$$Y = b_0 + b_1X_1 + \epsilon.$$
Then I've seen by some authors that: $b_1$ is the expected increase in $Y$ with a unit increase in $X_1$ without holding $X_2$ constant.
But I really don't see the last point because for me in the simple linear regression is  like holding constant $X_2$ by giving it a zero value.
So why do they say the in the simple linear regression all other predictors not considered are not constant?
I would really appreciate if you can help me clarify this idea.

A: For the most part, you should read my answer to: Is there a difference between 'controlling for' and 'ignoring' other variables in multiple regression?, of which, this is nearly a duplicate.

To address your explicit question more directly, $X_2$ is not being held constant.  What you have done is set $\beta_2 = 0$, not adjust the data to account for what they would be like if $X_2$ were $0$ for all data in the dataset.
Unless $X_1$ and $X_2$ were perfectly uncorrelated in your dataset, controlling for $X_2$ would amount to shifting the $X_1$ values to some degree.  As a result, the estimated $\hat\beta_1$s between the two models would differ.

A: Try estimating the two models on some dataset:
$$Y = \beta_0 + \beta_1X_1 + \epsilon$$
and
$$Y = \beta_0 + \beta_1X_1 + \beta_2X_2 + \epsilon$$
What you would usually notice is that the $\beta_0$ and $\beta_1$ parameters differ between the two models. In the second you control for $X_2$, in the first one you don't, hence the different parameter estimates. In the first model, by the fact that we didn't include $X_2$, it was accounted for by noise term $\epsilon$. If in the second model you set $X_2=0$ you would consider only the scenario where it is exactly zero. So in fact, in simple linear regression, all the other predictors are accounted for by the random noise, rather than considered constant.


text:
Q: How to use flowtype with cdn included objects? I'd like to use flowtype to check some Vue codes, the vue is included:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

and the js code:
//@flow
var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
})

but flowtype will report error, how to deal with this kind of error:
var app = new Vue({
               ^^^ identifier `Vue`. Could not resolve name

A: Currently, neither official Vue.js or flow-typed has official Flowtype definitions for Vue.js.
So, it looks like the following line is a quick fix:
declare var Vue:any


text:
Q: React JS event handler arguments I was reading about "Lifting State Up" in React JS documentation and there is something I am not very clear about. The codepen can be found here: https://codepen.io/valscion/pen/jBNjja?editors=0010
In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange, but the latter contains a parameter of temperature. How are we passing this parameter? There is no argument passed in the onTemperatureChange. What am I missing here?
Hope someone can help me understand this.
class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}

class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature) {
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature) {
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />
        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict
          celsius={parseFloat(celsius)} />
      </div>
    );
  }
}

A: Let's look at the TemperatureInput component first. When its input element fires a change event, this is handled by handleChange(e) (declared within the TemperatureInput component). You'll notice that it then calls this.props.onTemperatureChange with the parameter e.target.value (this is the value attribute of the input element).
Where does this.props.onTemperatureChange come from? It's set by the parent component Calculator that instantiates it. Looking at the render method of the Calculator component, you'll notice that the onTemperatureChange prop for each TemperatureInput instance is set to this.handle[Cel/Far]Change (both methods declared within the Calculator component).
So when the TemperatureInput component calls this.props.onTemperatureChange, it is in fact calling the handle[Cel/Far]Change method of the Calculator component.

A: Here to the TemperatureInput component you are passing the function (it acts like a pointer).
This is passed from Calculator to TemperatureInput component.
Now we see, our function handleCelsiusChange requires one argument, Therefore when we call onTemperatureChange function inside TemperatureInput component, we must be passing some variable there.
As you can see below code you are passing the parameter to the function call.
 handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

This where we are passing the argument to the function from TemperatureInput component

A:
In the TemperatureInput component, the onTemperatureChange event handler calls the handleCelsiusChange...

This assumption is incorrect.
You are passing a reference to the function object this.handleCelsiusChange to the attribute onTemperatureChange in the render function.
This function object is then used by calling it in TemperatureInput class.
this.props.onTemperatureChange(e.target.value)

If it were to call the handleCelciusChange in the JSX, the render would look like:
    <TemperatureInput
      scale="c"
      temperature={celsius}
      onTemperatureChange={this.handleCelsiusChange(some_value)} />


text:
Q: How can an external stylesheet be used to style Polymer 1.0 elements? Polymer 1.0 elements contain custom CSS variables that allow you to style them using inline styles as such:
<style is="custom-style">
  paper-toolbar {
    --paper-toolbar-color: blue;
  }
</style>

This works and is fantastic. How can I accomplish the same, but using an external stylesheet?  Adding is="custom-style" to the link tag does not seem to have any effect, as the following does not work:
<link rel="stylesheet" media="all" href="app.css" is="custom-style">

A: You can load the HTML file containing your custom-style like you would with a polymer element:
<link rel="import" href="my-custom-style.html">

And your my-custom-style.html file would contain:
<style is="custom-style">
    paper-toolbar {
        --paper-toolbar-color: blue;
    }
</style>

As of Polymer 1.1, this feature is now deprecated. See here for an update answer


text:
Q: pandas reshape multiple columns fails with KeyError For a pandas dataframe of:

defined by:
import pandas as pd
df = pd.DataFrame({'id':[1,2,3], 're_foo':[1,2,3], 're_bar':[4,5,6], 're_foo_baz':[0.4, 0.8, .9], 're_bar_baz':[.4,.5,.6], 'iteration':[1,2,3]})
display(df)

I want to reshape to the following format:
id, metric, value, iteration
1, foo    , 1    , 1
1, bar    , 4    , 1
1, foo_baz, 0.4  , 1
1, bar_baz, 0.4  , 0.4
...

A:
pd.wide_to_long(r, stubnames='re', i=['re_foo', 're_bar', 're_foo_baz', 're_bar_baz'], j='metric')

only results in a KeyError.
How can I fix the reshape to work fine?

A: Here's a way using stack:
# fix column name, remove re_
df.columns = df.columns.str.replace(r're_', '')

# reshape dataframe into required format
df = df.set_index(['id','iteration']).stack().reset_index().rename(columns={'level_2':'metric', 0: 'value'})

    id  iteration   metric  value
0    1          1      foo    1.0
1    1          1      bar    4.0
2    1          1  foo_baz    0.4
3    1          1  bar_baz    0.4
4    2          2      foo    2.0
5    2          2      bar    5.0
6    2          2  foo_baz    0.8
7    2          2  bar_baz    0.5
8    3          3      foo    3.0
9    3          3      bar    6.0
10   3          3  foo_baz    0.9
11   3          3  bar_baz    0.6

A: you can use pandas.melt and sort by id
df1 = df.melt(id_vars=['id', 'iteration'],
              var_name="matric").sort_values(by=['id'])
df1.matric = df1.matric.str.replace('re_','')

>>>
    id  iteration   matric  value
0    1          1      foo    1.0
3    1          1      bar    4.0
6    1          1  foo_baz    0.4
9    1          1  bar_baz    0.4
1    2          2      foo    2.0
4    2          2      bar    5.0
7    2          2  foo_baz    0.8
10   2          2  bar_baz    0.5
2    3          3      foo    3.0
5    3          3      bar    6.0
8    3          3  foo_baz    0.9
11   3          3  bar_baz    0.6

edit:
renaming the heading first is the right way

A: One option is to rename the columns before applying wide_to_long:
df.columns = df.columns.str.replace('re','value')

(pd
.wide_to_long(
    df,
    stubnames = 'value',
    sep='_',
    suffix = '.+',
    i = ['id', 'iteration'],
    j = 'metric')
.reset_index()
)
    id  iteration   metric  value
0    1          1      foo    1.0
1    1          1      bar    4.0
2    1          1  foo_baz    0.4
3    1          1  bar_baz    0.4
4    2          2      foo    2.0
5    2          2      bar    5.0
6    2          2  foo_baz    0.8
7    2          2  bar_baz    0.5
8    3          3      foo    3.0
9    3          3      bar    6.0
10   3          3  foo_baz    0.9
11   3          3  bar_baz    0.6

The renaming could also be done after the transformation:
df = pd.DataFrame({'id':[1,2,3],
                   're_foo':[1,2,3],
                   're_bar':[4,5,6],
                   're_foo_baz':[0.4, 0.8, .9],
                   're_bar_baz':[.4,.5,.6],
                   'iteration':[1,2,3]})

(pd
.wide_to_long(
    df,
    stubnames = 're',
    sep='_',
    suffix = '.+',
    i = ['id', 'iteration'],
    j = 'metric')
.squeeze()
.rename('value')
.reset_index()
)
    id  iteration   metric  value
0    1          1      foo    1.0
1    1          1      bar    4.0
2    1          1  foo_baz    0.4
3    1          1  bar_baz    0.4
4    2          2      foo    2.0
5    2          2      bar    5.0
6    2          2  foo_baz    0.8
7    2          2  bar_baz    0.5
8    3          3      foo    3.0
9    3          3      bar    6.0
10   3          3  foo_baz    0.9
11   3          3  bar_baz    0.6


text:
Q: Terraform Variables prompting me when defined in tfvars There is something that I am not understanding about terraform variables.  I am getting prompted for two variables in when I run "terraform apply".   I don't think that I should be prompted for any as I defined a terraform.tfvars.  I am getting prompted for (applicationNamespace, and staticIpName) but I am not sure why.  What am I misunderstanding?
I created a file (terraform.tfvars):
#--------------------------------------------------------------
# General
#--------------------------------------------------------------
cluster = "reddiyo-development"
project = "<MYPROJECTID>"
region  = "us-central1"
credentialsLocation = "<MYCERTLOCATION>"
bucket = "reddiyo-terraform-state"
vpcLocation = "us-central1-b"
network = "default"
staticIpName = "dev-env-ip"
#--------------------------------------------------------------
# Specific To NODE
#--------------------------------------------------------------
terraformPrefix = "development"
mainNodeName = "primary-pool"
nodeMachineType = "n1-standard-1"
#--------------------------------------------------------------
# Specific To Application
#--------------------------------------------------------------
applicationNamespace = "application"

I also have a terrform script:
variable "cluster" {}
variable "project" {}
variable "region" {}
variable "bucket" {}
variable "terraformPrefix" {}
variable "mainNodeName" {}
variable "vpcLocation" {}
variable "nodeMachineType" {}
variable "credentialsLocation" {}
variable "network" {}
variable "applicationNamespace" {}
variable "staticIpName" {}

data "terraform_remote_state" "remote" {
  backend = "gcs"
  config = {
    bucket = "${var.bucket}"
    prefix = "${var.terraformPrefix}"
  }
}

provider "google" {
  //This needs to be updated to wherever you put your credentials
  credentials = "${file("${var.credentialsLocation}")}"
  project     = "${var.project}"
  region      = "${var.region}"
}

resource "google_container_cluster" "gke-cluster" {
  name     = "${var.cluster}"
  network  = "${var.network}"
  location   = "${var.vpcLocation}"

  remove_default_node_pool = true

  # node_pool {
  #   name = "${var.mainNodeName}"
  # }
  node_locations = [
    "us-central1-a",
    "us-central1-f"
  ]
  //Get your credentials for the newly created cluster so that microservices can be deployed
  provisioner "local-exec" {
    command = "gcloud config set project ${var.project}"
  }
  provisioner "local-exec" {
    command = "gcloud container clusters get-credentials ${var.cluster} --zone ${var.vpcLocation}"
  }
}

resource "google_container_node_pool" "primary_pool" {
  name       = "${var.mainNodeName}"
  cluster    = "${var.cluster}"
  location   = "${var.vpcLocation}"
  node_count = "2"

  node_config {
    machine_type = "${var.nodeMachineType}"

    oauth_scopes = [
      "https://www.googleapis.com/auth/logging.write",
      "https://www.googleapis.com/auth/monitoring",
      "https://www.googleapis.com/auth/devstorage.read_only",
      "https://www.googleapis.com/auth/service.management.readonly",
      "https://www.googleapis.com/auth/servicecontrol",
      "https://www.googleapis.com/auth/trace.append",
    ]
  }

  management {
    auto_repair  = true
    auto_upgrade = true
  }
  autoscaling {
    min_node_count = 2
    max_node_count = 10
  }
}

# //Reserve a Static IP
resource "google_compute_address" "ip_address" {
  name = "${var.staticIpName}"
}

//Install Ambassador
module "ambassador" {
  source      = "modules/ambassador"
  applicationNamespace = "${var.applicationNamespace}"
}

A: You can try to force it to read your variables by using:
terraform apply -var-file=<path_to_your_vars>

A: For reference, read below, if anybody face the similar issue.
"terraform.tfvars" is the default variable file name, from where terraform will read variables.
If any other file name is used, it needs to be passed in the command line i.e: "terraform plan –var=whateverName.tfvars
Also, order of Loading for variables by Terraform program.

*

*Environment Variables

*terraform.tfvars

*terraform.tfvars.json

*Any .auto.tfvars

*Any –var or –var-file options


text:
Q: Add dynamic number of SelectMultipleField's to wtf-flask form I've looked at the documentation and a couple other Q/As on here but I can't seem to make the code work.  I have a basic form in a forms.py file:
class SimpleForm(Form):
    list_of_files = ['Option 1','Option 2','Option 3','Option 4','Option 5','Option 6']
    files = [(x, x) for x in list_of_files]
    acheckbox = MultiCheckboxField('Label',choices=files)
    third_list = ['Special Analysis']
    third_files = [(x, x) for x in third_list]
    bcheckbox = MultiCheckboxField('Label', choices=third_files)
    category_1 = SelectField(u'', choices=())
    category_2 = SelectField(u'', choices=())
    category_3 = SelectField(u'', choices=())

(I populate the categories later).  I also call this form in my views.py file.
form = SimpleForm()

I want to dynamically add several SelectMultipleField's (depending on the # of columns in an user uploaded csv file).  I want to pass a list variable (category) with the names of the columns n=1-5 and generate that many fields with another list (unique_values) which are the values of that field.  I was looking at the doc and tried to come up with this:
class F(Form):
    pass

    F.category = SelectMultipleField('category')
    for name in extra:
        setattr(F, name, SelectMultipleFields(name.title()))
    form = F(request.POST, ...)

I know it's not right.  How do I modify to append SelectMultipleField's to my original "SimpleForm?"
I ultimately want to generate n numbers of the following:
unique_values = [('1', 'Choice1'), ('2', 'Choice2'), ('3', 'Choice3')]
category_4 = SelectMultipleField(u"",choices=unique_values)

UPDATE:
To call the form on views.py, I use the following:
select_dict = {'Geography': ['US', 'Asia', 'Europe'], 'Product Type': ['X', 'Y', 'Z']}
form= F(request.form,select_dict)

My subclass (on forms.py) is:
class F(SimpleForm):
pass
#select_dict could be a dictionary that looks like this: {category_+str(col_number): set of choices}
def __init__(self, select_dict, *args, **kwargs):
    super(SimpleForm, self).__init__(*args, **kwargs)
    print(select_dict)
    for name,choices in select_dict.items():
        test = [(x, x) for x in choices]
        setattr(F, name, SelectMultipleField(name.title(),choices=test))

I'm getting the following error: "formdata should be a multidict-type wrapper that supports the 'getlist' method"

A: Basically what you are trying to do is append to SimpleForm a variable number of SelectMultipleField elements, each with a different choice set.
First of all, to add the SelectMultipleField elements to the original SimpleForm you should just subclass it (instead of the original Form) when you define F.
Second of all, you can use most of the code you already wrote, like so:
class F(SimpleForm):
    pass

#select_dict could be a dictionary that looks like this: {category_+str(col_number): set of choices}
for name,choices in select_dict.items():
    setattr(F, name, SelectMultipleFields(name.title(),choices=choices))

form = F(request.POST, ...)

To render the dynamic form in the template, you will need a custom Jinja filter (check out this answer) and maybe a simpler way to render a field (like described on this page).


text:
Q: Using an old version of N2CMS, how can I use .no instead of /no to change language? The project I am working with is using an old version (v.2.1.0.1) of N2CMS.
To start with, I want to avoid upgrading to the latest N2 version, not because I don't like new things (because I do) but because since I am using such an old version it would take a lot of efford trying to upgrade it and if there's a way to solve this issue in a more time efficient way then I need to do that instead.
What I need to do is to enable the url to set the languageroot for the website and having it not only rely on the /lang. For example, i want my website.se to point towards /sv and my website.no to point towards /no. Right now .se is default so no matter the URL, swedish is the language shown. The twist is, and the reason for why I need it done this way, that I am loading data from another database and showing it on the site, list of categories and products (/keyrings for example). These things don't have the /sv or /no in the url. The result here is that even if I get /no to working along side the .no url, as soon as I click on an item in that list without the language code in the url then I will automatically be redirected to the default swedish languageroot. So I want to completely rely the N2CMS languageroot on the URL and not the /lang. I know that this is possible in the later versions of N2CMS but I am hoping there's a workaround in the older versions as well.
In this version I have a startpage and under the startpage i have languageroots. Each language root has the option to enter an URI Name, in my case i have swedish and norwegian so that's /sv and /no. An example from the site could look like this: /sv/om-oss, the norwegian way would be /no/om-oss.
In the later versions (that I use for other and newer projects) I have just the startpage and in its settings I am able to enter the hostname, this is what I want for my site (not necessarily have it changable in N2CMS, it's easier to just have it coded in).
Does anyone have any experience in this, or knowledge deeper than mine when it comes to these sort of things?

A: Just for record, this problem got solved http://n2cms.codeplex.com/discussions/397494


text:
Q: jQuery click detection outside of specified area problem Hey guys, ok, so, I have a jPlayer jQuery plugin playlist hidden on my home page (http://www.marioplanet.com).
Now, it is hidden by default and is only supposed to be activated upon clicking the image labeled "Music" in the upper-right-hand-corner of my header
.
This works great, and once an end-user clicks the image, a nice, slick slideToggle action occurs on the
 element and it is revealed.
Now, everything holds.
Until, the end-user clicks anywhere except the Music image again, the
 element will slideToggle yet again, vanishing.
The only problem, is when the end-user clicks upon the Music image again, because, as far as I know, it slideToggles twice!
That is definitely not what we want.
So, here is the code which was adapted by Magnar's helpful post:
$('#text_music').click(function() {
    $('#jplayer').slideToggle(500, function() {
        $("body").click(function (event) {
            var outside = $(event.originalTarget).parents("#popup").length === 0;
            if (outside) {
                $("#jplayer").slideToggle(500);
                $("body").unbind("click");
            }
        });
    });
});

#text_music is my image reading "Music"
#jplayer is my
 containing my jPlayer plugin
So, what I want to try and do is declare a variable, just like how var outside is declared in the above code, which handles with the clicking of the #text_music image once the #jplayer
 is already visible.
However, I need a little assistance in understanding the meaning of this variable.
Anyone want to offer any words of wisdom?
:) Thanks!

A: Have a look at jQuery outside events plugin to detect events outside of the specific element.


text:
Q: Titanium Studio - Trying to run example app I'm newbie in Titanium Studio and I have some weird questions:
- When I choose a new Mobile Project and trying to Run under the Android SDK Emulator,
I able to see the phone screen but when I'm going in the emulator to the apps list, I cant see the application I just created...
any ideas?
thanks.

A: When you hit Run it is automatically installed in your device/emulator.
Be sure it was successfully installed in your emulator first, please see:

Android troubleshooting
The initial launch of the Android emulator can be quite slow and Studio may timeout before it can install and launch the application. If this happens just click Run in Studio again. Subsequent launches should not time out on the same virtual device.
http://docs.appcelerator.com/titanium/latest/#!/guide/Creating_Your_First_Titanium_Apps-section-37541502_CreatingYourFirstTitaniumApps-AddaTableView


text:
Q: Cannot connect using SQL Server JDBC driver When attempting to use ballerina/jdbc with the Microsoft JDBC driver I receive:
error: ballerina/runtime:CallFailedException, message: call failed
at ..<stop>(jdbc_test.bal:4) caused by error at ballerina/jdbc:stop(endpoint.bal:66)

Has anyone been able to accomplish this?
I'm using:

*

*Ballerina 0.981.1

*Microsoft JDBC Driver 7.0 for SQL Server (with mssql-jdbc-7.0.0.jre10.jar placed into C:\Program Files\Ballerina\ballerina-0.981.1\bre\lib)

*VS Code 1.27.1

Here's a repro:
import ballerina/jdbc;

endpoint jdbc:Client testDB {
    url: "jdbc:sqlserver://localhost;integratedSecurity=true;",
    poolOptions: { maximumPoolSize: 5 }
};

function main(string... args) {
}

I've tried connecting to my local sql server as well as an Azure SQL instance. I've also tried connecting with SQL Server authentication using both
endpoint jdbc:Client testDB {
    url: "jdbc:sqlserver://localhost;user=[user];password=[pass];",
    poolOptions: { maximumPoolSize: 5 }
};

and
endpoint jdbc:Client testDB {
    url: "jdbc:sqlserver://localhost;",
    username: "[user]",
    password: "[pass]",
    poolOptions: { maximumPoolSize: 5 }
};

A: Fixed. I had to switch from the mssql-jdbc-7.0.0.jre10.jar driver to mssql-jdbc-7.0.0.jre8.jar.


text:
Q: Changing an object in Java inside a function I tried to implement a merge sort for a list using the added code. The problem I encountered, which I have no idea what is causing it is: If I call recursiveMergeSort directly I get the correct sorted list back, but if I try to sort the list by calling mergeSort on it I only get a list of the first element.
I.E if in main I have a list = "d","a","f","g","b" then
list = recursiveMergeSort(list) // list will be "a","b","d","f","g"
mergeSort(list) // list will be "a"

What do I need to do for mergSort to give the same result as recursiveMergeSort?
 (The public void function was given to me in the API, that's why I created a private recursive function)
public static void mergeSort(List list) {
if (list == null) throw new NullPointerException("list");
    list = recursiveMergeSort(list);
    /* If I check list here, I get the correct result,
    only in the original it's wrong */
}
/** a recursive function for the merge sort  */
private static List recursiveMergeSort(List list) {

    int length = listLength(list);
    System.out.println(length);
    if (length <= 1) { // base case, list length 1
        return list;
    }

    // create sublists
    List left = new List(), right = new List();
    List.Node indexList = list.head;
    left.head = list.head;
    for (int i = 0; i < length / 2 - 1; i++ ) {
        indexList = indexList.getNext();
    }
    right.head = indexList.getNext();
    indexList.setNext(null);

    left = recursiveMergeSort(left); // recursively work on them
    right = recursiveMergeSort(right);
    List tempList = mergeLists(left, right); // final result
    return tempList;
}

(Merge lists just merges two ordered lists into an ordered list.)

A: list is a reference variable, referencing a List value.
You can't change a referenced value just by changing the value of a variable that references it.
Change your initial function to:
public static List mergeSort(List list) {
if (list == null) throw new NullPointerException("list");
    return recursiveMergeSort(list);
}

The value you return will be the sorted list.
If you do need to change the argument in place, try:
public static void mergeSort(List list) {
if (list == null) throw new NullPointerException("list");
    List temp = recursiveMergeSort(list);
    list.clear();
    list.addAll(temp);
}

You can change an object by calling methods on it, or changing the values of fields in it, either the object itself or components of it.  indexList in your recursiveMergeSort is another reference for nodes in your starting list, and you are altering it with the setNext(null)


text:
Q: Why I am getting Lat Long 0.0? Default Data Save after click

Static Data Save

I am getting current location correctly but when store lat and lang into my sqlite database then i am getting lat and long 0.0 into my table. It is showing lat and lang 0.0 and other values are null.
public class MapActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
    LocationListener {

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
TextView add;
Button button;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
String getbuildingname,locality,subLocality,current_state,current_country,postal_code;
double longitude,latitude;
private GoogleMap mMap;
DatabaseHelper databaseHelper;
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    databaseHelper = new DatabaseHelper(this);
    button = findViewById(R.id.button);
    add = (TextView)findViewById(R.id.current_location);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager()
                    .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    add_location();

}
// Map ready method
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setZoomGesturesEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);
    //Initialize Google Play Services
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    } else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(MapActivity.this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
}
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, this);
    }
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }
 //Showing Current Location Marker on Map
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    LocationManager locationManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(new Criteria(), true);
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    assert provider != null;
    Location locations = locationManager.getLastKnownLocation(provider);
    List<String> providerList = locationManager.getAllProviders();
    if (null != locations && providerList.size() > 0) {
        longitude = locations.getLongitude();
        latitude = locations.getLatitude();

        // Geo Coder
        Geocoder geocoder = new Geocoder(getApplicationContext(),
                Locale.getDefault());
        try {
            List<Address> listAddresses = geocoder.getFromLocation(latitude,
                    longitude, 1);
            if (null != listAddresses && listAddresses.size() > 0) {
                getbuildingname = listAddresses.get(0).getPremises();
                locality = listAddresses.get(0).getLocality();
                subLocality = listAddresses.get(0).getSubLocality();//
                current_state = listAddresses.get(0).getAdminArea(); //
                current_country = listAddresses.get(0).getCountryName(); // India
                postal_code = listAddresses.get(0).getPostalCode(); //
                markerOptions.title(""+getbuildingname+","+locality+"," + subLocality + "," +
                        current_state + "," + current_country + "," + postal_code);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                this);
    }
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();
                    }
                    mMap.setMyLocationEnabled(true);
                }
            } else {
                Toast.makeText(this, "permission denied",
                        Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}

private void add_location(){
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
            Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
        }
    });
}

 //Permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

// Database Helper
boolean insert_location(String lat , String lang , String state , String country, String pin){

    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(Location_Table_Column2,lat);
    values.put(Location_Table_Column3,lang);
    values.put(Location_Table_Column5,state);
    values.put(Location_Table_Column6,country);
    values.put(Location_Table_Column7,pin);
    long result =database.insert(Table_Name_Loaction,null,values);
    return result != -1;
}

Many times address title is disappear when I tap over pin.
Table is created successfully and lat and lang is saving 0.0 and other values are null.

A: it will capture the locality and others the moment it detected it not empty
Geocoder geocoder;
        List<Address> listAddresses;
        geocoder = new Geocoder(this, Locale.getDefault());

        try {
            listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
            if(!listAddresses.get(0).getLocality(0).equals("") || !listAddresses.get(0).getAdminArea(0).equals("") || !listAddresses.get(0).getCountryName(0).equals("")) {
                locality = listAddresses.get(0).getLocality(0);
                current_state = listAddresses.get(0).getAdminArea(0);
                current_country = listAddresses.get(0).getCountryName(0);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

and add this on your onClick, it will validates your inputs
if(lat.equal("") ||lng.equal("") ||locality.equal("") ||current_state.equal("") ||current_country.equal("") ){

                    Toast.makeText(MapsActivity.this, "Somethings Empty", Toast.LENGTH_SHORT).show();

                }else{
                    databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
                    Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
                }

A: Silly Mistake
 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String lat = String.valueOf(latitude);
            String lng = String.valueOf(longitude);
            databaseHelper.insert_location(lat,lng,locality,current_state,current_country);
            Toast.makeText(MapActivity.this, locality, Toast.LENGTH_SHORT).show();
        }


text:
Q: RecyclerView muestra un solo dato, JSON A la hora de mostrar datos solo muestra uno solo, esta es mi base de datos:

Cuando quiero mostrar los negocios rubro supermercado solamente me aparece el primero.
Este es el codigo del activity:
package com.example.emiliano.myfirstapp;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.textclassifier.TextLinks;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.emiliano.Entidades.negocio;
import com.example.emiliano.adaptador.listanegocioadapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class Listanegocio extends AppCompatActivity implements Response.Listener<JSONObject> , Response.ErrorListener {

    private String categoria;
    ProgressDialog progreso;
    RecyclerView recyclernegocio;
    ArrayList<negocio> listanegocio;
    RequestQueue request;
    JsonObjectRequest jsonObjectRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listanegocio);

        Bundle bundle=getIntent().getExtras();             //RECIBO CATEGORIA DE LOS BOTONES
        categoria = bundle.getString("categoria");

        listanegocio = new ArrayList<>();

        recyclernegocio = (RecyclerView) findViewById(R.id.IdRecycler);
        recyclernegocio.setLayoutManager(new LinearLayoutManager(this));
        recyclernegocio.setHasFixedSize(true);

        request = Volley.newRequestQueue(this);   //aca

        cargarwebservice();

    }

    private void cargarwebservice() {
        progreso = new ProgressDialog(this);   //getappcontext
        progreso.setMessage("Consultando...");
        progreso.show();
        String url = "http://192.168.0.101/DBRemota/wsJSONConsultarNegocio.php?categoria=" + categoria;
        jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url,null,this,this);
        request.add(jsonObjectRequest);
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        progreso.hide();
        Toast.makeText(this,"No se pudo consultar....." + error.toString(), Toast.LENGTH_LONG).show();
        Log.i("ERROR" , error.toString());
        progreso.hide();
    }

    @Override
    public void onResponse(JSONObject response) {
        negocio negocio=null;

        JSONArray json=response.optJSONArray("negocio");

        try {

            for (int i=0;i<json.length();i++){
                negocio=new negocio();
                JSONObject jsonObject=null;
                jsonObject=json.getJSONObject(i);

                negocio.setNombre(jsonObject.optString("nombre"));  //NOMBRE DEL ARCHIVO PHP
                negocio.setCategoria(jsonObject.optString("categoria"));
                negocio.setDescripcion(jsonObject.optString("descripcion"));

                listanegocio.add(negocio);
                Toast.makeText(this,"-"  ,Toast.LENGTH_LONG).show();
            }
            progreso.hide();
            listanegocioadapter adapter=new listanegocioadapter(listanegocio);   //CREAR RECYCLER
            recyclernegocio.setAdapter(adapter);

        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(this, "No se ha podido establecer conexión con el servidor" +
                    " "+response, Toast.LENGTH_LONG).show();
            progreso.hide();
        }

    }
}

Este es el logcat, cuadno presiono supermercado:

y el resultado:


text:
Q: A question about non-singular matrix size $n×n$ Matrix $A$ is a matrix of size $n×n$ with entries of even and odd natural numbers that differ from one another. In order for $A$ to be a non-singular matrix, the minimum number of odd number entries is · ·
GIve me a hint.
We know non singular matrix is a matrix that have determinat is equal 0.

A: We can easily construct a nonsingular matrix with distinct even positive integer entries. It is enough to make the diagonal elements larger than the sum of the other elements in the corresponding row.


text:
Q: Truncated output log files when logging stdout and stderr separately I have set up a subprocess command within a context manager that pipes the stdout and stderr to separate files via my own logger. This is a variation on the answer given here:
https://stackoverflow.com/a/4838875/4844311
My code is as follows:
import logging
import subprocess

with StreamLogger(logging.DEBUG, my_out_logger) as out:
    with StreamLogger(logging.ERROR, my_err_logger) as err:
        p = subprocess.Popen(cmd, shell=False, stdout=out, stderr=err)
        p.communicate()
        p.wait()

where my_out_logger and my_err_logger are logging objects with handles that log to files etc.
The StreamLogger code is similar to the code given at the link above:
import io
import os
import threading
import select
import time

class StreamLogger(io.IOBase):
    def __init__(self, level, logger):
        self.logger = logger
        self.level = level
        self.pipe = os.pipe()
        self.thread = threading.Thread(target=self._flusher)
        self.thread.start()

    def _flusher(self):
        self._run = True
        buf = b''
        while self._run:
            for fh in select.select([self.pipe[0]], [], [], 0)[0]:
                buf += os.read(fh, 1024)
                while b'\n' in buf:
                    data, buf = buf.split(b'\n', 1)
                    self.write(data.decode())
            time.sleep(0.01)
        self._run = None

    def write(self, data):
        return self.logger.log(self.level, data)

    def fileno(self):
        return self.pipe[1]

    def close(self):
        if self._run:
            self._run = False
            while self._run is not None:
                time.sleep(0.01)
            os.close(self.pipe[0])
            os.close(self.pipe[1])

The only significant difference between my code and the code provided by the answer at the link above is that my code sends the logging message to a logger that redirects according to its handles rather than logging directly, as in the code at the link.
This code all works fine most of the time.
But I have noticed that every so often there is a truncated output logging file. It looks like the output file being written by a FileHandler in my_out_logger is being closed before all the stdout content has been written.
I am not sure why this is happening or where to fix the code. For now I have just added a time.sleep(0.3) statement between p.communicate() and p.wait() and this reduced the frequency of truncated files, but it seems like an ugly solution.
I would rather understand what is going wrong and fix it properly. I welcome any suggestions or insight.

A: I think I've finally figured it out.
The problem here is that the StreamLogger code can't explicitly check to make sure the stdout is fully written. Once the main thread running the subprocess receives a returncode, it exits the context manager, calling the __exit__() method of the StreamLogger, which is inherited from IOBase (source code here). And this calls close() which changes the self._run attribute to False. This causes the thread that is polling the pipe to stop looping, regardless of what is still coming through the pipe.
This works fine for most commands with small to moderate outputs to stdout, where there is no lag time between the returncode returning and the output being written. But in my case I'm running a program through subprocess with a substantial amount of text written to stdout. So there's a kind of race against time to try and get the pipe cleared before the main thread tells the child thread to stop polling the pipe.
The two critical variables here are the size of the buffer being read from the pipe and the frequency at which the pipe is polled. I fixed my problem by increasing the buffer size in os.read() to 4096, and also removing the time.sleep() in the while loop in the _flusher() method. This maximizes the amount of data that can be read from the pipe and in my case ensures the output is fully logged before the logging loop stops.


text:
Q: IndexError: index 1 is out of bounds for axis 1 with size 1 when using python lime I am trying to validate my ANN built on tabular data with XAI methods to improve transparency. But when I am using the lime method I am getting this error, and I am not able to debug it. Kindly help me as I am new in this field.
I want to make the model more transparent and explainable as i am trying to improve it s accuracy and shoe how the accuracy is improving using different ML models.
tIndexError                                Traceback (most recent call last)
<ipython-input-54-d845b9c549ee> in <module>
----> 1 exp = interpretor.explain_instance(
      2     data_row=X_Test.iloc[5], ##new data
      3     predict_fn=classifier.predict
      4 )
      5

1 frames
/usr/local/lib/python3.8/dist-packages/lime/lime_base.py in explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, feature_selection, model_regressor)
    180
    181         weights = self.kernel_fn(distances)
--> 182         labels_column = neighborhood_labels[:, label]
    183         used_features = self.feature_selection(neighborhood_data,
    184                                                labels_column,

IndexError: index 1 is out of bounds for axis 1 with size 1 type here


text:
Q: DataDog Agent Upgrade on Azure Cloud Service I'm running an Azure Cloud Service with a WebRole.
We run the DataDog Agent on each of our server instances, by running a startup task that executes a .cmd file.
Previously we have been using the latest version of DataDog Agent 5, and installing it using this -
start /w cmd
set log=datadog-install.log
set api_key=%1

sc query | findstr DatadogAgent
if ERRORLEVEL 1 (
    echo "Datadog Agent service not detected" >> %log%
    echo "Starting the installation" >> %log%

    if exist ddagent.msi (
        echo "Already has the installer" >> %log%
    ) else (
        echo "Fetching the Agent Installer" >> %log%
        powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://s3.amazonaws.com/ddagent-windows-stable/ddagent-cli.msi', 'ddagent.msi')"
    )

    echo "Starting the installer" >>%log%
    msiexec.exe /qn /i ddagent.msi APIKEY=%api_key% /L+ %log%
) else (
    echo "Agent already exists, skipping install" >>%log%
)

echo "Finished Install" >>%log%
exit 0

Now we are trying to upgrade to the latest version of DataDog Agent 6 using this, which is failing to install and register the instance as an available host in DataDogs dashboard -
start /w cmd
set log=datadog-install.log
set api_key=%1

sc query | findstr DatadogAgent
if ERRORLEVEL 1 (
    echo "Datadog Agent service not detected" >> %log%
    echo "Starting the installation" >> %log%

    if exist ddagent.msi (
        echo "Already has the installer" >> %log%
    ) else (
        echo "Fetching the Agent Installer" >> %log%
        powershell -Command "(New-Object System.Net.WebClient).DownloadFile('https://s3.amazonaws.com/ddagent-windows-stable/datadog-agent-6-latest.amd64.msi', 'ddagent.msi')"
    )

    echo "Starting the installer" >>%log%
    msiexec.exe /qn /i ddagent.msi APIKEY=%api_key% /L+ %log%
) else (
    echo "Agent already exists, skipping install" >>%log%
)

echo "Finished Install" >>%log%
exit 0

The URL is of course different in each case.

A: If the Windows OS is D drive, the setting is installed in D:\ProgramData\Datadog.
Copying it to C:\ProgramData\Datadog will work, but I submitted an improvement request to Datadog Support.


text:
Q: For a given Azure AD Service Principal, Get a list of the Azure Objects and Rights We are trying to figure out all the rights an Azure Active Directory Service Principal (AADSP) has to objects in our Azure tenant.
For example an AADSP might have:

*

*Read rights to SharePoint Online site collection A

*Write permissions to SharePoint Online site collection B

*Get permission to Azure Function A

*Post permission to Azure Function B

*Select permissions to SQL Database A

We are hoping that this information to stored in a collection within the Service Principal object. But we have not been able to locate the collection using Azure Graph.
https://graph.microsoft.com/v1.0/servicePrincipals
Is our only option to loop thru all Azure objects and check each object's permission and see which Service Principal have been granted rights?

A: There's no single API to query all sets of permissions given to a SP: application permissions AKA app roles, Azure AD directory permissions, and Azure RBAC.
You can obtain application permissions using MS Graph List appRoleAssignments operation, Azure AD role assignments trough List unifiedRoleAssignments, and Azure RABC permissions using Azure REST API Permissions - List For Resource operation.
Depending on the set of permissions, you may have to list all resources to find what assignments are available for a given SP.


text:
Q: Partitions and cdrom are not automounted Provide my spec and sorry for my poor English first.

*

*MB: Gigabyte G31M-S2L (bios ver. F9)

*CPU: intel E5200

*2G RAM

*HD1: WD 160G with 2 partitions
(partition 1:60G, NTFS, win xp; partition 2:100G, NTFS)

*HD2: WD 320G with 2 partitions
(partition 3:220G, NTFS; partition 4:100G, ext4, Ubuntu)

Recently, I tried to install Ubuntu 12.04 Beta 2 on my desktop PC (on partition 4).
At the beginning, everything looked great including the auto-mounting of partitions 1~3 and the unity (3D).
However, after I deleted and re-allocated the partitions on HD2 and re-installed Ubuntu on partition 4, the partitions 1~3 are no longer auto-mounted when I logged in the desktop (and even the inserted cdrom would not be mounted either).
The configurations during these two installations are all the same as default.
Are there any possible reasons or solutions for this issue?

A: Open a terminal and run these commands after mounting the drives in Nautilus please.
sudo fdisk -l
cat /etc/fstab
sudo blkid
mount

Generally partitions will only be automounted if they are told to - they might appear in the sidebar of Nautilus - that does not mean they are actually mounted.


text:
Q: How can i enable syntax highlighting for markdown files (.mdown) in Netbeans? I just realized, that netbeans does not support syntax highlighting for markdown files.
Is there any plugin for netbeans, that enables syntax highlighting for these .mdown files?

A: UPDATE (2011-Nov-18): To answer your question precisely, there is no certified plugin for markdown available from NetBeans Update Center.  I have not seen any good plugin for NetBeans with syntax highlighting functionality for markdown language yet.
There is a emerging community contributed open source NetBeans plugin for markdown at http://github.com/madflow/flow-netbeans-markdown and very soon the code highlighting feature may get added to that project.  We should add our comments and desire for getting that plugin released soon to show the demand for that plugin, which will motivate the creator of that plugin to release it soon.


text:
Q: Batch File "echo" and function output not correct I am having trouble with my "echo" output.
I have 3 functions (Speak, SpeakByChoice, SpeakChoose) and 1 label (Play)
Here is my code so far...
@ echo off
title Text Story Game

:Main
color 9f
echo ====== Main Menu ======
echo 1) Play
echo 2) Password
echo 3) Quit
set /p mainMenuChoice=
if %mainMenuChoice% == 1 goto Play
if %mainMenuChoice% == 2 goto Password
if %mainMenuChoice% == 3 exit
goto Main

:Play
REM Gameplay Start
call :Speak "Mayor" "Mmm, oh, I didn't see you there!"
call :Speak "Mayor" "Hello there! Welcome to Rockwell Town, er...who are you?"
set /p name= Choose your name:
call :Speak "Mayor" "Oh, why hello %name%! Good to meet you."
call :Speak "Mayor" "What did you come here for?"
call :SpeakChoose "I need a favor done." "Um, nothing..." (here is problem)
pause
pause

:Speak
echo.
echo [ %~1 ^>^> %~2 ]
pause>nul
goto :EOF

:SpeakByChoice
echo.
call :Speak %~1 %~2
call :Speak %~3 %~4
goto :EOF

:SpeakChoose
echo.
echo [ Choice: ]
echo 1) %~1
echo 2) %~2
set /p SpeakChoose=
if %SpeakChoose% == 1 call :SpeakByChoice "%name%" "%~1" "Mayor" "Okay, what can I help you with?"
if %SpeakChoose% == 2 call :SpeakByChoice "%name%" "%~2" "Mayor" "Oh okay....wait a minute. Didn't you ask me about moving in earlier?"
goto :EOF

:DNCSpeakChoose
echo.
echo You didn't choose anything.....
call :Speak "%name%" "..."

Although the output is this:
My name is "(blank)" but it shows as "I" in the SpeakByChoice call but not in the other calls like Speak
====== Main Menu ======
1) Play
2) Password
3) Quit
1

[ Mayor >> Mmm, oh, I didn't see you there! ] ↓

[ Mayor >> Hello there! Welcome to Rockwell Town, er...who are you? ] ↓
Choose your name: (not chosen...)

[ Mayor >> Oh, why hello (blank name IS here) ! Good to meet you. ] ↓

[ Mayor >> What did you come here for? ] ↓

[ Choice: ]
1) I need a favor done.
2) Um, nothing...
1

[ I (who is I?? this should've been blank) >> need ] ↓

[ Mayor >> Okay ] ↓
Press any key to continue . . .
Press any key to continue . . .

I am unsure what is triggering this problem. Is it something with SETLOCAL, or my :EOF, I don't know. But my Speak and SpeakChoose function works perfect, but my SpeakByChoice  does not.

A: Just add some quotes.  This worked great for me.
@echo off
title Text Story Game

:Main
color 9f
echo ====== Main Menu ======
echo 1) Play
echo 2) Password
echo 3) Quit
set /p mainMenuChoice=
if %mainMenuChoice% == 1 goto Play
if %mainMenuChoice% == 2 goto Password
if %mainMenuChoice% == 3 exit
goto Main

:Play
REM Gameplay Start
call :Speak "Mayor" "Mmm, oh, I didn't see you there!"
call :Speak "Mayor" "Hello there! Welcome to Rockwell Town, er...who are you?"
set /p name= Choose your name:
call :Speak "Mayor" "Oh, why hello %name%! Good to meet you."
call :Speak "Mayor" "What did you come here for?"
call :SpeakChoose "I need a favor done." "Um, nothing..." (here is problem)
pause
pause

:Speak
echo.
echo [ %~1 ^>^> %~2 ]
pause>nul
goto :EOF

:SpeakByChoice
echo.
call :Speak "%~1" "%~2"
call :Speak "%~3" "%~4"
goto :EOF

:SpeakChoose
echo.
echo [ Choice: ]
echo 1) %~1
echo 2) %~2
set /p SpeakChoose=
if %SpeakChoose% == 1 call :SpeakByChoice "%name%" "%~1" "Mayor" "Okay, what can I help you with?"
if %SpeakChoose% == 2 call :SpeakByChoice "%name%" "%~2" "Mayor" "Oh okay....wait a minute. Didn't you ask me about moving in earlier?"
goto :EOF

:DNCSpeakChoose
echo.
echo You didn't choose anything.....
call :Speak "%name%" "..."


text:
Q: change a variable value according to others variables values in R I want to change(or keep) a value of my dataframe according to the values of other variables in the same data frame. I've been looking for and answer without much success. This is an example of the database I have:
    date    day VM  id
12/01/2013  4   133 1
12/01/2013  4   163 1
13/01/2013  5   143 1
13/01/2013  5   123 1
14/01/2013  6   90  1
14/01/2013  6   190 1
15/01/2013  7   922 1
15/01/2013  7   952 1
16/01/2013  1   13  1
16/01/2013  1   25  1
17/01/2013  2   333 1
17/01/2013  2   123 1
18/01/2013  3   143 1
18/01/2013  3   169 1
19/01/2013  4   203 1
19/01/2013  4   133 1

each number represents a day (1:Monday, 2:tuesday,...)and each day has hundreds of data, also the information is for 8 days so there will be one day repeated ( but in a different date). When I apply summary it gives me the info mixing the data of the repeated day and I want to avoid that, My idea is to change the last day of use (the repeated one) to the number 8 but the repeated day change by id and I've got plenty of data. So far I've tried this:
unicos<-unique(data$id)
 data_corr<-NULL
 for(j in 1:length(unicos))
  subset<-data[which(data$id==unicos[j]),]
  subset$day1<-NULL
  times<-0
  vector<-NULL

  for(i in 1:(dim(subset)[1])){
    if((subset$day[i]<-subset$day[1]) && if (subset$date[i]<-subset$date[1])){
        vector<-c(vector, i)
        times<-times+1
        subset$day1[i]<-subset$day[1]
    }
    subset$day1<-8
  }
  Basal_corr<-rbind(Basal_corr, subset)
}

The first "for" is meant to apply the conditions one id at the time. The second part is the hard one. What I want to do is that if the day in the row [i] is in, is the same that the one in the first row (since it is the one that is going to repeat) then go check the date, if the date is the same too I want to keep keep the original day value in a new column called day1, and if the date is different then day1 value will be 8. I use Basal_corr<-rbind(Basal_corr, subset) to keep track of all the changes made by id. I get an "ERROR" everytime I try to run it, and I really  don't know whats grong I'm an R newbie and this is beyond what I know till now.

A: What you describe

each number represents a day (1:Monday, 2:tuesday,...)and each day has
  hundreds of data, also the information is for 8 days so there will be
  one day repeated ( but in a different date).

is actually the definition of a Julian date.  This function is included in base R.  I don't think you need any loops, it's just 2 lines of code.  FYI- R operates with vectors, so a function refers to the whole vector/column of values at the same time.
Days$date <- as.Date(Days$date, format = "%d/%m/%Y")
Days$day <- julian(Days$date) - julian(Days$date[1]) + 1
Days # yields

# date day  VM id
# 1  2013-01-12   1 133  1
# 2  2013-01-12   1 163  1
# 3  2013-01-13   2 143  1
# 4  2013-01-13   2 123  1
# 5  2013-01-14   3  90  1
# 6  2013-01-14   3 190  1
# 7  2013-01-15   4 922  1
# 8  2013-01-15   4 952  1
# 9  2013-01-16   5  13  1
# 10 2013-01-16   5  25  1
# 11 2013-01-17   6 333  1
# 12 2013-01-17   6 123  1
# 13 2013-01-18   7 143  1
# 14 2013-01-18   7 169  1
# 15 2013-01-19   8 203  1
# 16 2013-01-19   8 133  1


text:
Q: serializing List for Restlet using Jackson I am interfacing to a library. I get List<List> foodItemsList
How do I serialize foodItemsList using Jackson? This is happening while handling a GET.
I have understood how to serialize an object using Jackson/Restlet, but I am unable to figure it out for a list.
For a single object here is what I do
@Get("json")
public Representation represent(Variant variant) throws ResourceException {
    :
    ObjectMapper mapper = new ObjectMapper();
    String myFinString = mapper.writeValueAsString(profileSupportedInfo);
    :
    return myFinstring
}

getter setter for member data in profileSupportedInfo is what I provide.
Before creating mapper object, here is the call I make
List<List> totalfoodItem = someMemberFunc();
ObjectMapper mapper = new ObjectMapper
// my question - how do I serialize totalFoodItem

The preferred representation of totalFoodItem in JSON is as given below
{
 "food":[
       {"name":"apple","img_loc":"123_apple.jpg","energ":210,"food_unit":"1"},
       {"name":"rice","img_loc":"134_rice.jpg","energ":123,"food_unit":"100 gm"},
       :
   ]
}

What am I missing / failing to understand?
Thank you

A: I'm afraid in order to successfully serialize a List you have to turn it into an array.  The JVM won't serialize Lists with the appropriate type information (you'll just get a list of generic Objects when you deserialize), and this is not Jackson's fault.  However, if you serialize an array, the array must be typed and the objects inside the array will retain their types as well.
From your desired JSON, it appears all you need is a helper class that can collect the food information such as the following:
public class Food {
    private String name;
    private String img_loc;
    private String energ;
    private String food_unit;
    public FoodItem(String name, String value, String energ, String food_unit) {
        this.name = name;
        this.value = values;
        this.energ = energ;
        this.food_unit = food_unit;
    }
}

Now all you need is an object that has an array of Food objects as an attribute:
public class TotalFoodItem {
    private Food[] food;
    ...
}

and you can serialize that object.  Jackson probably won't produce JSON that looks exactly like your desired JSON (I haven't tried this code myself) but it should be pretty close.


text:
Q: Path confusion with Spatie's Laravel Media Library on Laravel Forge I am using Spatie's Laravel Media Library (v7) to create a pictures gallery. Locally (using Valet), the path to the file is OK. "/media/45/conversions/image-thumb.jpg" The equivalent path in Forge does not map - it needs to be "/storage/media/45/conversions/image-thumb.jpg" to work.
I have run php artisan storage:link and confirmed the symlink is created. This is the same (or equivalent) link in my local setup.
I know I could create a symlink to the media, but why would I need to do this on the remote server and not the local machine?

A: for those who are equally foxed as I was it seems that it was the config/filesystem.php that was wrong.
namely:
 'url' => env('APP_URL').'/'.env('MEDIA_DISK')

which seemed to be fine in Valet however It should have been.
'url' => env('APP_URL').'/storage/'.env('MEDIA_DISK')

which also seems to work in Valet and now also forge


text:
Q: Multiple domains, single node (express) app I'm trying to create simple node app, where the user can create a profile. Defaultly the url to his profile should be like - user1.myappname.com, but when the user fills a custom domain input (and points this domain to my app IP address), he should be able to use this custom domain like:
usercustomdomain.com => user1.myappname.com
usercustomdomain.com/someaction => user1.myappname.com/someaction
Does anybody here have an experience with implementing this with express.js? I mean not only custom domains but also subdomains.
Thank you
-M

A: Since your paths are the same no matter what the domain, this is simple. Grab the host name from the request passed into your Express route methods, and then do whatever lookup you need. Node doesn't care what the domain is, and as long as your domain has CNAMEs for your subdomains, and custom domains are pointed to the same IP address as myappname.com, node will respond to all requests in the same way.
For example, in your /someaction route:
app.get('/someaction', function(req,res) {
    hostName = req.header('host');
    // lookup info from database based on hostName, then output it ....
});


text:
Q: How to display ADO recordset in Access 2010 I need some help solving this issue. I'm a VB novice, by the way. I currently have a stored procedure that accepts 3 parameters and when executed returns a temp table. I tested my procedure in SQL and it's working as expected.
I'm using an Access form as my front-end. It is to accept the 3 parameters via 3 text box controls and then executes my procedure 'on click' (User clicks the search button to execute and fire up SQL). The code below accomplishes this, up until it's time to display my recordsets in a table. I'm stuck on how to display my results from my procedure in a table by utlizing ADO properties I'm ok with either displaying the recordset in a datasheet form or inserting them into a table.
The code seems to choke up at this line, where I'm attempting to view my recordset:
    rs.Open cmd
Access VB Code
Private Sub cmdExecuteQuery_Click()
   Dim conn As ADODB.Connection
   Dim cmd As ADODB.Command
   Dim rs As ADODB.Recordset
   Dim accessionno As String

   Set conn = New ADODB.Connection
   Set rs = New ADODB.Recordset

   conn.ConnectionString = "Driver={SQL Server};Server=***;Database=***;Uid=****;Pwd=***;"
   conn.Open

   Set cmd = New ADODB.Command
   cmd.ActiveConnection = conn
   cmd.CommandType = adCmdStoredProc
   cmd.CommandText = "dbo.NameofStoredProcedure"

  cmd.Parameters.Append cmd.CreateParameter("@worksheetno", adVarChar,
  adParamInput, 10, Forms!RepeatForm!txtEnterWrkSheetno)
  cmd.Parameters.Append cmd.CreateParameter("@name", adVarChar,
  adParamInput, 10, Forms!RepeatForm!txtEnterName)
  cmd.Parameters.Append cmd.CreateParameter("@year", adVarChar,
  adParamInput, 4, Forms!RepeatForm!txtEnterYear)

  With rs
     .ActiveConnection = conn
     .CursorType = adOpenForwardOnly
     .CursorLocation = adUseServer
  End With

  Set rs = cmd.Execute()
  DoCmd.OpenForm "frmRepeats", acViewNormal
  rs.Open cmd

  rs.Close
  conn.Close

  Set rs = Nothing
  Set cmd = Nothing
  Set conn = Nothing
End Sub

SQL
CREATE PROCEDURE [dbo].[NameofStoredProcedure] @worksheetno varchar(10),
@name varchar(10), @year varchar(4)
AS
BEGIN
CREATE TABLE #Temp (accessionno varchar (100),
No varchar (100),
worksheetno varchar (10),
name varchar(100),
location varchar (10),
Result varchar (100),
year varchar (4))

INSERT INTO #Temp
SELECT DISTINCT
    a.accessionno,
    e.name + substring(a.Year, 3,2) + '-' + convert(varchar(10),
    c.SampleTestNum) AS No,
    a.worksheetno,
    b.name,
    c.platetext AS Location,
    d.finalcomment AS Result,
    a.Year
FROM
    tb_sample a (nolock), tb_patient b (nolock), tb_plate c (nolock),
    tb_finalresult d (nolock), tb_testcode e (nolock)
WHERE
    a.sample_id = b.sample_id
    and a.sample_id = c.sample_id
    and a.sample_id = d.sample_id
    and a.test_id = e.test_id
    and finalcomment like '%1061%'
    and worksheetno = @worksheetno
    and e.name = @name
    and a.year = @year
ORDER BY No
END
select distinct * from #Temp
drop table #Temp
GO


text:
Q: Why do we need to use BeginInvokeOnMainThread in on app loading to show DisplayAlert This code is not showing DisplayAlert
public MainPage()
{
    InitializeComponent();
    DisplayAlert("Hey", "Welcome", "OK");
}

but when I use Device.BeginInvokeOnMainThread alert is getting displayed
public MainPage()
{
    InitializeComponent();
    Device.BeginInvokeOnMainThread(() => {
                DisplayAlert("Hey ", "Welcome", "OK");
            });
}

Is this happens with DisplayAlert only or with other controls as well. Can anybody tell me why does this happens?

A: The reason for that is quite simple when a constructor is called it is on a different thread than the UIThread, Now the UI thread is where all the changes on the UI actually occur.
Note
An application can have n number of different threads but only one UIThread
So when you do this:
public MainPage()
{
   InitializeComponent();
   DisplayAlert("Hey", "Welcome", "OK");
}

What happens is it runs on a constructor's thread(not UIThread) and hence it is executed but never shown on the UI, On the contrary when you do this:
public MainPage()
{
   InitializeComponent();
   Device.BeginInvokeOnMainThread(() => {
            DisplayAlert("Hey ", "Welcome", "OK");
        });
}

The BeginInvokeOnMainThread method forces your display alert method to run on UI thread causing it to be visible on the UIThread.
I hope it makes sense to you,
Feel free to revert if you did not understand anything.
Good luck

A: UI operations must occur on the main UI thread.  BeginInvokeOnMainThread forces an operation on a background thread to occur on the UI thread


text:
Q: Integrating powers of polynomials Is there any way to symbolically integrate, say,
$$\int (2x^2+7)^{10}dx$$
other than to expand the polynomial and apply the power rule? I suspect not, but wanted to make sure there wasn't some integration technique I was forgetting.

A: When you have a power of a binomial, The Binomial Theorem works fine. It won't be fast, in the final calculation though.
Consider:
$$(a+b)^n = \sum_{k = 0}^n \binom{n}{k} a^k b^{n-k}$$
In your case:
$$\int (2x^2 + 7)^{10}\ \text{d}x = \sum_{k = 0}^{10} \binom{10}{k} \int (2x^2)^k 7^{10-k}\ \text{d}x = \sum_{k = 0}^{10} \binom{10}{k} 7^{10-k} \int x^{2k}\ \text{d}x$$
The integral is now trivial, giving you
$$\int (2x^2 + 7)^{10}\ \text{d}x = \sum_{k = 0}^{10} \binom{10}{k} 7^{10-k} \dfrac{2x^{2k+1}}{2k+1}+C$$