text:
Q: Basics in for loop in actionscript 3 in flex Good Morning stackoverflow...
I'm having a problem.... this is my sample code
var i:Number = new Number();

trace("showarray length" + showArray.length);

for(i=0;i<showArray.length;i++){

    trace("equal daw" + showArray.getItemAt(i).id + "==" + num);

    if(showArray.getItemAt(i).id == num){
        showArray.removeItemAt(i);

    }
}
trace('alerts');

myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop
this is a sample output
given that the length of showArray is 2 and num = 0
showarray length2
equal daw0==0
alerts
please help me

A: If you want to remove items while iterating over array, iterate in reverse order. This way element removal does not affect cycle condition:
for (var i:int = showArray.length - 1; i >= 0; i--) {
    if (someCondition) {
        showArray.removeItemAt(i);
    }
}

Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step.

A: An even better way might be to use the filter method of the Array class.
array = array.filter(function (e:*, i:int, a:Array):Boolean {
        return e.id != num;
    });

A: When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.

A: That's because you are removing items at the time you are iterating throught them.
array = [1, 2]
         ^         // pointer in first iteration

eliminate 1
array = [2]
         ^         // the pointer remains in the same location

//ups! out of the loop. all items were visited.

You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards.
PS: Sorry for my poor English.

A: After showArray.removeItemAt(i);, add i--;
Because you removed the item at index i from the array, the item that was at i + 1 got moved to i. By subtracting one, you ensure that the moved item doesn't get skipped.
alxx's answer is also a good solution.


text:
Q: Storing hierarchical data in Google App Engine Datastore? Can someone illustrate how I can store and easily query hierarchical data in google app engine datastore?

A: Well, you should try to keep your data as linear as possible. If you need to quickly query a tree structure of data, you would either have to store it pickled in the database (or JSON-encoded if you prefer) if that is possible for your data, or you would have to generate tree indices that can be used to quickly query a piece of a tree structure. I'm not sure how Google App Engine would perform when updating those indices, however.
When it comes to Google App Engine, your main concern should be to reduce the number of queries you need to make, and that your queries return as little rows as possible. Operations are expensive, but storage is not, so redundancy should not be seen as a bad thing.
Here are some thoughts on the subject I found by googling (although for MySQL, but you can get the general idea from it): Managing Hierarchical Data in MySQL
Ah and here's a discussion for Google App Engine: Modeling Hierarchical Data

A: The best option depends on your requirements. Here's a few solutions (I'm assuming you're using Python, since you didn't specify):

*

*If you need to do transactional updates on an entire tree, and you're not going to have more than about 1QPS of sustained updates to any one tree, you can use the built in support for heirarchial storage. When creating an entity, you can pass the "parent" attribute to specify a parent entity or key, and when querying, you can use the .ancestor() method (or 'ANCESTOR IS' in GQL to retrieve all descendants of a given entity.

*If you don't need transactional updates, you can replicate the functionality of entity groups without the contention issues (and transaction safety): Add a db.ListProperty(db.Key) to your model called 'ancestors', and populate it with the list of ancestors of the object you're inserting. Then you can easily retrieve everything that's descended from a given ancestor with MyModel.all().filter('ancestors =', parent_key).

*If you don't need transactions, and you only care about retrieving the direct children of an entity (not all descendants), use the approach outlined above, but instead of a ListProperty just use a ReferenceProperty to the parent entity. This is known as an Adjacency List.

There are other approaches available, but those three should cover the most common cases.

A: One way is to use the Model's parent attribute. You can then make use of query.ancestor() and model.parent() functions.
I guess it depends on what kind of operations you want to do on this data which would determine how best to represent it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Another MoebiusMu question When I evaluate the Mertens function to infinity:
NSum[MoebiusMu[k], {k, 1, \[Infinity]}]

I get -1, but I expected to get -2.
I wanted to modify the function thus:
Unprotect[MoebiusMu];
MoebiusMu[1] := -1
Protect[MoebiusMu];

in order to get -2.  But that gives me -3.
So, why does NSum return -1.?

A: In short NSum cannot handle this sort of sequence.  Indeed, strictly the series is not convergent, and some notion of summability/regularization needs to be chosen.
Given the nature of MoebiusMu, "Dirichlet" seems appropriate:
Sum[MoebiusMu[k], {k, 1, \[Infinity]}, Regularization -> "Dirichlet"]
  (* -2 *)

Here's how one can see NSum is not working reliably.
From the NSum reference page:

You should realize that with sufficiently pathological summands, the algorithms used by NSum can give wrong answers. In most cases, you can test the answer by looking at its sensitivity to changes in the setting of options for NSum.

The default for NSumTerms is 15.  Here's what happens if we increase that:
Quiet@NSum[MoebiusMu[k], {k, 1, \[Infinity]}, NSumTerms -> #] & /@  Range[15, 30]

(* {-1., -1., -1., ComplexInfinity, ComplexInfinity, -4., -4.,
    ComplexInfinity, ComplexInfinity, -1., -1., -1.5, ComplexInfinity,
    0., 0., ComplexInfinity} *)

You get all sorts of answers.  Quiet is suppressing the warning

NSum::nsumz: Some terms are zero. The algorithms are not very applicable. >>

One can see which terms are being tested this way:
ListPlot[Reap[NSum[MoebiusMu[k], {k, 1, Infinity}, EvaluationMonitor :> Sow[k]]][[2, 1]]]

The NSum reference page
suggests this is typical of the sequence extrapolation method.  MoebiusMu is not well-suited for extrapolation from these points.


text:
Q: Promblem finding empty elements in a comma seperated data import java.util.ArrayList;
import java.util.StringTokenizer;

public class test {

public static void main(String args[]) {

    ArrayList<String> data = new ArrayList<String>();
    String s = "a,b,c,d,e,f,g";
    StringTokenizer st  = new StringTokenizer(s,",");

    while(st.hasMoreTokens()){
        data.add(st.nextToken());
    }
    System.out.println(data);

}

}

Problem in finding empty elements in a CSV data
the above code works well when the data is complete. If some data is missing it fails to detect the empty data.
ex:
Complete DATA : a,b,c,d,e,f,g
if a,d,e,g are removed
New DATA : ,b,c,,,f,
4 data missing!!
I need a way to put this data into ArrayList with null or "" values for empty data

A: I'm sure there are more elegant solutions, but a simple one would be to use split() function:
public static void main(String args[]) {

    ArrayList<String> data = new ArrayList<String>();
    String s = ",b,c,,,f,";

    //create an array of strings, using "," as a delimiter
    //if there is no letter between commas, an empty string will be
    //placed in strings[] instead
    String[] strings = s.split(",", -1);

    for (String ss : strings) {
        data.add(ss);
    }

    System.out.println(data);
}

A: You can use Guava Splitter to do that:
import com.google.common.base.Splitter;

public class Example
{
    private static final Splitter SPLITTER = Splitter.on(",").trimResults();

    public List<String> split(String singleLine) {
        return SPLITTER.split(singleLine);
    }
}


text:
Q: Using the google-custom-search for educational purpose Is there any access to the "google-custom-search" for students?
It is for a thesis. I want to implement/use the "normalized google distance" for my dataset. Unfortunately, my university has no general agreement with google.
PS. yes I know I could simply parse the web-page. But it seems to be a bit lame if there is an api for that.

A: Google discontinued the only paid option of the Custom Search Engine (CSE), so now your only option is 'free' -- in return for seeing a few content-based ads in your custom search results.
The 'pro' option now is the json/atom Search API, also free up to 100 queries per day.
I highly recommend that "anyone who ever uses a search engine", check them both out.  It takes minutes to create a custom search - and after that there are countless optional ways to customize or integrate with other (free) tools like Analytics or Sheets/Slides/Forms/etc.  If your CSE gets popular enough, they'll start paying you.
Google has a lot of 'products' that many people aren't aware of (most with free options) that.
Side note, since you're a class - Microsoft has some pretty sweet deals for anyone student/teacher with an email address on a school domain ($1000's in free software.)


text:
Q: Sum selected rows in datatable only? I have a datatable which has an amount column & a status column. I want to sum only those rows who have status '1'. How to do this? I am summing the column via datatable Compute method.

A: dataTable.Compute("sum(amount)", "status = 1")


text:
Q: Movable jquery box should not be moved out of the page I'm creating a web application where I need to do some design tweaks. Here is the sample feature code: http://jsfiddle.net/rkumarnirmal/FSDPH/
The black movable box shown there should not be moved out of the page(not even a bit), but if you check there, You can move the box and place it somewhat out of the page. How can I control it?
One more thing, I'm going to implement jPicker tool http://www.digitalmagicpro.com/jPicker/ in that box. If we click the color box, the jPicker tool will be popped out and then if the box is moved the jPicker tool must have to arranged itself according to the page.
I know asking question like this is not fair, but I have no chance :( Could anyone guide me?
Thanks!

A: You can use the containment property on draggable to keep the draggable element inside one of its parents.
For example:
$("#box_bg").draggable({scroll: false, cancel: "div#box", containment: 'document'});

A: Doing the whole code is not possible now. I'm giving you the logic. You can do it easily.
You have to track the overlay's drag event. Then in the event handler you have to check the left and top position of the overlay. If it goes beyond your limit then set left/top to 0 (or some offset).
On the other side if it goes beyond the extreme right (or bottom) you have to set the window's width (or height) minus the overlay's width (or height) accordingly.
same goes for the Color Picker. But instead of drag event you have to perform repositioning when the color picker is displayed.


text:
Q: Help understanding boost::bind placeholder arguments I was reading a StackOverFlow post regarding sorting a vector of pairs by the second element of the pair. The most obvious answer was to create a predicate, but one answer that used boost caught my eye.
std::sort(a.begin(), a.end(),
  boost::bind(&std::pair<int, int>::second, _1) <
  boost::bind(&std::pair<int, int>::second, _2));

I've been trying to figure out how boost::bind works, or at least just how to use it, but I can't figure out what the purpose of the placeholder arguments _1 and _2 are, and the boost documentation doesn't sink in at all.
Could anyone explain this specific usage of boost::bind?
P.S. Original question: How do I sort a vector of pairs based on the second element of the pair?

A: This expression:
boost::bind(&std::pair<int, int>::second, _1) <
boost::bind(&std::pair<int, int>::second, _2)

namely, the use of the < operator actually defines a functor between two other functors, both of which defined by bind.
The functor expected by sort needs to have an operator() which looks like this:
bool operator()(const T& arg1, const T& arg2);

when you're creating a functor using boost's < then the name holders _1 and _2 correspond to arg1 and arg2 of the functor you're creating.
The bind call create a functor that calls ::second of arg1 and arg2
With any luck, the introduction of lambdas in C++0x will make expressions like this obsolete.

A: std::sort requires a binary predicate to compare two items from the range. The placeholders show where the first and the second argument are going to be used.
boost::bind makes it so that the entire expression reads as _1.second < _2.second (except since the . operator is not overloadable, such expressiveness cannot be achieved).
Both bind calls, in this case, create a function object that accepts a pair<int, int> and returns the value of second. operator< in turn is overloaded to return another binary functor that compares the results of the previous functors. And that gets used by std::sort.


text:
Q: JS: Array print the values that repeat I need to print the duplicates from an array.
For example, given the following array and index, the function will print 6,23,33,100.
var array = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100];

Apparently we need to do it using two 'while loops'.
Im looking for a solution, but more importantly an explanation.
Links are very much appreciated.
Thanks!

A: The most elegant and efficient solution is to use a while loop which iterates the array only once, so, we have O(N) complexity.
For this, we need to declare an hash which keeps the number of occurencies for each array's item. If we found a duplicate one then we store it in duplicates array.

var arr = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100], i = 0, hash = {}, duplicates = [];
while(i < arr.length){
  hash[arr[i]] = hash[arr[i]] ? hash[arr[i]] += 1 : 1;
  if (hash[arr[i]] === 2)
    duplicates.push(arr[i])
  i++;
}

console.log(duplicates)

A: You could use the filter() and indexOf() methods.

var array = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100];
console.log(array.filter((a,b,c) => c.indexOf(a) !== b));

a -> is the value being passed in the arrow function.
b -> is the index being passed in.
c -> is the whole array being passed in.
This line is filtering the array based on, if the original array has a value (argument a) whose index does not match the given index passed in through the arrow function (argument b).

A: A good sample and explanation can be found here... W3Resource
Futhermore to assist in understanding the two major components of the code the Object...
Working with objects - Javascipt
and Arrays...Javascipt Arrays

A: For the shortest approach, you could take a closure
(s =>                           )(       )

with a Set
(s =>                           )(new Set)

and a check. If a value is already seen, then take this value
(s => v => s.has(v)             )(new Set)

or add the value to the set and return false, because a not seen value should not in the result set.
(s => v =>             !s.add(v))(new Set)

var array = [3, 6, 67, 6, 23, 11, 100, 8, 93, 0, 17, 24, 7, 1, 33, 45, 28, 33, 23, 12, 99, 100],
    duplicates = array.filter((s => v => s.has(v) || !s.add(v))(new Set));

console.log(duplicates);


text:
Q: Fancybox 2 scrollbar disapears and site shifts to the right I have a small issue with fancybox 2. I'm now to the coding stuff so sorry if I am going to ask stupid questions.
I got the fancybox working on the testsite but when I click on an image the box opens and the whole page in the background shifts to the right and the scrollbar disappears. I don't want this behaviour. The scrollbar should be there.
It is on this site: http://elgaucho.lu/restaurant.php
Can you help me please?
Thanks in advance
Andy

A: As far as I can tell, you modified the original fancybox css file.
You changed the line 167 from this
.fancybox-lock {
    overflow: hidden;
}

into this
.fancybox-lock {
    overflow: hidden;
    margin-right:0 !important;
}

... and the line 187 from this
.fancybox-lock .fancybox-overlay {
    overflow: auto;
    overflow-y: scroll;
}

into this
.fancybox-lock .fancybox-overlay {
    overflow: hidden;
    overflow-y: hidden;
}

... so no wonders (bear in mind that the js file also changes some css properties dynamically so you may not have full control just changing the css file)
Generally speaking you shouldn't mess with the original files unless you are pretty sure what you are doing, otherwise you will have unexpected results

A: I've solved this problem by adding the following code in the main CSS file:
body { margin: 0 !important; }
.fancybox-lock,
.fancybox-overlay { overflow: visible !important; }

A: I had the same issue... scrollbar disappeared and page shifted to the right. Annoying, but this code indeed works. Just add it to any of your fancybox css file (or any included css file for that matter).
.fancybox-lock, .fancybox-overlay { overflow: visible !important;}

A: Force the page to always scroll with:
body {overflow-y: auto !important;}

A: I had this problem and my solution was easier than I expected it to be. I simply went into the html  and noticed I'd had two body's
In the code (near the bottom) there is the following:
    body {
        max-width: 700px;
        margin: 0 auto;
    }

I deleted that and my website now went back to being centred.

A: added:
.fancybox-lock, .fancybox-overlay { overflow: visible !important;}
body {overflow: visible !important;}
removed:
.fancybox-lock body {
    overflow: hidden !important;}
fine


text:
Q: Run DTEXEC from SSMS to run SSIS Catalog Package I would like to execute SSIS package using Catalog in a stored procedure using DTEXEC:

DECLARE @cmd varchar(8000)
DECLARE @params varchar(4000)
SELECT @params = '/SET
\Package.Variables[User::VarBigInt].Properties[Value];"' +
CONVERT(char(10), @VarBigInt) + '" '     SELECT @params = @params +
'/SET \Package.Variables[User::VarDate].Properties[Value];"' +
CONVERT(NVARCHAR(20), @VarDate,101) + ' " '
SELECT @params = @params + '/SET
\Package.Variables[User::VarDestination].Properties[Value];"' +
@VarDestination+ '" '
SELECT @params = @params + '/SET
\Package.Variables[User::VarBoolean].Properties[Value];"' +
CONVERT(CHAR(1), @VarBoolean) + '" '      SELECT @params = @params +
'/SET \Package.Variables[User::VarString].Properties[Value];"' +
@VarString+ '" '            SELECT @params = @params + '/SET
\Package.Variables[User::VarList].Properties[Value];"' + @VarList+ '"
'
SELECT @cmd = 'dtexec ' +N'/ISSERVER ""\SSISDB\test\test'+
@PackageName +'" /SERVER ""'+ @DestServerName +'"" /ENVREFERENCE 1
' + @params + '"$ServerOption::SYNCHRONIZED(Boolean)";True'

This is failing at

SELECT @params = @params + '/SET
\Package.Variables[User::VarDate].Properties[Value]";' +
CONVERT(NVARCHAR(20), @VarDate,101) + '''"'

upon running the stored procedure to deploy this to catalog:
Option " /SET \Package.Variables[User::VarDate].Properties[Value];01/15/2019" is not valid.
VarDate is a datetime variable in the SSIS package.

A: You are missing some " around both sets of SET
SELECT @params = @params + '/SET "\Package.Variables[User::VarDate].Properties[Value]";"' + CONVERT(NVARCHAR(20), @VarDate,101) + '"'


text:
Q: AWS Loadbalancer is not accessible I have a solution (AnzoGraph DB) deployed on my AWS Kubernetes Cluster (EC2 Instance), and was working totally fine.
Suddenly this solution stopped and i could not access it via the DNS anymore.
I tested the solution deployed on my cluster using kubectl port-forward command and they are working fine (the pods and services), thus i assume the problem is with AWS Loadbalancer.
To access the application we need to go through this path:
Request -> DNS -> AWS Load Balancer -> Services -> Pods.
The LoadBalancer is (classic) internal, so it's only accessible for me or the company using VPN.
Every time when I try to access the DNS , I got no response.
Any idea how i can fix it ? or where is the exact issue ? how can I troubleshoot this issue and follow the traffic on AWS ?
Thanks a lot for the help!

A: sorry I missed your post earlier.
lets start with a few questions...
You say you use k8s on AWS EC2, do you actually use EKS, or do you run a different k8s stack?
Also ... you mentioned that you access the LB from your (DB) client/ your software by DNS resolving the LB and then access AnzoGraph DB.
I want to make sure that the solution is actually DNS resolving the LB via DNS every time. if you have a long running service, and AWS changes the IP address of the LB, and your SW possibly had cached the IP, you would not be able to connect to the LB.

*

*on the system you run your Software accessing AnzoGraph DB ... (I assume CentOS (7) )

*make sure you have dig installed (yum install bind-utils)

*dig {{ your DNS name of your LB }}
is that actually the IP address your SW is accessing?

*has the IP address of the client changed? make sure the LB SG allows access
(https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-groups.html)

I assume you access the AnzoGraph DB frontend POD via 443?
as you write

"I tested the solution deployed on my cluster using kubectl port-forward command and they are working fine (the pods and services)"

we probably do not have to look for pod logs.
(if that was not the case, the LB would obviously block traffic as well.)
So I agree, that the most likely issue is (bad) DNS caching or SG due to different SRC IP being rejected by the classic LB SG.
also for completeness .. please tell us more about your env.

*

*AnzoGraph DB image

*EKS/k8s version

*helm chart / AnzoGraph operator used.

Best - Frank


text:
Q: How do I overcome the XHR FF POST size limit? My XHR POST REQUEST is cut off. When I try to reload my page information is missing. Firebugs sends following message:

Firebug request size limit has been reached by Firebug.

My question is: What are my options?

*

*Would it work if I declare the content.length in the header?

*I added a line to my apache config file and restarted it: LimitRequestBody 0

*I increased the size of transfer files in mysql config file

Or it is a browser issue?
The only solution I could think of was to cut the data in pieces and transmit the array one by one but I don't like this idea. The content length is 91691 according to firebug.
Any suggestions?

A: You just need to modify Firebug settings. In browser's address bar go to about:config, then look for option extensions.firebug.netDisplayedPostBodyLimit.
You should increase its value in order to see non truncated requests. Set it to 65535 for example.
Here you can find many other Firebug options you may want to change: http://getfirebug.com/wiki/index.php/Firebug_Preferences


text:
Q: Problem 6.6-12 of Evans' PDE Can please somebody tell me, how solve this problem ?

We say that the uniformly elliptic operator
  $$Lu\ =\ -\sum_{i,j=1}^na^{ij}u_{x_ix_j}\ +\ \sum_{i=1}^nb^iu_{x_i}\ +\ cu$$
  satisfies the weak maximum principle if for all $u\in C^2(U)\cap C(\bar{U})$
  $$\left\{\begin{array}{rl}
Lu \leq 0 & \mbox{in } U\\
u \leq 0  & \mbox{on} \partial U
\end{array}\right.$$
  implies that $u\leq 0$ in $U$.
Suppose that there exists a function $v\in C^2(U)\cap C(\bar{U})$ such that $Lv \geq 0$ in $U$ and $v > 0$ on $\bar{U}$. Show the $L$ satisfies the weak maximum principle.
(Hint: Find an elliptic operator $M$ with no zeroth-order term such that $w := u/v$ satisfies $Mw \leq 0$ in the region $\{u > 0\}$. To do this, first compute $(v^2w_{x_i})_{x_j}$.)

Thanks so much in advance.

A: First, assume that you found the operator $M$ in the hint. If $w$ has a local maximum, all first derivatives are zero and all second derivatives are negative, so $Mw$ is positive, a contradiction. Thus, all maxima are on the boundary, so $w\leq 0$. (Edit: I implicitly assumed that the mixed partial terms were 0, but the result still holds because the second derivative terms can be diagonalized)
But $v$ is positive, so $u=vw$ must also be nonnegative.
This assumes that you completed the hint. Would you like help with that part?

A: $Mw=-\sum_{ij=1}^{n}a^{ij}w_{ij}+\sum_{i=1}^{n}(b_i -\frac{2}{w}\sum_{k=1}^{n}a^{ik}v_k)w_i$
$Mw=\frac{Lu}{v}-\frac{uLv}{v^2}$
Use this we can solve the problem, I find in Han Qing's book.


text:
Q: Get objects from a list that have matching values for specific attributes and group them: Java 11 I have a class called Product. From this class I have created 8 objects, and I have added those objects to a list called productList. Each object represents a product that has a name, color and size attribute, and a storage bin that it belongs to. Each product also has a quantityCounted value. I need to go through this list, get all products that have matching attribute values for the following:
productName,
attributeSetValue,
storageBin
I will need to add each matching set of objects to a group, and then add these groups to a list. (reason: I  will need to get each group in the list and calculate the most common quantityCounted figure for that group which will then be the final quantity for that product item.)
For example, from the example code below, I would need:

*

*p1, p2, p5 and p6 to all be in one group because all 3 of the above mentioned attribute values match.

*p3 would be in it's own group because the value of storageBin is different.

*p4 and p7 would form a group.

*p8 would be in it's own group because the productName value does not match any of the others.

What is the best way to go about this please? Fairly new to Java - any advice would be appreciated. Thanks in advance.
// Class Declaration
public class Product
{
    // Instance Variables
    public String id;
    public String productName;
    public String attributeSetValue;
    public String storageBin;
    public String countedBy;
    public int quantityCounted;

    // Constructor Declaration of Class here...

    // Creating objects using new operator:
    Product p1 = new Product("1", "gumboots", "Blue_7", "Bin 1", "John", 12);
    Product p2 = new Product("2", "gumboots", "Blue_7", "Bin 1", "Sally", 13);
    Product p3 = new Product("3", "gumboots", "Red_8", "Bin 2", "John", 15);
    Product p4 = new Product("4", "gumboots", "Red_8", "Bin 1", "Sally", 15);
    Product p5 = new Product("5", "gumboots", "Blue_7", "Bin 1", "Sue", 13);
    Product p6 = new Product("6", "gumboots", "Blue_7", "Bin 1", "Bob", 13);
    Product p7 = new Product("7", "gumboots", "Red_8", "Bin 1", "Sue", 16);
    Product p8 = new Product("8", "sandals", "Red_10", "Bin 1", "Bob", 10);

    //Add product objects to list:
    List<Product> productList = Arrays.asList(p1,p2,p3,p4,p5,p6,p7,p8);

}

A: You can use the streams API to group the Product objects according to your criteria.
Note: Explanations after the code.
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Product {
    private String id;
    private String productName;
    private String attributeSetValue;
    private String storageBin;
    private String countedBy;
    private int quantityCounted;

    public Product(String id,
                   String productName,
                   String attributeSetValue,
                   String storageBin,
                   String countedBy,
                   int quantityCounted) {
        this.id = id;
        this.productName = productName;
        this.attributeSetValue = attributeSetValue;
        this.storageBin = storageBin;
        this.countedBy = countedBy;
        this.quantityCounted = quantityCounted;
    }

    private static void display(List<Product> list) {
        System.out.println();
        if (list != null) {
            if (list.size() > 0) {
                list.forEach(System.out::println);
            }
            else {
                System.out.println("Empty list.");
            }
        }
        else {
            System.out.println("Null list.");
        }
    }

    public String getId() {
        return id;
    }

    public String getProductName() {
        return productName;
    }

    public String getAttributeSetValue() {
        return attributeSetValue;
    }

    public String getStorageBin() {
        return storageBin;
    }

    public String getCountedBy() {
        return countedBy;
    }

    public int getQuantityCounted() {
        return quantityCounted;
    }

    public String toString() {
        return String.format("%s %s %s %s %s %d",
                             id,
                             productName,
                             attributeSetValue,
                             storageBin,
                             countedBy,
                             quantityCounted);
    }

    public static void main(String[] args) {
        Product p1 = new Product("1", "gumboots", "Blue_7", "Bin 1", "John", 12);
        Product p2 = new Product("2", "gumboots", "Blue_7", "Bin 1", "Sally", 13);
        Product p3 = new Product("3", "gumboots", "Red_8", "Bin 2", "John", 15);
        Product p4 = new Product("4", "gumboots", "Red_8", "Bin 1", "Sally", 15);
        Product p5 = new Product("5", "gumboots", "Blue_7", "Bin 1", "Sue", 13);
        Product p6 = new Product("6", "gumboots", "Blue_7", "Bin 1", "Bob", 13);
        Product p7 = new Product("7", "gumboots", "Red_8", "Bin 1", "Sue", 16);
        Product p8 = new Product("8", "sandals", "Red_10", "Bin 1", "Bob", 10);

        //Add product objects to list:
        List<Product> productList = Arrays.asList(p1,p2,p3,p4,p5,p6,p7,p8);
        Map<String, List<Product>> map = productList.stream()
                                                    .collect(Collectors.groupingBy(p -> p.getProductName() + p.getAttributeSetValue() + p.getStorageBin()));
        map.values()
           .forEach(Product::display);
    }
}

The groupingBy method concatenates the productName, attributeSetValue and storageBin for each Product object in the list. Those Product objects that have identical concatenations are added to a List and that List serves as the value for a Map where the concatenation is the [map] key.
The above code also uses method references. I refer to this line:
map.values()
   .forEach(Product::display); // method reference

Running the above code produces the following output:

4 gumboots Red_8 Bin 1 Sally 15
7 gumboots Red_8 Bin 1 Sue 16

3 gumboots Red_8 Bin 2 John 15

8 sandals Red_10 Bin 1 Bob 10

1 gumboots Blue_7 Bin 1 John 12
2 gumboots Blue_7 Bin 1 Sally 13
5 gumboots Blue_7 Bin 1 Sue 13
6 gumboots Blue_7 Bin 1 Bob 13

The output shows that Product with ID = 4 and ID = 7 are in the same group. Similarly, Product with IDs 1, 2, 5 and 6 are in the same group while ID = 3 is in a group by itself as is Product with ID = 8.

A: Have you tried Java's streams API before? I think this may help you. You can filter each product using .filter() and reconstruct it back into a list or collection. For e.g:
List<Product> blue7 = productList.stream().filter(product -> product.attributeSetValue == "Blue_7").collect(Collectors.toList());

See this article for reference - https://www.baeldung.com/java-8-streams-introduction

A: Since the attributes are strings, you could simply concatenate them and use that as a classifier:
Map<String, List<Product>> result =
    productList.stream().collect(
            Collectors.groupingBy(p -> String.join(":", p.productName, p.attributeSetValue, p.storageBin)));

You could extract the joining part of the attribute values to a function to make it a bit more readable (but it is a matter of preference):
Function<Product,String> nameValueBin = p -> String.join(":", p.productName, p.attributeSetValue, p.storageBin);

Map<String,List<Product>> result2 = productList.stream()
                                               .collect(Collectors.groupingBy(nameValueBin));

with above approach you could easily add other functions if you need to group on other fields.
If not all attributes are of same type (for example if you need to group by productName(string), storageBin(string), quantityCounted(int), whatever (LocalDate...)) use a list instead of string concatenation:
productList.stream().collect(
            Collectors.groupingBy(p -> List.of(p.productName, p.attributeSetValue, p.storageBin)));


text:
Q: output text not displying the account lookup corresponding contact VF Page:
<apex:page standardController="case_obj__c" extensions="caseobj">
 <apex:form >
  <apex:inputField value="{!a.Account__c}"/>

   <apex:outputtext value="{!c.name}" label="dis"/>

   <apex:commandLink action="{!save}" value="ok"/>
 </apex:form>
</apex:page>

Class:
Public class caseobj{

 public case_obj__c a {get;set;}
 public  contact c {get;set;}

 public caseobj(apexPages.standardController con){
  this.a = (case_obj__c)con.getRecord();
}

 public void save(){
  id b =(id)a.Account__c;
  contact c=[select name from contact where accountID=:b];
  system.debug(c);
 }

}

if i select account in the lookup field it should automatically show the corresponding contact in the output text field.but it is not displaying help me out

A: You need to use rerender attribute in  to show the contacts when you click Save. Also as there can be more than one contact under each account, it is better to assign the contact query list to a list of contacts. Please find updated code below,
<apex:page standardController="case_obj__c" extensions="caseobj">
<apex:form >
  <apex:inputField value="{!a.Account__c}"/>

  <apex:outputpanel id="contacts">
   <apex:repeat value="{!contactList}" var="c">
    <apex:outputtext value="{!c.name}" label="dis"/>

   </apex:repeat>
  </apex:outputpanel>
   <apex:commandLink action="{!save}" rerender="contacts" value="ok"/>
 </apex:form>
</apex:page>

Controller code updated to show more than one contact
Public class caseobj{

 public case_obj__c a {get;set;}
 public  List<contact> contactList {get;set;}

 public caseobj(apexPages.standardController con){
  this.a = (case_obj__c)con.getRecord();
 }

 public void save(){
  id b =(id)a.Account__c;
  contactList =[select name from contact where accountID=:b];
  system.debug(contactList);
 }

}


text:
Q: 'Correct the classpath of your application' in a Springboot Configuration in IntelliJ I have such an application with an IntelliJ-Idea IDE that has a Springboot configuration that errors out and gives the following recommendation:
The following method did not exist:

org.springframework.context.ConfigurableApplicationContext.setApplicationStartup(Lorg/springframework/core/metrics/ApplicationStartup;)V

The method's class, org.springframework.context.ConfigurableApplicationContext, is available from the following locations:

jar:file:/C:/Users/tlmitch/.m2/repository/org/springframework/spring-context/5.2.8.RELEASE/spring-context-5.2.8.RELEASE.jar!/org/springframework/context/ConfigurableApplicationContext.class

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.context.ConfigurableApplicationContext

I'm relatively new to IntelliJ-Idea and Springboot.  If this were say Eclipse - I would probably just go to the Java Build Path and add the jar file that contains the class.
I'm less familiar with IntelliJ.  So far if something is missing, I've just been running 'npm install' and that usually takes care of it.
Any suggestions?
Thanks much

A: If you've added Spring dependencies in your pom.xml file, they might be conflicting with the Spring dependencies in the lib folder in your project directory. Deleting the lib folder will fix this. (just make sure your project does not depend on other libraries in the lib folder before deleting).

A: As error suggests:
Correct the classpath of your application so that it contains a single, compatible version of org.springframework.context.ConfigurableApplicationContext

you need to make sure your classpath contains only one such class. You can use Navigate | Class action to see if there are multiple versions of this class exists in project and exclude the duplicated library dependency in Maven pom.xml file.


text:
Q: Symfony 4: Returning only active records I would like to only get records where the active indicator is true:
class Question {
   /**
    * One Question has one Figure
    * @ORM\OneToOne(targetEntity="QuestionFigure", mappedBy="question")
    */
    private $figure;

    public function getFigure()
    {
     $criteria = Criteria::create()->where(Criteria::expr()->eq("active", true));
     return $this->figure->matching($criteria);
    }

When I do this, I get the error:
Attempted to call an undefined method named "matching" of class

I believe this is because the matching method can only be applied to an ArrayCollection which $this->figure is not. What would be a similar way of achieving this same result?
Edit based on answer provided by Ihor Kostrov:
getActive() is returning nothing. Testing this out, this works:
public function getFigure()
    {
         if (!empty($this->figure) && $this->figure->getId() === 1) {
            return $this->figure;
        }

        return null;
    }

But changing the id to 2 does not work ($this->figure->getId() === 2). I am thinking this is because of the one-to-one relationship doctrine only fetches one row?

A: Yes, you have OneToOne, so you cat try this
public function getFigure(): ?QuestionFigure
{
    if (!empty($this->figure) && $this->figure->getActive()) {
        return $this->figure;
    }

    return null;
}

A: No! You must not have logic in your entity!
To have all question with have QuestionFigure active you must configure a repository and you implement a method.


text:
Q: Seismic Unix display facilities I have compiled Seismic Unix source on a linux machine successfully, after many attempts. The OS is OpenSUSE Leap 15.4.
I am following the software's user manual to get to know the package.
The problem I have is with the plotting utilities. I am getting an error as below:
"
$ suplane | suxwigb &
[1] 7557
suplane: fputtr.c: segy output can't be tty
"
The command is supposed to plot an image in X-windows.


text:
Q: Iterate through 2 dimensional array I have a "connect four board" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use  "System.out.println", so I have to iterate through the rows.
I need a way to iterate this way [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] etc
If i use the normal procedure:
for (int i = 0; i<array.length; i++){
     for (int j = 0; j<array[i].length; j++){
        string += array[i][j];
     } System.out.println(string)

}

it doesnt work because it iterates this way [0,0] [0,1] [0,2] [0,3] etc
The normal procedure stays in x and increments y until the end of the column, but i need to say in y and increment x until the end of the row.

A:  //This is The easiest I can Imagine .
 // You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
    for(int columns=0;columns <array[rows].length;columns++){
        System.out.print(array[rows][columns] + "\t" );}
    System.out.println();}

A: Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };

    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

A: Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.
String string="";
for (int i = 0; i<array.length; i++){
    for (int j = 0; j<array[i].length; j++){
        string = string.concat(array[j][i]);
    }
}
System.out.println(string)

A: Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
     for (int i = 0; i<array.length; i++){

because all rows has same amount of columns you can use this condition  j < array[0].lengt in first for condition due to the fact you are iterating over a matrix

A: These functions should work.
// First, cache your array dimensions so you don't have to
//  access them during each iteration of your for loops.
int rowLength = array.length,       // array width (# of columns)
    colLength = array[0].length;    // array height (# of rows)

//     This is your function:
// Prints array elements row by row
var rowString = "";
for(int x = 0; x < rowLength; x++){     // x is the column's index
    for(int y = 0; y < colLength; y++){ // y is the row's index
        rowString += array[x][y];
    } System.out.println(rowString)
}

//      This is the one you want:
// Prints array elements column by column
var colString = "";
for(int y = 0; y < colLength; y++){      // y is the row's index
    for(int x = 0; x < rowLength; x++){  // x is the column's index
        colString += array[x][y];
    } System.out.println(colString)
}

In the first block, the inner loop iterates over each item in the row before moving to the next column.

In the second block (the one you want), the inner loop iterates over all the columns before moving to the next row.

tl;dr: Essentially, the for() loops in both functions are switched. That's it.

I hope this helps you to understand the logic behind iterating over 2-dimensional arrays.

Also, this works whether you have a string[,] or string[][]

A: Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.
  int longestRow = 0;
  for (int i = 0; i < array.length; i++) {
    if (array[i].length > longestRow) {
      longestRow = array[i].length;
    }
  }

  for (int j = 0; j < longestRow; j++) {
    for (int i = 0; i < array.length; i++) {
      if(array[i].length > j) {
        System.out.println(array[i][j]);
      }
    }
  }


text:
Q: Set up user's profile on a new Windows domain computer without user's password or reset Is it possible to set up a profile for a current user on a new computer on a Windows domain without knowing the user's password or resetting the password?

A: Not really, no. When we were doing our computer labs for students, we ended up preparing the Default Profile to be pretty close to what they actually needed. This is the preferred method of doing it for Windows, other methods are prone to wacky and subtle problems.


text:
Q: C# Enums with reserved keywords I'm opening old C# code from my work using Reflector and I found out that there was an enum in an SQL class which looked like this:
public enum Column
{
     bool,
     ...
}

The enum is populated with column types and it doesn't compile due it being a reserved keyword. Obviously someone was able to compile it at some point. How do I get it to compile?
Thanks!

A: You need to prefix with a character literal (@ symbol) in order to use keywords.
MSDN (Thanks @erikH)


text:
Q: Make CouchDB vhosts rule via PUT request I wish make working with public CouchDB database only via _rewrite
I add string to local.ini to vhosts:
*/mydb = /mydb/_design/doc/_rewrite

It's working good, all requests to http://localhost:5984/mydb redirect to _rewrite
But I can't make this vhosts rule via futon, or via curl. Futon return me error in jquery.couch.js.
I dont know how make this curl valid:
curl -H 'Content-Type: application/json' \
        -X PUT http://127.0.0.1:5984/_config/vhosts/*/mydb \
        -d '{"/mydb/_design/doc/_rewrite"}'

A: I do not think it's possible to change the configuration of couchDB via the http-interface, if that is what you want to do.


text:
Q: JS: regex, $ end of input not able to use console.log(/\d+?\d+?\d+?-\d+?\d+?\d+?-\d+?\d+?\d+?\d+?$/.test("555-555-55539"));

Answer --> true
I was looking for false, i am validating phone numbers. e.g. 555-555-5555 is a correct response([0-9])
I am a newbie to regex, can anyone explain what i am doing wrong here?

A: How about this.

console.log(/\d{3}-\d{3}-\d{4}$/.test("555-555-55539"));

A: You used wrong quantifiers in your regex. You made them lazy (+?), but it will still match all characters until the next character from regex is found. In case of your last quantifier (just before $) it will match all digits until the end of string is found. Hence it matches not only one digit but all of them. Same thing happens before each hyphen (555555555-5555-555555555 is valid for your regex).


text:
Q: Lotus Domino Datatable columns So I need to get some information from lotus domino database with java.
At first I need to create a session:
Session session = NotesFactory.createSession(host, user, password);

Then I need to get database:
Database db = session.getDatabase(serverName, dbName);

At the next step i need to get information. How this db looks comparable to simple relation db? I mean that in relation db I can make SQL query like "SELECT table FROM room WHERE table.hieght < 10" and for example how that query will look to get the same inforamtion from Lotus Domino DB?

A: Notes uses a document-oriented database called NSF (Notes Storage Facility) to manage semi-structured data like rich text and files. The data is stored as documents and views unlike relational databases.
To query NSFs you can use the Java API but they are hard to use especially if you are used to relational databases and standart Java collections. (i.e. most of the collection return types are not iterable so you have to use while to iterate through them :S, also expect a lot of weird exceptions). Here is an example:
Session session = NotesFactory.createSession(host, user, password);
View view = session.getDatabase(DATABASE).getView(VIEW);
ViewEntryCollection allEntries = view.getAllEntries();
ViewEntry entry = allEntries.getFirstEntry();
while (entry != null) {
    if (entry.isDocument()) {
        Document doc = entry.getDocument();
        String no = doc.getItemValueString("No");
    }
    entry = allEntries.getNextEntry();
}

Using the above code I retrieved a field labeled as "No" on a notes document which I got from a collection of entries which ultimately form a view named VIEW, and that view is under the database DATABASE.
There is also a scripting language called Lotus Domino Formula Language which is also used to query NSFs, you can learn about that here: Lotus Programming Guide and Formula Language.


text:
Q: Delete Lines containing a string after a Matching patterns? In my yaml file , i want to delete a block using Sed After matching a pattern .
Example:
Keypages:
- name: Key pages
LaunchPad:
- name: "\U0001F680Launch Pad"
- location: US
Microservices:
- name: 'Micro services '

In this example , when matching LaunchPad(for example) in the start of a line, i want to delete it ans its block ( for me the lines  starting with - and then stop when not finding -)
Result :
Keypages:
- name: Key pages
Microservices:
- name: 'Micro services '

thank you

A: Use this Perl one-liner:
perl -i.bak -ne 'print unless m{^LaunchPad} .. !m{^\s*-}' in_file

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak.
EXPR1 .. EXPR2 : this is true in between where expression EXPR1 is true and expression EXPR2 is true, inclusive.
!m{^\s*-} : not matching a pattern where the line starts with 0 or more whitespace characters followed by a dash.
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start

A: Using the python PyYaml library, you can use the following script as a filter that removes any section named LaunchPad:
import sys, yaml
data = yaml.safe_load(sys.stdin)
del data['LaunchPad']
yaml.dump(data, sys.stdout)

Simply run: python above-script < input.yml > output.yml
Given this input:
Keypages:
- name: Key pages
LaunchPad:
- name: "\U0001F680Launch Pad"
- location: US
Microservices:
- name: 'Micro services '

The above script produces this output:
Keypages:
- {name: Key pages}
Microservices:
- {name: 'Micro services '}

A: This might work for you (GNU sed):
sed -n '/^LaunchPad:/{:a;n;/^-/ba};p' file

Turn off implicit printing -n.
Match a line beginning LaunchPad: and then fetch following lines beginning with -.
Print all other lines.
Alternative:
sed '/LaunchPad:/{:a;N;/^-/Ms/\n//;ta;D}' file


text:
Q: Doble scrollbar en flutter Desarrollo una app en flutter, estoy creando un selector de ejercicios por dias.
Tengo un scrollbar exterior para los dias de la semana y unos interiores para la lista de ejercicios por dias.
Ls lista de dias es un ListView.builder y la lista de ejercicios por dias es un ReorderableListView dentro de un container, cado uno cuenta con su scrollcontroller.
El problema se genera cuando muevo el scrollbar interior, se visualiza el scrollbar exterior
 return Scrollbar(
  controller: scrollController,
  child: ListView.builder(
    controller: scrollController,
    primary: false,
    shrinkWrap: true,
    itemCount: diasSemana.length,
    itemBuilder: (context, index) {
      String dia = diasSemana[index];
      List<Ejercicio> rutinaDia = [];
      if (diasRutina.containsKey(dia)) {
        rutinaDia = diasRutina[dia];
      }

      return Card(
        child: Column(
          children: [
            if (rutinaDia.isNotEmpty)
              Container(
                height: MediaQuery.of(context).size.height / 3,
                child: Scrollbar(
                  controller: isScroll[index],
                  child: ReorderableListView(
                    scrollController: isScroll[index],
                    shrinkWrap: true,
                    onReorder: (int oldIndex, int newIndex) {
                      if (newIndex > oldIndex) {
                        newIndex -= 1;
                      }
                    },
                    children: [
                      for (final items in rutinaDia)
                        ListTile(
                          key: Key(items.id.toString()),
                          title: Text(
                            items.ejercicio,
                          ),
                        ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      );
    },
  ),
);


text:
Q: Passing google identity from chrome extension to my node.js app Overview: I am trying to understand the interactions between OAuth security in my server and in my chrome extension.  I think I have 90% of the answer working, but I'm missing a bit. I'd like to find the cleanest way to finish my implementation using existing tools, rather than reinventing any wheels.
Background: I have a node.js app that uses passport, passport-google-auth, and express-session to authenticate users. I save per-user information, keyed by the user's Google identity.  This works fine. My web pages can exchange data with the app, and the Google login screen pops up correctly in exactly the cases I'd expect.
I also have a chrome extension, which includes a browser_action popup that needs to write data to my node.js app and a content_script that needs to read data from my app.
My extension already uses chrome.identity.getAuthToken to get the user identity.
For testing, if I ignore security, I can pass this id to my node.js app, and access the info I need.
But, this is no good, of course. I want my node.js API to be locked down, only letting in clients that have the cookie generated for me by passport.
Side note: I imagine, instead, that I could do some song-and-dance wheel reinvention and pass the id securely to my server via https. But this seems completely wrong, right?
Question: I assume that my chrome extension really should be doing the OAuth2 dance directly with my node.js app. But, I don't know what piece I should be using, or how to cleanly play with chrome.identity.  I suspect that I'm just missing a small bit of wisdom, but I don't know what it is.
Side comment: Because cookies are shared between browser tabs, I can (clumsily) achieve what I want by simply connecting to my node.js app from another tab in the browser. So, I guess I just need to get the same behavior from my extension background page.

A: It looks like the easiest answer for me was to use the Stormpath APIs for this. It took some effort, but was reasonably straightforward.


text:
Q: warning: Swift error in module. Debug info from this module will be unavailable in the debugger I have no debugging values in my console for my swift + obj-c app, and I get a really unhelpful message that explains why the debugger isn't working: "warning: Swift error in module XXX.". XXX is the name of my module, not a 3rd party that I include.
My app has been around since before Swift. I used the bridging header to start using Swift, and I recently used the Xcode tool to migrate all the Swift 2 files to Swift 3. (but I still have obj-c legacy in there). I use cocoapods, which may be contributing to the problem.

(lldb) po self
warning: Swift error in module XXX.
Debug info from this module will be unavailable in the debugger.

I tried following the second answer to this post and a couple others
I have found that suggest the same thing: remove duplicate imports.
I tried removing duplicate imports from my swift project. In fact if I run find . -name "*swift" | xargs grep "import" I get no results. So I went to the extreme of removing all imports from all of my swift files (and commenting out code to get it to compile) just to see if I can get my debugger to come back.
So...

*

*Is there another solution to this problem?

*Is there a way to get a more detailed error message?

*Is it a problem to have duplicate headers in the my bridging header? For example, a lot of my obj-c files import UIKit, and I include a few of those files in the bridging header.

A: Just now I have encountered this problem.
This is my solution:
If you import 3rd repo by Cocoapods, and the repo is written by Objective-C, you need to import it by this way:
// System
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

// Directly add - Objective-C
#import "EaseUI.h"

// Cocoapods - Objcetive-C
@import MJRefresh;

You can refer to this issue in Github and this question.


text:
Q: How to compute this conditional probability in Bayesian Networks? I met a problem related to conditional probability from the article "Bayesian Networks without Tears"(download) on page 3.
According to the Figure 2, the author says
$$P(fo=yes|lo=true, hb=false)=0.5$$
While I don't know how to calculate it and obtain the correct result. I attached the screenshot of Figure 2. from the article. I tried it as following
$$P(fo|lo, \bar{hb})=\frac{P(lo, \bar{hb}|fo)\cdot P(fo)}{P(lo, \bar{hb})}=\frac{P(lo|fo)\cdot P(\bar{hb}|fo)\cdot P(fo)}{P(lo, \bar{hb})}$$
And $P(lo|fo)=0.6,\ P(fo)=0.15$, but how to know other 3 terms?
Thank you!

A: Other than the normal rules on conditional probability, the key thing specific to working with Bayesian networks (BN) is the rules regarding independence and conditional independence of the events represented by the nodes.
Without using the independence inferred by the particular network you can only get so far. There are lots of notes around if you google "Bayesian network". One example: Bayesian Networks.
I'll use a common method of solving it. Let's name the five events as:
\begin{eqnarray*}
F &=& \mbox{family out} \\
B &=& \mbox{bowel problem} \\
D &=& \mbox{dog out} \\
H &=& \mbox{hear bark} \\
L &=& \mbox{light on}
\end{eqnarray*}
(Note that there seems to be a typo in the diagram. It has $P(D \mid \lnot F, B) = 0.3$. This I think should be $P(D \mid \lnot F, \lnot B) = 0.3$.)
Every possible situation that can occur in our scenario can be represented by the intersection of these five events, each one either occurring or not occurring. E.g. all five events occurring is $(F,B,D,H,L)$. There are $2^5 = 32$ such combinations, and if we needed to, we could calculate all $32$ with the information provided. An example of how this is done follows. The Chain Rule of probability gives:
\begin{eqnarray*}
P(F,B,D,H,L) &=& P(L \mid F,B,D,H) \times P(H \mid F,B,D) \times P(D \mid F,B) \times P(B \mid F) \times P(F) \\
&=& P(L \mid F) \times P(H \mid D) \times P(D \mid F,B) \times P(B) \times P(F) \\
&=& 0.6 \times 0.7 \times 0.99 \times 0.01 \times 0.15 \\
&=& 0.0006237
\end{eqnarray*}
The second step there is really the key part and it uses the BN rules for independence, which are explained in the above link (too much to explain here).
To the calculation of $P(F \mid L, \lnot H)$, which is what we want,
$$P(F \mid L, \lnot H) = \dfrac{P(L, F, \lnot H)}{P(L, \lnot H)}$$
We work out the numerator and denominator separately:
$$P(L, F, \lnot H) = P(L, F, \lnot H, \lnot B,\lnot D) + P(L, F, \lnot H, \lnot B,D) + P(L, F, \lnot H, B,\lnot D) + P(L, F, \lnot H, B,D)$$
This is just applying $4$ combinations of the two missing events, $B$ and $D$.
Each of these $4$ terms can be calculated as above for $P(F,B,D,H,L)$. E.g.
\begin{eqnarray*}
P(L, F, \lnot H, \lnot B,\lnot D) &=& P(L \mid F,\lnot B,\lnot D,\lnot H) \times P(\lnot H \mid F,\lnot B,\lnot D) \times P(\lnot D \mid F,\lnot B) \times P(\lnot B \mid F) \times P(F) \\
&=& P(L \mid F) \times P(\lnot H \mid \lnot D) \times P(\lnot D \mid F,\lnot B) \times P(\lnot B) \times P(F) \\
&=& 0.6 \times 0.99 \times 0.1 \times 0.99 \times 0.15 \\
&=& 0.0088209
\end{eqnarray*}
Similarly we can get:
$$P(L, F, \lnot H, \lnot B,D) = 0.6 \times 0.3 \times 0.9 \times 0.99 \times 0.15 = 0.024057$$
$$P(L, F, \lnot H, B,\lnot D) = 0.6 \times 0.99 \times 0.01 \times 0.01 \times 0.15 = 0.00000891$$
$$P(L, F, \lnot H, B,D) = 0.6 \times 0.3 \times 0.99 \times 0.01 \times 0.15 = 0.0002673$$
So the numerator:
$$P(L, F, \lnot H) = 0.0088209 + 0.024057 + 0.00000891 + 0.0002673 = 0.03315411$$
By a similar method we can calculate the denominator, summing over $8$ terms, $4$ of which are those in the numerator. So now we do the other $4$:
\begin{eqnarray*}
P(L, \lnot F, \lnot H,B,D) &=& P(L \mid \lnot F) \times P(\lnot H \mid D) \times P(D \mid \lnot F,B) \times P(B) \times P(\lnot F) \\
&=& 0.05 \times 0.3 \times 0.97 \times 0.01 \times 0.85 \\
&=& 0.000123675
\end{eqnarray*}
\begin{eqnarray*}
P(L, \lnot F, \lnot H,B, \lnot D) &=& P(L \mid \lnot F) \times P(\lnot H \mid \lnot D) \times P(\lnot D \mid \lnot F,B) \times P(B) \times P(\lnot F) \\
&=& 0.05 \times 0.99 \times 0.03 \times 0.01 \times 0.85 \\
&=& 0.0000126225
\end{eqnarray*}
\begin{eqnarray*}
P(L, \lnot F, \lnot H,\lnot B,D) &=& P(L \mid \lnot F) \times P(\lnot H \mid D) \times P(D \mid \lnot F,\lnot B) \times P(\lnot B) \times P(\lnot F) \\
&=& 0.05 \times 0.3 \times 0.3 \times 0.99 \times 0.85 \\
&=& 0.00378675
\end{eqnarray*}
\begin{eqnarray*}
P(L, \lnot F, \lnot H,\lnot B,\lnot D) &=& P(L \mid \lnot F) \times P(\lnot H \mid \lnot D) \times P(\lnot D \mid \lnot F,\lnot B) \times P(\lnot B) \times P(\lnot F) \\
&=& 0.05 \times 0.99 \times 0.7 \times 0.99 \times 0.85 \\
&=& 0.029157975
\end{eqnarray*}
Summing these $4$ terms and the numerator, we get:
$$P(L, \lnot H) = 0.000123675 + 0.0000126225 + 0.00378675 + 0.029157975 + 0.03315411 = 0.0662351325$$
Finally, our answer:
$$P(F \vert L, \lnot H) = \dfrac{0.03315411}{0.0662351325} = 0.5005517275895839719200380$$


text:
Q: How to split elemts in a column into more columns in python I have this df:

I want to split the elements in each column into more columns. Therefore, my output should look like this:

I've been trying to use the following code:
dff = df.columna.str.split(expand=True)
dff

But the output is being generated looks like the first image. I'm not sure about how to approach this problem.

A: You have to specify the the columns' names and the delimiter as ',' :
dff[['column0','column1','column2','column3','column4','column5']] = dff['columna'].str.split(',',expand=True)
dff

A: Suppose, you have this dataframe:
df = pd.DataFrame({'columna': ['a,b,c', 'x,y', 'd,e,f', 'g,h,i,j,k,l,m']})

Then:
df = df['columna'].str.split(',', expand=True).rename(columns=lambda x: 'column{}'.format(x))
print(df)

Creates:
  column0 column1 column2 column3 column4 column5 column6
0       a       b       c    None    None    None    None
1       x       y    None    None    None    None    None
2       d       e       f    None    None    None    None
3       g       h       i       j       k       l       m


text:
Q: int main(int argc, char *argv[]) If I have this:
int main(int argc, char *argv[])

In the body, you can sometimes find programs using argv[1].
When do we use argv[1] over argv[0]? Is it only when we just want to read the second argument in the command line?

A: argv is an array of pointers, and each pointer in this array stores one argument from command line. So argv[0] is the first argument (that is the executable/program itself), argv[1] is the second argument, and so on!
The total number of arguments is determined by argc.

A: argv[0] is the execution path of the program, argv[1] is the first parameter to the program

A: Let's suppose your C++ executable file is:
/home/user/program (or C:\program.exe in Windows)
if you execute:
./home/user/program 1 2 (or C:\program.exe 1 2 in Windows)
argv[0] = /home/user/program (C:\program.exe)
argv[1] = 1
argv[2] = 2
That is because:

*

*argv[0] is the path of the executable file

*argv[1] is the 1st argument

Edit:
Now I see that argv[0] isn't necessarily the path of the executable file.
Read the following SO question: Is args[0] guaranteed to be the path of execution?

A: By convention, argv[0] is the current program's name (or path), and argv[1] through argv[argc - 1] are the command-line arguments that the user provides.
However, this doesn't have to be true -- programs can OS-specific functions to bypass this requirement, and this happens often enough that you should be aware of it. (I'm not sure if there's much you can do even if you're aware of it, though...)
Example:
gcc -O3 -o temp.o "My file.c"

would (should) produce the following arguments:
argc: 5
argv: ["gcc", "-O3", "-o", "temp.o", "My file.c"]

So saying argv[0] would refer to gcc, not to -O3.

A: Yes, that's mostly it, argv[1] is the second command line parameter.  The first command line parameter is the name of the program itself.
Alternatively, to avoid the semantic mess that this answer originally had, and the comments from others, it might make sense to call argv[0] the zeroth parameter, so that argv[1] would now be the "first" of the user supplied values.
In any event, this comes from the exec() family of functions, e.g. execl which has usage:
 int execl(const char *path, const char *arg0, ... /*, (char *)0 */);

In the (Unix) shell when you type in a command, if necessary the shell first resolves the command name (using $PATH) to find the real absolute path.  The (absolute or relative) path is supplied for path, and the command as originally typed-in is supplied as arg0, eventually becoming argv[0] in your program.
The remaining command line parameters then end up as argv[1], etc.

A: Short answer is yes, the array contains all the options passed into the program.

A: as argv[0] is filepath of the program itself.
Extra command line parameters are in further indexes, argv[1],argv[2]..
You can read more here :
http://www.site.uottawa.ca/~lucia/courses/2131-05/labs/Lab3/CommandLineArguments.html


text:
Q: btusb.ko file missing...Getting "Module not found error" I have the issue of not being able to use my USB Bluetooth adapter(It is a CSR 4.0) on my Ubuntu OS 20.04.4 LTS with GNOME version 3.36.8... Normally this USB stick works perfectly on my Windows but over here it doesnt... So I went online and did almost everything possible.. Note I have tried the following commands
sudo systemctl status bluetooth.service
systemctl restart Bluetooth
systemctl restart Bluetooth logs
sudo rfkill unblock Bluetooth
sudo rfkill unblock bluetooth
sudo systemctl restart bluetooth
sudo systemctl status bluetooth.service
sudo nano /etc/bluetooth/main.conf
sudo systemctl enable bluetooth.service
sudo systemctl start bluetooth.service
sudo systemctl status bluetooth.service
sudo vim /etc/bluetooth/main.conf
sudo systemctl status bluetooth.service
sudo apt install bluez
sudo systemctl enable bluetooth.service
sudo systemctl start bluetooth.service
sudo apt install bluez*

All of these I have tried until I came across a post which mentioned me not having the required driver installed for the USB Bluetooth Adapter... So I downloaded the driver specified but since the driver wasnt specifically for my adapter, trying to install it failed but ever since, I have had the issue of my Bluetooth toggle button not switching on even when my Bluetooth adapter is connected... I keep getting a " No Bluetooth Found Please Insert Dongle" message...
For better understanding on my issue.. I found this post  which helps explain my current issue... Apparently the btusb.ko file is missing because the driver I was trying to install earlier manipulated it...
So from the post I mentioned earlier one of the comment suggested I run the command
dpkg -S btusb, and locate btusb
This is the result of my own output:

Fortunately I located the missing package from the output which is highlighted
Now the question is what next
Please Help


text:
Q: How to generate a usable tensor product of two matrices in Python This thread successfully answers how to use numpy to calculate the tensor product of two matrices in Python.  However, I want the output to be in a proper matrix format so that further calculations can be performed on it without my manually editing it.
For instance,
I=matrix([[1,0],[0,1]])
print np.tensordot(I, I, axes=0)

Gives the output:
[[[[1 0]
   [0 1]]

  [[0 0]
   [0 0]]]

 [[[0 0]
   [0 0]]

  [[1 0]
   [0 1]]]]

I want it in the form:
[[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]

so that I can perform further operations on it within the program itself.
How do I do this?

A: The Kronecker tensor product can be calculated using numpy.kron.


text:
Q: How to remove a UIGestureRecognizer from a table cell I want to only allow swipe to delete on the first cell of a UITableView.
This bit is easy, however I want to display a UIAlert when the user tries to swipe any other cell. Again I have this working by using UIGestureRecognizer on each cell apart from cell 0.
The problem i'm having is once the top row has been deleted, I want the new top row to be allowed to be deleted.
It's as if I need to remove the UIGestureRecognizer's i've assigned to the cell, but I can't figure out how to.
Here is some of my code
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BetCell"];

    Bet *bet = [self.bets objectAtIndex:([self.bets count]-indexPath.row-1)];
    cell.BFNeedLabel.text = bet.BFNeeded;

    if (indexPath.row != 0) {
    UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeDetected:)];
    swipeRecognizer.direction = (UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight);
    [cell addGestureRecognizer:swipeRecognizer];
    }

    return cell;

}

-(void)swipeDetected:(UIGestureRecognizer *)sender
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"You can only delete starting from the top cell" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return YES;
    } else  {
        return NO;
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // If the very first row
    if ((editingStyle == UITableViewCellEditingStyleDelete) && (indexPath.row == 0)) {
        Bet *betObj = [self.bets objectAtIndex:([self.bets count]-indexPath.row-1)];
        //Delete from array
        [self.bets removeObjectAtIndex:([self.bets count]-indexPath.row-1)];
        //Delete the row
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

        //Attempt to remove gesture recognizer from cell 0
        UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeDetected:)];
        swipeRecognizer.direction = (UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight);
        [[tableView cellForRowAtIndexPath:0]removeGestureRecognizer:swipeRecognizer];
    }
}

A: No need to remove the gestureRecognizer. In your swipeDetected find out which cell you are, and only show the alert if indexPath.row != 0.
Your gesture recognizer will give you the location which can be translated to the table view coordinate space which turn can be used to get the indexPath for that cell.
In swipeDetected
CGPoint location = [sender locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
if ( indexPath.row != 0 {
// do alert
}

Update with sample code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Test"];
    if ( !cell ) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"] autorelease];
        UISwipeGestureRecognizer *gr = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleCellSwipe:)];
        gr.direction = UISwipeGestureRecognizerDirectionRight + UISwipeGestureRecognizerDirectionLeft;
        gr.delegate = self;
        [cell addGestureRecognizer:gr];
        [gr release];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d",indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.row == 0 )
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row == 0;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // do stuff
}

- (void)handleCellSwipe:(UIGestureRecognizer *)gestureRecognizer
{
    if ( gestureRecognizer.state == UIGestureRecognizerStateRecognized ) {
        CGPoint location = [gestureRecognizer locationInView:self.tableView];
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
        if ( indexPath.row != 0 ) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cell Swipe"
                                                            message:@"Cell in row not equal to 0 swiped"
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"OK", nil];
            [alert show];
            [alert release];
        }
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint location = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
    return indexPath.row != 0;
}

A: Why go through the trouble of a gesture recognizer when you can just show the alert through the caneditrowatindexpath. Only problem I can see is if you also use an edit button - then you'll get a lot of alerts at once.
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return YES;
    } else  {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:@"You can only delete starting from the top cell" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

If your set on using the gesture recognizer you'll just have to use reloadRowsAtIndexPaths:withRowAnimation: on index 0 after the delete this will reset the first cell. However your cellforrowatindexpath is set up wrong in your original post and will cause weird things to happen for this setup either way.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BetCell"];

    if ( !cell ) //this is needed in case a cell was never created in the first place
        cell = [[[BetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BetCell"] autorelease];

    Bet *bet = [self.bets objectAtIndex:([self.bets count]-indexPath.row-1)];
    cell.BFNeedLabel.text = bet.BFNeeded;

    if (indexPath.row != 0) {
        UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeDetected:)];
        swipeRecognizer.direction = (UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight);
        [cell addGestureRecognizer:swipeRecognizer];
    } else {//this is needed to reset a cell that is being reused (such as when you scroll off the page and return)
        for (UIGestureRecognizer *gesture in cell.gestureRecognizers) {
            [cell removeGestureRecognizer:gesture];
        }
    }

    return cell;

}


text:
Q: Read-only file system I am trying to remove write permission for others for this one
-rwxrwxrwx 1 root root 2950421 Jul  7 15:19 fcp_daemon

I am using this command and I am performing this action as a root user
chmod o-w fcp_daemon

but I am getting this error
chmod: changing permissions of `fcp_daemon': Read-only file system

A: Your filesystem is read-only, probably because it is damaged. This has nothing to do with the file permissions. Check the output of the dmesg command if there are any ATA error messages that may indicate a damaged hard disk.


text:
Q: Reading XML file prepared for JAR when testing application in Eclipse I'm writing a small app with the help of Eclipse while learning Swing GUIs in Java. I'm also taking my first baby steps in Ant build scripting and have come across a small problem.
I'm parsing an XML file to create objects to store in a List. I've assigned the Ant build script to include the XML file in the Jar package by adding this to the Jar command:
<zipfileset dir="${basedir}" includes="countries.xml" />

To read it I'm doing it through an InputStream:
InputStream is = getClass().getClassLoader().getResourceAsStream(COUNTRY_XML);

and then parse it with the parse()-method of a DocumentBuilder.
To the core of my question, then. After I've run the Ant build script and execute the Jar package, the XML file is easily accessible by the classes and the program runs without problems, but if I only want to test run it in Eclipse (Ctrl+F11) the XML file isn't found, obviously.
Is there a way to remedy this?

A: If you place your XML file in the same directory as your source files in your eclipse project it will be able to find the file when running in eclipse.
If you don't want to add the XML file to your sources you can create a second "source folder" in eclipse and store the file there.  At runtime the file should be found.

A: You can add a directory where this file resides to your classpath in Eclipse run configuration


text:
Q: Help in this proof of the argument principle I'm reading Conway's complex analysis book and on page 123 he made the following comment:

Suppose that $f$ is analytic and has a zero of order $m$ at $z=a$. So
  $f(z)=(z-a)^mg(z)$ where $g(a)\neq 0$. Hence
(3.1) $$\frac{f'(z)}{f(z)}=\frac{m}{z-a}+\frac{g'(z)}{g(z)}$$
and $g'/g$ is analytic near $z=a$ since $g(a)\neq 0$. Now suppose that
  $f$ has a pole of order $m$ at $z=a$; that is, $f(z)=(z-a)^{-m}g(z)$
  where $g$ is analytic and $g(a)\neq 0$. This gives
(3.2) $$\frac{f'(z)}{f(z)}=\frac{-m}{z-a}+\frac{g'(z)}{g(z)}$$

Afterwards in order to prove the argument principle he said that we can get the following equality from (3.1) and (3.2):

So, why can we get

$$\frac{f'(x)}{f(x)}=\sum_{k=1}^n{\frac{1}{z-a_k}}-\sum_{j=1}^m{\frac{1}{z-p_j}}$$

from (3.1) and (3.2)?

A: $$f(z)=\frac {(z-z_1)\dots(z-z_n)}{(z-p_1)\dots (z-p_m)}g(z)$$
And $g$ has no zero and no pole since $z_i$ and $p_i$ are all the zeros and poles of $f$.
Let's start, we let $a_1(z)=\frac {(z-z_2)\dots(z-z_n)}{(z-p_1)\dots (z-p_m)}g(z)$ : $$f(z)=(z-z_1)a_1(z) \Rightarrow \frac{f'(z)}{f(z)}=\frac {1}{z-z_1}+\frac{a_1'(z)}{a_1(z)}$$
Let $a_2(z)=\frac {(z-z_3)\dots(z-z_n)}{(z-p_1)\dots (z-p_m)}g(z)$ :$$a_1(z)=(z-z_2)a_2(z) \Rightarrow \frac{a_1'(z)}{a_1(z)}=\frac {1}{z-z_2}+\frac{a_2'(z)}{a_2(z)} \Rightarrow \frac{f'(z)}{f(z)}=\frac {1}{z-z_1}+\frac {1}{z-z_2}+\frac{a_2'(z)}{a_2(z)}$$
So by induction :
$$\frac{f'(z)}{f(z)}=\sum_{k=1}^n{\frac{1}{z-z_k}}+\frac{a_{n-1}(z)}{a_{n-1}(z)}$$ Where $a_{n-1}(z)=\frac {1}{(z-p_1)\dots (z-p_m)}g(z)$.
Let $b_1(z)=\frac{1}{(z-p_2)\dots(z-p_m)}g(z)$
$$u(z)=\frac{1}{z-p_1}b_1 \Rightarrow \frac{f'(z)}{f(z)}=\sum_{k=1}^n{\frac{1}{z-z_k}}-\frac{1}{z-p_1}+\frac{b_1'(z)}{b_1(z)}$$
We notice that $b_{m-1}=g(z)$, so by induction $$\frac{f'(x)}{f(x)}=\sum_{k=1}^n{\frac{1}{z-z_k}}-\sum_{j=1}^m{\frac{1}{z-p_j}}+\frac{g'(z)}{g(z)}$$


text:
Q: The best way to understand Hibernate internals I'm trying to understand how Hibernate works under the hood, how it manages lazy loading, transactions, data mappers, unit of work, identity maps, etc.
I wrote a small object model, and I downloaded Hibernate source code for debugging it.
I'm kind of lost, is this the best approach? Does documentation on these issues exist out there (web) ?
Any suggestions will be greatly appreciated.

A: Try the excellent book : Hibernate in Action, also debugging through the source is helpful but (I speak from experience of nhibernate only) understanding the principles before the implementation may be a better approach.

A: Hibernate in Action is old what you need is the 2nd edition Java Persistence in Action. This does a great job at going into the exotic cases and dealing with legacy db amongst other things but before you go spending money you should really look at this doc there you will see the reference docs as well as the FAQ, Common Problems, Advanced Problems plus you will see the annotations references which you will need if you are not using xml for your configuration.


text:
Q: Place a photo in the correct position (html) Hi i have created this html code for add photos on my site , the photo with my computer is seen in the correct posizone, but when when I see my picture on the computer of my friend I find the picture in a different location, how can I fix this problem ?

<img src="https://s27.postimg.org/8gj6vh1ur/a1_android.png"  style="position: absolute; z-index: -10; width: auto; height: 50%; top: 785px; right: 0px; bottom: 0px; left: 24px" />

`

A: Although your snipet is too incomplete to provide any sort of answer I will point out that "width: auto; height: 50%;" make your picture's dimensions variable based on the monitor's resolution and operating system (retina display, scaling etc).


text:
Q: How to open the Preview window maximised by default? Does anyone know how to open Preview.app with the window maximised by default, in order to automatically fit the screen?
Right now, the Preview window opens almost half screen and I think it is quire annoying to enlarge it manually. Thanks.

A: Only option is to use the key combination option (alt) + space to fullscreen the document.
**update: If you do alt+space you will go fullscreen, hold the alt button and you zoom 100% of the file


text:
Q: SQL Server - Transform multiple columns into multiple rows I have a wide table that contains 60+ columns for UPS/Fedex tracking numbers. I am trying to reduce the number of columns and have a parent to child relationship.
SELECT
    [TRACKING-NO1], [TRACKING-NO2], [TRACKING-NO3], [TRACKING-NO4],
    [TRACKING-NO5], [TRACKING-NO6], [TRACKING-NO7], [TRACKING-NO8],
    [TRACKING-NO9], [TRACKING-NO10]
FROM
    [CustomerServiceOrderEntry].[dbo].[InvoicedOrdersTempTable]
WHERE
    [TRACKING-NO2] IS NOT NULL

The output returns a list of all the tracking numbers in one row (60+) columns. If there are child tracking numbers, then columns 2 - 60 will be populated; If there are no child tracking numbers, 2 - 60 will be NULL.
What I would like to do is have a parent tracking number and the associated child tracking number, and a flag to indicate it is a child.
Current Structure
New Output
Any help you can provide would be greatly appreciated...

A: We need to use UNPIVOTfor convert columns to row.
But UNPIVOT does not returns any rows that not have child columns.
That' why, we need to determine  this kind of rows additionally.
SELECT
    [TRACKING-NO1] TrackingNumberParent ,
    'TRUE' TrackingNumberChildren
    ,TrackingNumberChild
FROM
    (SELECT * FROM [CustomerServiceOrderEntry].[dbo].[InvoicedOrdersTempTable] ) SRC
        UNPIVOT( TrackingNumberChild FOR COL IN (
            [TRACKING-NO2],
            [TRACKING-NO3],
            [TRACKING-NO4],
            [TRACKING-NO5],
            [TRACKING-NO6],
            [TRACKING-NO7],
            [TRACKING-NO8],
            [TRACKING-NO9],
            [TRACKING-NO10])) PVT
UNION ALL
SELECT
    [TRACKING-NO1] TrackingNumberParent,
    'FALSE' TrackingNumberChildren,
    NULL TrackingNumberChild
FROM
    [CustomerServiceOrderEntry].[dbo].[InvoicedOrdersTempTable]
WHERE
    [TRACKING-NO2] IS NULL
ORDER BY
    TrackingNumberParent

A: The following should be considerably faster as it only takes a single pass over the base table...
SELECT
    TrackingNumberParent = iot.[TRACKING-NO1],
    TrackingNumberChildren = CASE WHEN ctn.[TRACKING-NO] IS NULL THEN 'False' ELSE 'True' END,
    TrackingNumberChild = ctn.[TRACKING-NO]
FROM
    [CustomerServiceOrderEntry].[dbo].[InvoicedOrdersTempTable] iot
    OUTER APPLY (
                SELECT
                    tn.COL_NO,
                    tn.[TRACKING-NO]
                FROM ( VALUES
                    (2, iot.[TRACKING-NO2]), (3, iot.[TRACKING-NO3]), (4, iot.[TRACKING-NO4]),
                    (5, iot.[TRACKING-NO5]), (6, iot.[TRACKING-NO6]), (7, iot.[TRACKING-NO7]),
                    (8, iot.[TRACKING-NO8]), (9, iot.[TRACKING-NO9]), (10, iot.[TRACKING-NO10])
                    ) tn (COL_NO, [TRACKING-NO])
                WHERE
                    (
                        tn.[TRACKING-NO] IS NOT NULL
                        OR
                        tn.COL_NO = 2
                    )
                ) ctn;


text:
Q: Programatically add and bind DataGrid column I want to add a column programatically to my datagrid and bind it.
I have tried following examples on the web but cant get the data do be displayed.
I did have it working with columns declared in the xaml.
Here is the datagrid Xaml declaration:
<DataGrid Grid.Row="0" x:Name="dtgMain" AutoGenerateColumns="False" ItemsSource="{Binding}" RowHeight="25" SizeChanged="dtgMain_SizeChanged"></DataGrid>

Here is where I set the datacontext for the datagrid:
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(response);
                provider.Document = doc;
                provider.XPath = "/moo/response/data/load/panel";
                dtgMain.DataContext = provider;

Here is where I add the column:
DataGridTextColumn dc = new DataGridTextColumn();
            dc.Binding = new Binding("panelCode");
            dc.Header = "Job Number";
            dtgMain.Columns.Add(dc);

And here is an example of the xml:
<moo>
  <response>
    <data>
      <load count="2">true
        <panel index="10">
          <panelCode>100072
          </panelCode>
        </panel>
      </load>
    </data>
  </response>
</moo>

A: Your column binding is not using XPath when it should it seems to me.
dc.Binding = new Binding() { XPath = "panelCode" };


text:
Q: Best host for running large mem and processor intensive WordPress sites? I host a number of WordPress sites, some of which have VERY large databases. I've gone through several popular web hosts though no joy yet. Any suggestions.

A: If you've got a lot of hosts with tons of databases, perhaps it's time to upgrade to a dedicated server?  I host with Liquid Web and have been VERY happy.

A: Depending on what you're looking for, I'd suggest http://hub.org. It's not necessarily the cheapest around, nor does it necessarily have the most cutting edge control panel. But you get a VPS maintained by the most proficient system admin I can name (he's one of the original four behind postgresql), and it's an actual managed VPS (in the sense that whatever is not in the control panel, meaning much about everything except domain and email management, ends up as a "can you please do..." kind of support ticket). Highly recommended.


text:
Q: Remove the first link on the second tr element I have this HTML:

         Some text

         Some text

                New
                 List

     ... many others tr ...

I need to remove using jQuery the first a element in the second tr meaning the one with New text, any advice?
Note: My bad a made a typo

A: Try
Shortest code
$('tr:eq(1) a.btn-link:first').remove();

$('tr:eq(1) a:first').remove();

$('tr:eq(1) a:contains("New")').first().remove();

For exact match remove

$('tr:eq(1) a').filter(function(){
    return $(this).text() === 'New';
}).first().remove();

Reference
:eq()
:first
:contains()
.first()
.filter()

A: it has a div parent
so it doesn't really matter that it's in a td...
$('.btn-group:eq(0) a:eq(0)').remove();

or to repeat for all .btn-group:
$('.btn-group a:eq(0)').remove();

made a fiddle: http://jsfiddle.net/filever10/TFSem/


text:
Q: Higher inductive type: what for? The typical example of higher inductive type (HIT) is the circle $S^1$ that is nicely described here. I understand HITs are convenient if you want to do homotopy theory within type theory. But what does it bring the computer scientist? Are there interesting data structures that could not be defined without an HIT?

A: Good question.  To start with I should be clear that I think HITs are probably much more interesting to a homotopy theorist than to a computer scientist.  However, it seems that they are not completely devoid of interest to a computer scientist either.
One general class of applications is to constructing true quotients, where you have a data structure in which the same "real object" has multiple representations; by representing it as a HIT you can add actual equalities between the two representations so that any function defined on this data structure must necessarily respect that equality (be "representation-independent").
Additionally, here are some posts from the homotopy type theory blog on topics that might be of interest to computer scientists:

*

*Abstract types with isomorphic types

*Higher lenses

*Homotopical patch theory

*HoTTSQL


text:
Q: How to get GPS location from android app widget? I am new in android programming, and I have a task to make a standalone android widget (app widget), which sends some data to PHP server. I need to find a way to get current device location from the widget class. The widget class is called Alarm and it extends AppWidgetProvider, and it should be launched without Activity.
I have found many examples explaining how to get GPS location using LocationManager and LocationListener from MainActivity, but it's not what I need, I need it to be without activity, only widget.
I'll appreciate any idea.
Thanks in advance.

A:
I have a task to make a standalone android widget (app widget), which sends some data to PHP server. I need to find a way to get current device location from the widget class.

An app widget cannot "send send some data" to a server, and an app widget cannot "get current device location". An app widget — in the form of an AppWidgetProvider — lives for a millisecond or so, long enough to publish an update to its portion of the home screen's UI. That's it. Your entire process may be terminated within milliseconds after you return from onUpdate().
Create a Service (e.g., a JobService on Android 5.0+) that:

*

*Registers for location updates

*When it receives the location update, sends the data to the server

*If appropriate (since we do not know what the actual UI of the app widget is), use AppWidgetManager to update the app widget's UI

*Stops itself

When and how you schedule the service to do its work is up to you (JobScheduler and a JobService would be a fine choice).


text:
Q: terminal goes down with all children even when SIGKILLed but normal processes don't do the same I would like to have the same effect in my program as the bash(terminal) does when we kill it using SIGKILL. As we know that we cannot handle SIGKILL in our progams so when ever I kill my program its children are assigned to init process, there is no way to handle it so that I can kill all my child processes and then kill the parent itself. Though when ever we kill terminal all the process created through it are killed even if we kill our terminal by SIGKILL.
For this I did some research and found the below post:
[https://unix.stackexchange.com/questions/54963/how-can-terminal-emulators-kill-their-children-after-recieving-a-sigkill][1]
The post is bit confusing, still what I got out of the post is that if the process you are killing is the process leader of the process group then all its children will be killed.
So for simplicity, I implemented below program to test if it is so:
int main()
{
    printf("Curent PID: %u\n", getpid());

    // make a new session
    pid_t pid = setsid();

    printf("New session ID: %u\n", pid);

    pid = fork();
    switch(pid)
    {
            case -1:
                    perror("UNable to fork the process\n");
                    exit(EXIT_FAILURE);
            case 0:
                    // child process
                    while (1)
                    {
                            sleep(1);
                    }
                    break;
    }

    while (1)
    {
            printf("Process Leader running\n");
            sleep(1);
    }

return 0;

}

After running the above program when I killed the parent process the child process didn't got killed. I also modified the above program so that it does not belong to any tty, I thought might be the process leader should not be associated with any tty. I did that by the following way:
Create a normal process (Parent process)
Create a child process from within the above parent process
The process hierarchy at this stage looks like :  TERMINAL -> PARENT PROCESS -> CHILD PROCESS
Terminate the the parent process.
The child process now becomes orphan and is taken over by the init process.
Call setsid() function to run the process in new session and have a new group.
then the same above code repeats.
Still when i killed the process leader children were there.
Maybe I didn't got that post on unix.stackexchange or is it the deafult behaviour in LINUX.
One way that I can implement to make all children kill is by catching each TERMINATING SIGNAL like SIGTERM, SIGHUP etc. handle them and write logic inside those signal handlers to kill child first.But still on SIGKILL I can't do anything.
Also I am interested to know that if killing parent process doesn't affect child process even if the parent is process leader or whatever then how bash(terminal) manages to kill all the child processes even if we send SIGKILL to it. Is there some extra logic written for terminals in LINUX kernel.
If there is a way to kill all child processes when parent is killed even using SIGKILL signal, I would be happy to know that too.

A: Manual page of kill says:

Negative PID values may be used to choose whole process groups

In my understanding to kill the whole group of processes, you have to send negative PID.
Another mechanism is causing that killing a terminal kills its child processes. Processes running from a terminal have their stdin/stdout attached to the terminal. When killing the terminal, those connections are closed and a signal (SIG_HUP) is sent to those processes. A usual program does not handle this signal and is terminated by default.

A: The advice from Marian is quite correct and well worth researching, but if you choose to follow that route you will likely end up with an implementation of what might be called the "hostage trick".
The hostage trick consists of your root process spawning an artificial child process which spends all its time in the stopped state.  This "hostage" will be spawned immediately before the first child process which does real work in your (multi-process) program.
The hostage process is made the leader of its own process group and then enters a loop in which it stops itself with "raise(SIGSTOP)".  If it is ever continued, it checks to see whether its parent has terminated (i.e. whether it has been re-parented or cannot signal its parent with the null signal (ESRCH)).  If the parent has terminated, then the hostage should terminate, otherwise it should re-suspend with another "raise(SIGSTOP)".
You need to be careful about race conditions: e.g. for the re-parenting test take care to cache the parent-process-id for the hostage as the return value from "getpid()" before "fork()"-ing the hostage and also make "setpgid()" calls downstream of "fork()" in both parent and child.  You then need to consider what you do if someone "kill(., SIGKILL)"s the hostage!
True, you can put a SIGCHLD handler in the parent to re-spawn it, but that requires considerable care to preserve the continuity of the identity of the hostage's process group; maybe there were other child processes at the time of the SIGKILL and the replacement hostage should go in the original process group, maybe there weren't and the original process group has evaporated.
Even if you get that right, the fact that you have put a "fork()" call in a handler for an asynchronous signal (SIGCHLD) will likely open another can of worms if your main process uses multiple threads.
Because of these difficulties I would advise against using the hostage trick unless the child processes run code over which you have no control (and to think seriously about the costs in complexity and maintainability even then).  If you have control of the code of the child processes, then it is much simpler to use a "pipe()".
You create the pipe in the parent process and manage the file descriptors to ensure that the parent process is the sole writer and that each child process allocates one file descriptor to the read-side.  If you do this, then the termination of the parent process (whether due to SIGKILL or any other cause) is communicated to the child processes by the EoF condition on the read side of the pipe as the last writer terminates.
If you want to treat SIGKILL specially, then you can use a protocol on the pipe whereby the parent process sends a termination message advising the children of its termination status on all normal terminations and on catchable fatal signals, and leaves the children to infer that the parent was killed by SIGKILL in the event that the read-side of the pipe delivers an EoF without a preceding termination message.

A: On Linux prctl(PR_SET_PDEATHSIG... will arrange for a process to receive a signal when it's parent dies, this setting is preserved over exec but not inherited by child processes.


text:
Q: Converting comma separated list to dummy variables I have a table as follows:
yel <- data.table(id=c(1,2,3))
yel$names[1] <- "\"parking space\", \"dining\", \"3bh\""
yel$names[2] <- "\"parking\" , \"outdoor\""
yel$names[3] <- "\"Hello!\",\"dining room\",\"3bh\""
yel

   id                            names
1:  1 "parking space", "dining", "3bh"
2:  2            "parking" , "outdoor"
3:  3     "Hello!","dining room","3bh"

I was to dummify the names variable and join the same words like parking space with parking and also dining room with dining.
I want the dummy variables as follows: parking , dining, 3bh , outdoor, hello. Is there any method that does this?

A: How about this (the regex may still need to be tweaked a bit-doesn't look like it is generalized enough). Using tidyr:
separate_rows(yel,names,sep=",")->df1
df1 %>% mutate(newnames=gsub('\\"| space|\\!| |room', "", names))

  id           names newnames
1  1 "parking space"  parking
2  1        "dining"   dining
3  1           "3bh"      3bh
4  2      "parking"   parking
5  2       "outdoor"  outdoor
6  3        "Hello!"    Hello
7  3   "dining room"   dining
8  3           "3bh"      3bh