text:
Q: free function for linked-list not working I've pasted my function code below to free to contents of the following structure:
struct LetterFrequencyPair
{
    char character;
    int frequency;
    struct LetterFrequencyPair* next;
};

Creating and displaying the list isn't an issue and works fine. However, when I got to free function nothing happens. To try to pin point the cause of the issue I added printed step statements to my code. (Seen in the function below) to see how much of the code executes. On the output all I get is "Step 1" and nothing else so that would suggest the error is after that line. I'm not sure what is incorrect here as it's the same format I've used in another linked-list exercise.
Please let me know if you spot where I've gone wrong. Also if you need to see the whole code (I'm pretty sure you shouldn't, as this is where the error is) let me know and I'll edit the question to add it in. :)
 void freeList()
{
    struct LetterFrequencyPair* temp;
    temp = root;
    if (temp == NULL)
        {
            printf("List is empty.\n");
        }
    else
    {
        printf("step 1\n");
        while(temp != NULL);
        {
            printf("Step 2.\n");
            struct LetterFrequencyPair* nexttemp = temp->next;
            printf("step 3\n");
            free(temp);
            printf("Step 4\n");
            temp = nexttemp;
            printf("5\n");
        }
        printf("\n");
    }
}

A: The error was spotted by @Alexander Dmitriev (He commented on the question).
The error was the ; in the line while(temp != NULL);
Removed the ; and the function now works fine.


text:
Q: Pandas - Create Column Name Based on the values in a Column I want to create the column names based on the values in a column
This is what I have:
part_number source  recent_date  recent_price
    0023496     a1  2017-06-27    55.0
    0023496     e1  2017-08-03    315.0
    0023084     a1  2017-01-12    255.0
    0023084     e1    NaN           NaN

This is the output that I want:
part_number a1_recent_date   a1_recent_price   e1_recent_date e1_recent_price

0023496     2017-06-27       55.0               2017-08-03        315.0
0023084     2017-01-12      255.0                  NaN             NaN

A: Use set_index and unstack
In [520]: dff = df.set_index(['part_number', 'source']).unstack()

In [521]: dff
Out[521]:
            recent_date             recent_price
source               a1          e1           a1     e1
part_number
23084        2017-01-12         NaN        255.0    NaN
23496        2017-06-27  2017-08-03         55.0  315.0

Then, set the column names
In [522]: dff.columns = dff.columns.map(lambda x: '{1}_{0}'.format(*x))

In [523]: dff
Out[523]:
            a1_recent_date e1_recent_date  a1_recent_price  e1_recent_price
part_number
23084           2017-01-12            NaN            255.0              NaN
23496           2017-06-27     2017-08-03             55.0            315.0

Details
In [527]: df
Out[527]:
   part_number source recent_date  recent_price
0        23496     a1  2017-06-27          55.0
1        23496     e1  2017-08-03         315.0
2        23084     a1  2017-01-12         255.0
3        23084     e1         NaN           NaN

A: This can do it:
pd.concat([agg_df.add_prefix(index+'_').reset_index()
           for index,agg_df  in df.groupby('source', as_index=False)],
           axis=1)

Explanation:

*

*create groups of dataframe based on the value of soure: df.groupby('source', as_index=False)

*iterate through these group for index,agg_df ...

*for each group add the source value as prefix and reset_index : agg_df.add_prefix(index+'_').reset_index()

*Finally, concatenate all groups back to one dataframe: pd.concat([...])

Results:
In [46]: pd.concat([agg_df.add_prefix(index+'_').reset_index()
    ...:            for index,agg_df  in df.groupby('source', as_index=False)],
    ...:            axis=1)
Out[46]:
   index a1_part_number a1_source a1_recent_date a1_recent_price  index  \
0      0        0023496        a1     2017-06-27            55.0      1
1      2        0023084        a1     2017-01-12           255.0      3

  e1_part_number e1_source e1_recent_date e1_recent_price
0        0023496        e1     2017-08-03           315.0
1        0023084        e1            NaN             NaN

In [47]:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable cargo-related functionality in rust-analyzer If I don't want to use cargo for some reasons, I have the error: could not find 'Cargo.toml'. Is there any way to disable all Cargo.toml-related functionality?
I tried this:
{
    "cargo": {
        "noSysroot": true,
        "sysroot": "",
        "autoreload": false,
        "buildScripts": { "enable": false }
    }
}

But this didn't help.

A: To use rust-analyzer with single files, please check out https://github.com/rust-lang/rust-analyzer/pull/8955. For larger projects that don't use Cargo, you won't be able to use rust-analyzer at the moment as per this comment.


text:
Q: Test unpublished add-on fails I'm trying to test an unpublished Google Sheets add-on with other google accounts.
I've followed the documentation but it doesn't work as expected:

*

*In any case no "Install add-on" button is displayed for the head deployment

*In order to display the button "install as add-on", the tester needs to create a new deployment

*If the user has read-only access it shows the following error

*If the user has edit access, then it shows the button
Once the button is displayed, clicking on it shows a message saying that it's deploying the add-on but...

*

*In no case the add-on appears in a spreadsheet, nor in the Manage add-ons pop-up

*When I come back to the "deploy from manifest" list, the deployment that was supposed to be associated to the add-on doesn't show the expected button "uninstall add-on"

I have tried:

*

*with Gsuite users having editing rights and myself, the owner.
FYI,

*with a stand-alone script and a script associate to a spreadsheet... same results

I think the whole flow is just not working. So please G Suite team check out this message


text:
Q: Clojure: Create or update Map values in a vector I want to update some values in my vector.
To change this :
[{:key 0, :values {:value1 1, :value2 100}} {:key 1, :values {:value1 5, :value2 300}}]

In this:
[{:key 0, :values {:value1 1, :value2 100}} {:key 1, :values {:value1 6, :value2 500}}]

I'm trying to do something like that, without success:
(if (contains? myvectors myId)
  (do
    (assoc ((myvectors myId) :values) :value2 500));not working
  )
  (do
    (def myvectors (merge myvectors {:key myId :values {:value1 1 :value2 300}}))
  )
)

A: This would work:
(def v
  [{:key 0 :values {:value1 1 :value2 100}} {:key 1 :values {:value1 5, :value2 300}}])

(defn update-values [v k value1 value2]
  (mapv (fn [{:keys [key] :as m}]
          (cond-> m
            (= key k) (assoc :values {:value1 value1 :value2 value2})))
        v))

(update-values v 1 6 500)
;; => [{:key 0 :values {:value1 1 :value2 100}}
;;     {:key 1 :values {:value1 6 :value2 500}}]

If possible I would change your data structure so you can make better use of core functions, for example a map from key to values:
(def m
  {0 {:value1 1 :value2 100}
   1 {:value1 5 :value2 300}})

(assoc m 1 {:value1 6 :value2  500})
;; => {0 {:value1 1 :value2 100}
;;     1 {:value1 6 :value2 500}}

A: If all you want to do is change the second element (map) in your vector as per your before/after examples, you can do something like this:
(let [m [{:key 0, :values {:value1 1, :value2 100}}
         {:key 1, :values {:value1 5, :value2 300}}]]
  (update-in m [1 :values] merge {:value1 6 :value2 500}))
=> [{:key 0, :values {:value1 1, :value2 100}} {:key 1, :values {:value1 6, :value2 500}}]

where update-in updates the second element in the vector (index 1 in the [1 ...] expression - 0 based indexing) and on that element updates the :values key. For that value ({:value1 5, :value2 300}) we call the merge function. update-in will send in the old value (again, the old value is at this point {:value1 5, :value2 300}) as the first argument to merge and then we send in {:value1 6 :value2 500} as the second argument. Since later arguments to merge "win", the map values we send in will overwrite the ones already in your data.

A: It's not clear what's your goal, but I've tried to come up with something general enough:
(def data [{:key 0, :values {:value1 1, :value2 100}}
           {:key 1, :values {:value1 5, :value2 300}}])

(reduce
  (fn [v {:keys [key] :as row}]
    (conj v
          (cond-> row
                  (= key 1)
                  (assoc :values {:value1 6, :value2 500}))))
  []
  data)
=> [{:key 0, :values {:value1 1, :value2 100}} {:key 1, :values {:value1 6, :value2 500}}]

This will reduce over the input sequence by changing the given row only based on some condition. Since it looks like you want to change based on the key I've added the condition (= key 1) but this can be easily adapted to any condition for anything that's contained in the row.


text:
Q: WPF ICollectionView Filter Reset I have a CollectionView derived from an ObservableCollection:
private static ObservableCollection<CalculationViewModel> _calculations;

CalculationViewModelsCollection = (CollectionView)CollectionViewSource.GetDefaultView(_calculations);

My problem is that, when the result of the filter is nothing, I'd like to clear the filter, and re-filter with other conditions, but the CollectionView is always empty.
I tried to reset the filter these ways:
CalculationViewModelsCollection.Filter = null;
CalculationViewModelsCollection.Refresh();

and
CalculationViewModelsCollection.Filter = delegate(object p)
{
    return true;
};

But none of them worked.
Could you give some advice how to reset a filter on a CollectionView?

A: From your example, I'm not entirely sure how you're getting your CollectionView, nor am I sure I understand your question correctly.
But anyway, I hope the sample code below helps you with your problem.  It's an app that has a listbox containing strings, and a "filter" textbox.  if nothing in the list matches the filter, the filter will be set to null and thus display all items.
XAML:
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:v="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox x:Name="textBox" TextChanged="TextBox_TextChanged"/>
        <ListBox x:Name="listBox"/>
    </StackPanel>
</Window>

Code-behind:
public partial class MainWindow : Window
{
    ListCollectionView lcv;
    Predicate<object> filterFx;

    public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<string> s = new ObservableCollection<string>();
        "The Quick Brown Fox Jumps Over The Lazy Dog"
            .Split(' ')
            .ToList()
            .ForEach((word) => s.Add(word.ToString()));

        this.lcv = new ListCollectionView(s);
        this.listBox.ItemsSource = this.lcv;

        this.filterFx = (p) => ((string)p).ToUpper().Contains(this.textBox.Text.ToUpper());
        lcv.Filter = this.filterFx;
    }

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        lcv.Refresh();

        if (lcv.Count == 0)
            lcv.Filter = null;
        else
            lcv.Filter = filterFx;
    }
}

A: I did a big binding mistake. I don't understand how it works at all.
So the matter is that, it's simple to reset a filter, just set the value to null.
There is one more thing. I tried to create ListCollectionView like you did it.
this.lcv = new ListCollectionView(s);

But the filter didn't work, and I couldn't add SortDescription to the CollectionView.
I create CollectionView this way:
this.lcv = (CollectionView)CollectionViewSource.GetDefaultView(s);

and everything work fine. But ideally your technique have to work too.


text:
Q: How do I execute this unique reshaping in R (or excel)? I am trying to reshape a data frame, and the task is just different enough from a typical reshape that I can't quite swing it. The table is originally in excel, but I've already imported to R, so I can work with a solution in either software.
I have a data frame donors containing names, values, and months:
NAME    AMT    MONTH
brett   100    jan
brett   100    mar
brett   100    nov
brett   50     apr
brett   50     jun
jane    75     dec
sam     200    jan
sam     200    feb
sam     200    mar

I need to reshape this data frame so that there is a NAME column, an AMT column, and a column for each month. Each row corresponds to any observation that is unique in both name and amount, and the month columns are binary variables (1 if that donor/amount combo occurred that month, and 0 if not.
So the above example would work out to:
NAME   AMT   JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
brett  100   1   0   1   0   0   0   0   0   0   0   1   0
brett  50    0   0   0   1   0   1   0   0   0   0   0   0
jane   75    0   0   0   0   0   0   0   0   0   0   0   1
sam    200   1   1   1   0   0   0   0   0   0   0   0   0

if you want to complete my code, create a final column equal to the total number of times that NAME/AMT combo occurred (just equal to the sum of the month columns)... but I can do that myself if you aren't feeling it.
Thank you!

A: Here's a tidyverse attempt -

*

*complete to create rows with missing months.

*arrange so that you have columns in correct order.

*Get data in wide format using pivot_wider.

library(dplyr)
library(tidyr)

df %>%
  complete(MONTH = tolower(month.abb)) %>%
  arrange(match(MONTH, tolower(month.abb))) %>%
  pivot_wider(names_from = MONTH, values_from = MONTH,
              values_fn = length, values_fill = 0) %>%
  na.omit

#  NAME    AMT   jan   feb   mar   apr   may   jun   jul   aug   sep   oct   nov   dec
#  <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#1 brett   100     1     0     1     0     0     0     0     0     0     0     1     0
#2 sam     200     1     1     1     0     0     0     0     0     0     0     0     0
#3 brett    50     0     0     0     1     0     1     0     0     0     0     0     0
#4 jane     75     0     0     0     0     0     0     0     0     0     0     0     1

Note that month.abb is inbuilt R vector which gives abbreviated month names. I used tolower(month.abb) to match it with the actual column names in the data.
data
df <- structure(list(NAME = c("brett", "brett", "brett", "brett", "brett",
"jane", "sam", "sam", "sam"), AMT = c(100L, 100L, 100L, 50L,
50L, 75L, 200L, 200L, 200L), MONTH = c("jan", "mar", "nov", "apr",
"jun", "dec", "jan", "feb", "mar")),
class = "data.frame", row.names = c(NA, -9L))

A: Here's my approach with dcast :
library(reshape2)
library(Hmisc)

my_df <- data.frame("NAME" = c(rep("brett", 5), "jane", rep("sam", 3)),
                "AMT" = c(rep(100, 3), rep(50, 2), 75, rep(200, 3)),
                "MONTH" = c("jan", "mar", "nov", "apr", "jun", "dec", "jan", "feb", "mar"),
                stringsAsFactors = FALSE)

my_df <- dcast(my_df, NAME+AMT ~ MONTH, value.var = "MONTH", fun.aggregate = length)
my_df <- my_df[order(my_df$NAME, -my_df$AMT),]
my_miss <- setdiff(month.abb, capitalize(colnames(my_df)))
my_df[tolower(my_miss)] <- 0
my_df <- my_df[, c("NAME", "AMT", tolower(month.abb))]

A: Same solution as provided above, just using data.table
donors <- structure(list(NAME = c("brett", "brett", "brett", "brett", "brett", "jane", "sam", "sam", "sam"), AMT = c(100L, 100L, 100L, 50L, 50L, 75L, 200L, 200L, 200L), MONTH = c("jan", "mar", "nov", "apr",
"jun", "dec", "jan", "feb", "mar")), row.names = c(NA, -9L), class = c("data.frame"))

library(data.table)
setDT(donors) # make a data.table

m <- tolower(month.abb)
donors <- dcast(donors, NAME + AMT ~ MONTH, fun.aggregate = length)
donors[, setdiff(m, names(donors)) := 0L]
setcolorder(donors, c(c("NAME", "AMT"), m))
donors[, total := rowSums(.SD), .SDcols = m]
setnames(donors, old = m, new = toupper(m))

donors

    NAME AMT JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC total
1: brett  50   0   0   0   1   0   1   0   0   0   0   0   0     2
2: brett 100   1   0   1   0   0   0   0   0   0   0   1   0     3
3:  jane  75   0   0   0   0   0   0   0   0   0   0   0   1     1
4:   sam 200   1   1   1   0   0   0   0   0   0   0   0   0     3

A: A base R approach.
First aggregate the data to get the grouping
dat_agg <- aggregate( . ~ AMT ,dat, unique )

dat_agg
  AMT  NAME         MONTH
1  50 brett      apr, jun
2  75  jane           dec
3 100 brett jan, mar, nov
4 200   sam jan, feb, mar

Then add the desired table of months
dat_agg <- cbind( dat_agg, setNames( data.frame(
  matrix( 0, nrow(dat_agg), length(month.abb) ) ), tolower(month.abb) ) )

dat_agg
  AMT  NAME         MONTH jan feb mar apr may jun jul aug sep oct nov dec
1  50 brett      apr, jun   0   0   0   0   0   0   0   0   0   0   0   0
2  75  jane           dec   0   0   0   0   0   0   0   0   0   0   0   0
3 100 brett jan, mar, nov   0   0   0   0   0   0   0   0   0   0   0   0
4 200   sam jan, feb, mar   0   0   0   0   0   0   0   0   0   0   0   0

Finally populate the binary data by matching the colnames with the list of MONTH
dat_agg[,-c(1:3)][ t( sapply( seq_along(dat_agg$MONTH), function(x)
  colnames(dat_agg[,-c(1:3)]) %in% dat_agg$MONTH[[x]] ) ) ] <- 1

dat_agg[,-3]
  AMT  NAME jan feb mar apr may jun jul aug sep oct nov dec
1  50 brett   0   0   0   1   0   1   0   0   0   0   0   0
2  75  jane   0   0   0   0   0   0   0   0   0   0   0   1
3 100 brett   1   0   1   0   0   0   0   0   0   0   1   0
4 200   sam   1   1   1   0   0   0   0   0   0   0   0   0

Data
dat <- structure(list(NAME = c("brett", "brett", "brett", "brett", "brett",
"jane", "sam", "sam", "sam"), AMT = c(100L, 100L, 100L, 50L,
50L, 75L, 200L, 200L, 200L), MONTH = c("jan", "mar", "nov", "apr",
"jun", "dec", "jan", "feb", "mar")), class = "data.frame", row.names = c(NA,
-9L))


text:
Q: Is my website being crawled? I have a mean-stack website hosted in a DigitalOcean & nginx & ubuntu server.
In the website, there is a webpage with a button to allow users to send me a message:
<button type="submit" class="btn btn-lg btn-theme" ng-click="mySubmit()">Send Message</button>

in the controller:
$scope.mySubmit = function () {
    return $http.post('/httpOnly/request/addRequest', { "name": $scope.name, "mail": $scope.mail, "message": $scope.message })
}

Then, in the backend, it uses https://github.com/sendgrid/sendgrid-nodejs to send me emails.
Previously, everything was fine. However, for 1 week, I received every day 7 mails in a row with undefined values. The 7 mails arrived at almost same time every day.
Does anyone know what is happening? Is my website being crawled? Is there a way to verify that?

A: The answer is almost definitely yes. You should be able to verify that by checking your nGinx logs and looking for standard bot user-agent fields.
There is a difference between being crawled by good bots (probably desirable, in order to appear in search engines) and being spam posted to by bad bots. These are often simply trying to post to e.g. blog comments sections with spammy links etc.
To manage which goods bots crawl you, you should use robots.txt.
Bad bots on the other hand, won't respect robots.txt, and might even spoof their user agents, so you can't block them using that.
A captcha, or recaptcha challenge would work. Alternatively consider using a Cloudflare account. They implement a configurable web application firewall between the internet and your site, and block a lot of this type of activity automatically.


text:
Q: Debugging NSObjectInaccessibleException - The NSManagedObject with ID:0x123456789 has been invalidated I have a bug I'm struggling to track down. I believe what's happening is that I'm deleting an object from the underlying database whilst another managed object context (in another thread) has a fault on it and gets the 'NSObjectInaccessibleException' when it tries to fulfil the fault.
The scenario is that I have a view accessing the data through one context meanwhile in the background, another threat is purging out of date records from the store. The background thread should only be purging objects which are not required by the view - this obviously isn't the case but I'm having trouble tracking down exactly what happens. By the time I see the defect, it's too late and it is a relatively rare defect that mainly only happens in the field.
Hence my question: Are there any tricks I'm missing when debugging CoreData - can I track lifetimes of objects from one context in another? I.e. when I delete my object is there an easy way to see if any other contexts have a reference to that same object? Using that, I could build some test code to check my logic and find the error.

A: I encountered this error earlier and the culprit was that I was cleaning up (completed released) my context and then later tried to access an object (previously) managed by that context.
In my case, the context was a "scratch" context that goes away when the view was closed.  However, I had a background job that the view had spawned that wanted to update the object.
I ended up making an accessor for the managed object that returned nil when [managedObject isFault] was true.  Then in my code I was checking the value of that accessor selector to make sure I had a valid object to work with (say when my background job finally finished its work).
I'm pretty new to Core Data, so there's probably a better/smarter way to do this, but I think it fixed the issue for me.

A: I just faced this issue me too. I did some refactoring to follow Apple's "find-or-create" pattern for a bulk import of data. I created a new context dedicated to the import, by setting the undomanager to nil as suggested.
So:
// create a new special context for the bulk import of data
NSManagedObjectContext *importContext = [[NSManagedObjectContext alloc] init];
[importContext setPersistentStoreCoordinator:_persistentStoreCoordinator];

// avoid tracking for undo/redo operations
[importContext setUndoManager:nil];

then I created a fetchRequest to retrieve ids of objects stored in the database, and inside the import loop I tested object's id to find if it was contained inside the array of ids retrieved... the problem was that at a given interval I was saving the importContext and resetting it. And since I did erroneously referring to importContext rather than defaultContext I get that error. I fixed simply by changing:
NSArray *storedObjects = [importContext executeFetchRequest:checkRequest error:&fetchError];

with:
NSArray *storedObjects = [defaultContext executeFetchRequest:checkRequest error:&fetchError];

A: What is the second context doing when it tries to fault in the object which has been deleted from the persistent store?
This sounds like a bug which may have 2 parts: you aren't merging changes from your peer context, and you have a logic bug which is causing you to use an object in thread B which has been deleted in thread A.
Typically you'll want to merge changes from a peer context using -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:].

A: The solution was a combination of cleanup and this mapkit bug. a map view was holding onto its delegate after I had released my NSManagedObjectContext. Mapkit asked the delegate for the co-ordinates of an annotation and my delegate object tried to query an object that was in a released context (similar to Jason's problem).
The fix was as described in Jake's blog post - set the delegate to nil when you are finished with the map view.


text:
Q: How can I plot my trained model result on video using Detectron2? I am new on using Detectron2. I want to load the video from local drive. And then, do detection using my trained model using Detectron2's VideoVisualizer.
I tried to find a tutorial about this. But it does not exist. Could you please what do I do?
Thank you
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()

# import some common libraries
import numpy as np
import tqdm
import cv2

# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.video_visualizer import VideoVisualizer
from detectron2.utils.visualizer import ColorMode, Visualizer
from detectron2.data import MetadataCatalog
import time

video = cv2.VideoCapture('gdrive/My Drive/video.mp4')
width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))

cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.OUTPUT_DIR = 'gdrive/My Drive/mask_rcnn/'
cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7  # set threshold for this model
predictor = DefaultPredictor(cfg)

v = VideoVisualizer(MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), ColorMode.IMAGE)

A: First, check the following tutorial (you can skip training parts if you don't want to train on your own data).
https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=Vk4gID50K03a
Then, look at the following code to inference on video.
https://github.com/facebookresearch/detectron2/blob/master/demo/demo.py


text:
Q: convert*bat file to .sh file I would like to change the batch file to *.sh file to run in linux?
the *bat file as following:
@echo off
rem -----------
rem Use following two lines to input value on command line
rem if "%1"=="" goto NoRunners
rem set N=%1
rem -----------
set N=8

if %N%==0 goto NoRunners

cd W:\MCMC\runner1\MCMC\tracer2D\
Echo Starting Runner 1
Start "Runner 1" /min runner

if %N%==1 goto GoHome

cd W:\MCMC\runner2\MCMC\tracer2D\
Echo Starting Runner 2
Start "Runner 2" /min runner

if %N%==2 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 3
Start "Runner 3" /min runner

if %N%==3 goto GoHome

cd W:\MCMC\runner2\MCMC\tracer2D\
Echo Starting Runner 4
Start "Runner 4" /min runner

if %N%==4 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 5
Start "Runner 5" /min runner

if %N%==5 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 6
Start "Runner 6" /min runner

if %N%==6 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 7
Start "Runner 7" /min runner

if %N%==7 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 8
Start "Runner 8" /min runner

if %N%==8 goto GoHome

cd W:\MCMC\runner3\MCMC\tracer2D\
Echo Starting Runner 9
Start "Runner 9" /min runner

:GoHome
cd ..\..\..\
goto End

:NoRunners
Echo No Runners started

:End
pause

A: You would literally have to hand translate that entire script. I have had an idea for a while, though, to make a bash implementation of at least the DOS batch language (extensions and Windows specific commands will be a harder one to pull off), but it would take a lot of work.

A: Here is my sh script to automate this task with sed. Run it in the directory with batch files (backup has .bak extension):
#!/bin/sh
files="*.bat"
sed -i.bak "s/%\([^%]\+\)%/\$\1/g" $files #Variables conversion
sed -i "s/%\([0-9]\+\)\b/\$\1/g" $files
sed -i "s/if \+not \+defined \+\([^ ]\+\) /[ -z \"\$\1\" ] \&\& /gI" $files
sed -i "s/if \+defined \+\([^ ]\+\) /[ -n \"\$\1\" ] \&\& /gI" $files
sed -i "s/if \+not \+exist \+\([^ ]\+\) /[ ! -f \$\1 ] \&\& /gI" $files
sed -i "s/if \+exist \+\([^ ]\+\) /[ -f \$\1 ] \&\& /gI" $files
sed -i "s/if \+not \+\([^ ]\+\) /[ ! \1 ] \&\& /gI" $files
sed -i "s/if \([^ ]\+\) /[ \1 ] \&\& /gI" $files
sed -i "s/\\\\/\//gI" $files  #path conversion
sed -i "s/\^|/|/gI" $files #backslashed pipe conversion
sed -i "s/\"==\"/\" == \"/gI" *.bat # == conversion
sed -i "s/\brem /# /gI" $files #comments conversion
sed -i "s/\bnul\b/\/dev\/null/gI" $files # 'nul' conversion
sed -i "s/\bset //gI" $files # 'set' conversion
sed -i "s/\btype /cat /gI" $files # 'type' conversion
sed -i "s/\bfind /grep /gI" $files # 'find' conversion
sed -i "s/\bdel\(ete\)\? /rm /gI" $files # 'del' conversion

I published the script here:
https://github.com/meshr-net/helpers/blob/master/bat2sh.sh


text:
Q: Python Regex and group function Hi trying to separate each of the expressions from the colon.  So want to obtain 'ss_vv', 'kk' and 'pp'.  But the two print expressions below give me 'v' and 'k', so getting parts only of each string.  Can anyone see what wrong here?
m0 = re.compile(r'([a-z]|_)+:([a-z]|_)+:([a-z]|_)+')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)

A: In [52]: m0 = re.compile(r'([a-z|_]+):([a-z|_]+):([a-z|_]+)')

In [53]: m1 = m0.search('ss_vv:kk:pp')

In [54]: print m1.group(1)
ss_vv

In [55]: print m1.group(2)
kk

In [56]: print m1.group(3)
pp

What my regex does:
([a-z|_]+):([a-z|_]+):([a-z|_]+)

Debuggex Demo
What your regex does:
([a-z]|_)+:([a-z]|_)+:([a-z]|_)+

Debuggex Demo

A: No need to use regex for your case. You can just split on basis of ':' and get required output..
>>> a = 'ss_vv:kk:pp'
>>> b_list = a.split(':')
>>> b_list
['ss_vv', 'kk', 'pp']
>>>

A: What are the other rules for the regular expression? based on your question, this regex would do:
m0 = re.compile(r'(.*):(.*):(.*)')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)

UPDATE:
as mentioned by @Jan in the comments, for efficient and better use of regex, you can modify it as
regex = r'([^:]+):([^:]+):([^:]+)'
m0 = re.compile(regex)

output:
ss_vv
kk

or by just splitting the string:
string = 'ss_vv:kk:pp'
parts = string.split(':')

print parts

outputs: ['ss_vv', 'kk', 'pp']


text:
Q: Exiting a thread that contains a blocking statement in c I made a program with multiple processes, each with a number of threads. I want to stop the program using ctrl-c, and decided to use an interrupt handler. To do this I used the signal() function to set a flag when ctrl-c is pressed. Most of the threads contain loops that don't have a blocking statement in them, and just run while the flag is not set. When the flag is set, the loop ends and pthread_exit() is called. Some of the threads contain a blocking statement, and might not get to the point where the flag change is noticed and the loop can end.
In the example below, this would result in a memory leak (malloc() without a free() ) and a process that was not ended properly.
I checked many Q&A's, but could not find a proper solution. Any help would be greatly appreciated!
I added an example below (pseudo-code):
int flag = 0;

int main(void)
{
    // when (CTRL-C) is pressed, execute the interrupt handler
    signal(SIGINT, interrupt_handler_STATSERVER);

    // -- THREAD1: continuously receive packets from the data server
    pthread_t receivePackets_thread;
    int rc = pthread_create(&receivePackets_thread, NULL,(void*) receiveFromDataServer, NULL);
    if (rc)
    {
        printf("ERROR; return code from pthread_create() is %d\n", rc);
        exit(-1);
    }
}

void* receiveFromDataServer(void)
{
    while(flag == 0)
    {
        //every loop, allocate memory for a packet
        packet = (ProcessedPacket*) malloc(sizeof(ProcessedPacket));
        if(packet == NULL)
        {
            // ERROR: mem allocation error
        }
        else
        {
            // wait for a connection
            //*** THE BLOCKING STATEMENT IS HERE ***
        }
    }

    pthread_exit(NULL);
}

void interrupt_handler_STATSERVER(int signum)
{
    printf("STAT SERVER INTERRUPT!\n");
    flag = 1;
}`

A: Make sure to mask off SIGINT on all your child threads, as signal delivery is to a single, arbitrary thread without the signal masked.  This guarantees your "management thread" will get the ctrl-c.  Then, use pthread_kill from your management thread to send signals to your other threads using an unmasked signal.  This will interrupt your blocking calls and allow you to test flags and such.
Read this: http://man7.org/linux/man-pages/man7/signal.7.html
especially the section titled: Signal mask and pending signals
Use pthread_sigmask to examine and change your thread's signal mask.


text:
Q: Sign of the real parts of the solutions of $\det (s^2+Bs+C)=0$ where $B$, $C$ are real positive definite matrices. Let $ B, C$ be $n \times n$ symmetric, positive definite matrices with real entries and $I_n$ be the $n\times n$ identity matrix. Here, Consider the following polynomial equation with complex variable $s$.
$\det ( s^2I_n + sB+C) = 0$
Can I conclude that all the $2n$ solutions (which is of course, counted with multiplicity) has  strictly negative real parts?
Note: The above conjecture is predicted by a physical argument, since the above equation comes out during an attempt to solve the equations of motion of an $n$- dimensional oscillator with some frictional force, by subsituting $x(t)=C e^{st}$. The existence of frictional force must cause the position to decay, which exactly amounts to $\Re \{{s\}} <0$. (This derivation is from Landau's Course of Theoretical Physics Vol. I, section 25.)

A: Note first that the matrices $B$ and $C$ can be viewed as Hermitian matrices with positive real eigenvalues.
Suppose that $\det ( s^2I_n + sB+C) = 0$ for some $s\in\mathbb{C}$, then there is a complex unit vector $\bf{x}$ such that $(s^2 I_n + sB + C) \bf{x} = \bf{0}$. Then it follows by multiplying $\bf{\overline{x}^T}$ to the left that
$$
s^2 + s \beta+\gamma=0 \ \
$$
where $\beta=\bf{\overline{x}^T}\it B \bf{x}$, $\gamma=\bf{\overline{x}^T}\it C\bf{x}$.
Since $B$ and $C$ are positive definite, we have $\beta>0$, $\gamma>0$.
Then, such number $s\in\mathbb{C}$ is a root of the equation
$$
z^2 + \beta z + \gamma=0 \ \ \ (*).
$$
This equation has either one of two possibilities for the location of roots:
Case 1 (Both roots are not real: $\beta^2-4\gamma<0$)
By the quadratic formula, the real parts of the roots are $-\beta/2$.
Case 2 (It has real roots: $\beta^2-4\gamma\geq 0$)
We cannot have nonnegative real roots since $\beta>0$, $\gamma>0$. Thus, any real roots must be negative.
Therefore, any roots of the equation
$$
\det(s^2 I_n + sB + C)=0
$$
must have negative real parts.

It would be interesting to know how to derive such equation from an attempt to solve the equations of motion of an $n$- dimensional oscillator with some frictional force. It would be great if you can add the derivation in your question, or point us to a reference.


text:
Q: How to use Python keyboard module to persistently detect input? I'm trying to write a script so that when I press "0" I will get an output, but I want to work without restarting the script, and I haven't been successful using the keyboard module which I've seen as being the most commonly used for detecting key inputs in Python.
What I have so far is
import keyboard

def goto(linenum):
    global line
    line = linenum
line = 1

if line == 1:
    while True:
        if keyboard.is_pressed('0'):
            print('pressed 0')
            break
        goto(1)

What I tried doing was after the loop breaks to refer back to the beginning of the loop and try again from there, however the script ends after I press 0. If I remove the break then it constantly outputs "pressed 0", which is not what I want to happen.

A: You can use pynput to detect key input.
I would do something like this:
from pynput.keyboard import Key, Listener

def on_press(key):
    if str(key).replace("'","") == '0':
        print('pressed 0')

listener = Listener(on_press=on_press)
listener.start()

Once you start the listener, it will be always waiting for the key press and you can still add code after. In fact, with this example I recommend to add something after,  maybe an input() so the script won't close immediately.

A: I think there are a few problems going on here.

*

*goto is a pretty bad pattern to use and I don't think there's anything here to make your implementation work. It kinda sounds like you're going for some kind of recursion like approach here where when 0 is pressed, then it does some 'reset' and starts looping again. If that is the case you could do something like this:

def wait_for_zero():
    # wait for press here
    # Should add some sort of exit check too
    # 'reset' logic, if any here
    wait_for_zero()

*looping with a weak condition is pretty fast cycling and generally a bad idea without some time delay. This is mentioned in the documentation for keybaord. There also is an example in the documentation for keyboard to wait for a keypress: https://github.com/boppreh/keyboard#waiting-for-a-key-press-one-time


text:
Q: I lost my files under the libraries Music, Pictures and Videos after doing a windows refresh.How can I get them back? When I did a Windows refresh, I lost my files under the libraries Music, Pictures and Videos. How can I get them back? I am using Windows 8. I have my files in the library Documents, also other files are not missing.

A: Do you have a "Windows.old" directory ?
\windows.old\users\YOUROLDNAME\  find your lost stuff accordingly named
I don't do MS refreshes preferring restoring images, advice that isn't helping you at this moment.
Assuming you've enabled view hidden files, look for a \Windows.old directory, whether the refresh process is or isn't supposed to preserve your old settings, it's dangerous to presume anything about Windows.
If you've determined the Windows.old directory is't there AND You fear those files are deleted, turn off your computer right now since its drive activity is diminshing the chances of undeleting your lsot files.
You'll have an entirely new adventure of undeleting to undertake, and you'll need desk side help if those files are irreplaceable.


text:
Q: Creating a Pod, Cocoapods lint source_files issue I am creating a static library and I want to make a podspec so it can be included in other projects as well. To generate proper pod structure I used a command :
pod lib create <library_name>

It generated the following structure

*

*.podspec

*CHANGELOG.md

*Classes

*Project

*README.md

*Rakefile

*LICENSE

I created a new Xcode project inside the "projects" directory. I also added two files to the project called Test1.h and Test2.h and saved them inside classes  directory. Plus I added, header search path variable to xCode project settings, "../Classes/" so the classes & headers in other directories are are seen by compiler.
(Is there a way to have a group in Xcode such that all classes added to it, go to Classes directory, and compiler can see them automatically ?)
So now it looks like this

*

*.podspec

*CHANGELOG.md

*Classes

*

*Test1.h

*Test2.m

*Project

*

* (folder)

*.xcodeproj

*Tests

*Podfile

*README.md

*Rakefile

*LICENSE

In my podspec I have the following setting for source files

s.source_files = 'Classes/*.{h,m}'

But when I run :

pod spec lint .podspec

I get the following error :

*

*ERROR | The source_files pattern did not match any file.

  Analyzed 1 podspec.
[!] The spec did not pass validation.

What is the issue here? I have been stuck on this for hours.

A: This was also driving me nuts for 'hours'. I then discovered that the files and tags must be present in the source git repo. So make sure you push your code and your tags to the remote repo...
Update:
You can also do a 'pod lib lint' to lint the local files not the git repo.


text:
Q: How would I write an algorithm to find the greatest jump from number to number in a sequence? If your sequence is 4 2 1, the largest jump is from 4 to 2. If your sequence is 3 10 5 16 8 4 2 1, the largest jump is from 5 to 16.
I've made an algorithm however I'm not completely sure what I have done wrong (whever I haven't made the loop properly, set my variables correctly, or something else). I'm not sure what I need to set my index, BiggestDiff, or CurrentDiff too. I tried using a while loop to compare each number in my vector but I get zero (I'm assuming because I set BiggestDiff to zero)
If anyone can point me in the right direction, show me an example, or something else, that will be greatly appreciated.
Here is my code below
int findBiggestDiff(std::vector<int> sequence)
{
  int index = 0;
  int BiggestDiff = 0 ;
  int CurrentDiff = BiggestDiff;
  CurrentDiff = std::abs(sequence[index] - sequence[index + 1]);
  while (index < sequence.size())
  {
    if (CurrentDiff > BiggestDiff)
    {
      BiggestDiff = CurrentDiff;
    }

    return index;
  }
}

A: Try this:
{
    int indexOfBiggestJump = 0;
    int BiggestDiff = 0 ;
    int CurrentDiff = BiggestDiff;

    for(int i = 0; i < sequence.size() - 1; i++) {
        CurrentDiff = std::abs(sequence[i] - sequence[i + 1]);
        if (CurrentDiff > BiggestDiff)
        {
            BiggestDiff = CurrentDiff;
            indexOfBiggestJump = i;
        }
    }
    return indexOfBiggestJump;
}

There are several errors in your code.

*

*your return index literally does nothing, only returns index (which will be 0) always.

*you are not saving the index of the biggest jump anywhere.

*if you are looking positions i and i + 1, you must go until sequence.size() - 1, otherwise you will look out of the bounds of sequence.

A: You aren't recalculating CurrentDiff at all. Also, your return statement in the in the wrong spot. You can do something like this (not tested)
int findLargest( const std::vector<int> &sequence ) {
  if ( sequence.size() < 2 ) return -1; // if there's not at least two elements, there's nothing valid.
  int index = 0;
  int biggestIndex = -1;
  int biggestDiff = -1;

  while (index < sequence.size() - 1) // -1 so that the +1 below doesn't go out of range
  {
    // get the current difference
    int currentDiff = std::abs(sequence[index] - sequence[index + 1]);
    if (currentDiff > biggestDiff)
    {
       // update stats
       biggestIndex = index;
       biggestDiff = currentDiff;
    }
    ++index;
  }
  return biggestIndex
}

int main() {
   //…
   int index = findLargest( sequence );
   if ( index != -1 ) {
       std::cout << "Biggest difference was between " << sequence[index] << " and " << sequence[index+1];
   }
}


text:
Q: Nifi ConvertAvroToJSON--Number types error I'm trying to read data from 'Oracle' and populate the same to 'mysql' database.
'ExecuteSQL' - >'ConvertAvroToJSON' - >'ConvertJSONToSQL' - >'PutSQL'

:
Figure 1 shows the unconverted data in ConvertAvroToJSON.

Figure 2 shows the data after the conversion.

The data type after conversion is now in the wrong format.

A: I have worked with ConvertJsonToAvro and ConverAvroToJson processors and I often have collided with some strange warnings or errors. E.g. ConvertJsonToAvro can show you warning like "Could not parse incoming data" and that's all. Nothing else.
After that I have been starting to use ConvertRecord Processor. I need to convert json to avro, so I set JsonTreeReader in Reader property and AvroRecordSetWriter in Writer property.
My advice: try to use ConvertRecord processor. Maybe you will see more detailed information about parsing and errors.


text:
Q: GCC's __builtin_expect assembly dump seems to always go down branch Ok so I have been playing around with __builtin_expect a bit and I just created a simple test program that I put through godbolt.org to get the assembly output (https://godbolt.org/g/FZo5fP)
int main(){
  volatile int num = 4;
  //if(num == 4){
  if(__builtin_expect(num,4)){
    return num*800;
  }else{
    return num*500;
  }
}

When compiled with -O1 or greater produces:
main:
        mov     DWORD PTR [rsp-4], 4
        mov     eax, DWORD PTR [rsp-4]
        test    eax, eax
        mov     eax, DWORD PTR [rsp-4]
        je      .L2
        imul    eax, eax, 800
        ret
.L2:
        imul    eax, eax, 500
        ret

It seems as though the part that says test eax,eax would always set zero flag to 0 unless num was equal to 0. So it seems as though if num is not set to 0 it will always multiply by 800 instead of only when num=4. My understanding of __builtin_expect is that while it will  optimize to assume that it will go to that branch it should still be comparing to ensure that it should use that branch.
If I switch __builtin_expect to just == it produces
main:
        mov     DWORD PTR [rsp-4], 2
        mov     eax, DWORD PTR [rsp-4]
        cmp     eax, 4
        mov     eax, DWORD PTR [rsp-4]
        je      .L5
        imul    eax, eax, 500
        ret
.L5:
        imul    eax, eax, 800
        ret

Which makes much more sense to me in that it actually compares against 4. Is my understanding of __builtin_expect wrong? Does __builtin_expect actually only work with 0 or 1 even though it specifies that it takes a long?

A: From the docs:

The return value is the value of exp, which should be an integral expression.

So the logical semantics of:
if(__builtin_expect(num,4)) { ... }

are:
if (num) { ... }

which is different than what you say you want. If you want to write that you expect that num == 4 to be very likely, you want:
if (__builtin_expect(num == 4, 1)) { ... }

Commonly, you'd just wrap these in macros:
#define likely(expr)   __builtin_expect((expr), 1)
#define unlikely(expr) __builtin_expect((expr), 0)

and then the usage becomes more natural:
if (likely(num == 4)) { ... }


text:
Q: How can I create bind a list of elements as a group without ng-repeat? I've been trying to learn Angular but hit a small blocker. My markup has a list of DIVs which when clicked get toggled (a new class). This is a static list of options and I would like to avoid the ng-repeat directive.

Germany

Poland

Sweden

Japan

    <button type="button" ng-click="selected = []">Reset</button>

I would like to bind it to an array of selections. When clicked, the item's id should be added to the array and when unselected, it should be removed. The existence of the item's id in the selection array defines whether it should have the "active" class.
Below is how I've done it in Angular but this means that I cannot use my static list of DIVs but use the ng-repeat with the JSON. I've toyed around with this and got it correctly bound to the selected array. Clicking the button correctly resets the active class showing that the binding works.
Can I still accomplish this without going down the JSON + ng-repeat way? An example pointing me to this would be nice. Thank you
Here's the CSS:
.item {
    border-color: #ddd;
    background-color: #fff;
    color: #444;
    position: relative;
    z-index: 2;
    display: block;
    margin: -1px;
    padding: 16px;
    border-width: 1px;
    border-style: solid;
    font-size: 16px;
}

.item.active {
    border-color: #ccc;
    background-color: #d9d9d9;
}

Here's the JS:
var SampleApp;
(function (SampleApp) {

    var app = angular.module('sampleApp', []);
    app.controller('MainCtrl', function ($scope) {
        $scope.selected = [];

        $scope.clicked = function (member) {
            var index = $scope.selected.indexOf(member.name);
            if (index > -1) {
                $scope.selected.splice(index, 1);
                member.selected = false;
            } else {
                $scope.selected.push(member.name);
                member.selected = true;
            }
            console.log($scope.selected);
        }
        $scope.items = [{
            name: "item1"
        }, {
            name: "item2"
        }, {
            name: "item3"
        }, {
            name: "item4"
        }, {
            name: "item5"
        }];
    });

})(SampleApp || (SampleApp = {}));

Here's the markup:

{{ item.name }}

    <button type="button" ng-click="selected = []">Reset</button>

A:
= 0 }">Germany

and repeat the same pattern for the other countries.
In the controller:
$scope.toggle = function(country) {
    var index = $scope.selected.indexOf(country);
    if (index >= 0) {
        $scope.selected.splice(index, 1);
    } else {
        $scope.selected.push(country);
    }
};

Not sure why you want to avoid ng-repeat though. Using it would avoid repeating the same code again and again in the view, and thus reduce the risk of introducing a bug.


text:
Q: how to stop data being skipped when recording over long intervals? I'm using an arduino to log the temperature from ten PT100s in real time.
My code works fine over short intervals (e.g. 10 minutes), but over longer intervals (e.g. 2-7 hours), specifically on the 63rd temperature logged, Matlab doesn't pick up the full string from the serial print  It doesn't matter what sample rate i set it at (I have tried 2.5 mins, 1 min and 5 mins), it always stops working at the 63rd piece of data - specifically the y variable from fscanf only has 2 values in it - one normal looking temperature value and 2.
I changed the code so that when the y string isn't the expected 10 temperature values, it just plots 10 NaN values and keeps going. From this point onwards, it fails to log 10 temperature values exactly once every 4 samples, no matter what I set the sample rate to.
clear all;
clc;
delete(instrfindall); %pre-emptively close all ports
b = serial('COM7','BaudRate',1000000); % COM is the COM port of the Arduino
 %flush input buffer
flushinput(b);

fopen(b);  % initiate arduino communication

%% Create a figure window to monitor the live data
Tmax = 24*60*60; % Total time for data collection (s)
figure,
grid on,
xlabel ('Time (s)'), ylabel('Tempeature (K)'),
%axis([0 Tmax+1]),

%% Read and plot the data from Arduino
Ts = 150; % Sampling time (s)
ii = 0;
dataa = 0;
datab = 0;
t = 0;
tic % Start timer
mData = [];
while toc <= Tmax
    ii = ii + 1;
    %% Read buffer data

    datab = fscanf(b);
    y = strsplit(datab, ',')
    if(length(str2double(y))<10)
        disp("Output length mismatch");
        y = NaN(10,1);
        t1(ii,1) = str2double(y(1));
        t2(ii,1) = str2double(y(2));
        t3(ii,1) = str2double(y(3));
        t4(ii,1) = str2double(y(4));
        t5(ii,1) = str2double(y(5));
        t6(ii,1) = str2double(y(6));
        t7(ii,1) = str2double(y(7));
        t8(ii,1) = str2double(y(8));
        t9(ii,1) = str2double(y(9));
        t10(ii,1) = str2double(y(10));
    else
        t1(ii,1) = str2double(y(1));
        t2(ii,1) = str2double(y(2));
        t3(ii,1) = str2double(y(3));
        t4(ii,1) = str2double(y(4));
        t5(ii,1) = str2double(y(5));
        t6(ii,1) = str2double(y(6));
        t7(ii,1) = str2double(y(7));
        t8(ii,1) = str2double(y(8));
        t9(ii,1) = str2double(y(9));
        t10(ii,1) = str2double(y(10));
        %sTemp = smooth(data,25);
        %% Read time stamp
        % If reading faster than sampling rate, force sampling time.
        % If reading slower than sampling rate, nothing can be done. Consider
        % decreasing the set sampling time Ts

        t(ii) = toc;
        if ii > 1
            T = toc - t(ii-1);
            while T < Ts
                T = toc - t(ii-1);
            end
        end
        t(ii) = toc;
        grid on
        grid minor
        %% Plot live data
        if ii > 1
            x = [t(ii-1) t(ii)];
            %the two values output by the arduino when the sensor is not
            %attached are 38.98 and 1261.79 - changed these values to 0 using
            %logic
            y1 = [(t1(ii-1)*(t1(ii-1)~=30.98)*(t1(ii-1)~=1261.79)) (t1(ii)*(t1(ii)~=30.98)*(t1(ii)~=1261.79))];
            y2 = [(t2(ii-1)*(t2(ii-1)~=30.98)*(t2(ii-1)~=1261.79)) (t2(ii)*(t2(ii)~=30.98)*(t2(ii)~=1261.79))];
            y3 = [(t3(ii-1)*(t3(ii-1)~=30.98)*(t3(ii-1)~=1261.79)) (t3(ii)*(t3(ii)~=30.98)*(t3(ii)~=1261.79))];
            y4 = [(t4(ii-1)*(t4(ii-1)~=30.98)*(t4(ii-1)~=1261.79)) (t4(ii)*(t4(ii)~=30.98)*(t4(ii)~=1261.79))];
            y5 = [(t5(ii-1)*(t5(ii-1)~=30.98)*(t5(ii-1)~=1261.79)) (t5(ii)*(t5(ii)~=30.98)*(t5(ii)~=1261.79))];
            y6 = [(t6(ii-1)*(t6(ii-1)~=30.98)*(t6(ii-1)~=1261.79)) (t6(ii)*(t6(ii)~=30.98)*(t6(ii)~=1261.79))];
            y7 = [(t7(ii-1)*(t7(ii-1)~=30.98)*(t7(ii-1)~=1261.79)) (t7(ii)*(t7(ii)~=30.98)*(t7(ii)~=1261.79))];
            y8 = [(t8(ii-1)*(t8(ii-1)~=30.98)*(t8(ii-1)~=1261.79)) (t8(ii)*(t8(ii)~=30.98)*(t8(ii)~=1261.79))];
            y9 = [(t9(ii-1)*(t9(ii-1)~=30.98)*(t9(ii-1)~=1261.79)) (t9(ii)*(t9(ii)~=30.98)*(t9(ii)~=1261.79))];
            y10 = [(t10(ii-1)*(t10(ii-1)~=30.98)*(t10(ii-1)~=1261.79)) (t10(ii)*(t10(ii)~=30.98)*(t10(ii)~=1261.79))];
            %replace zero values with nan so they will not be plotted
            y1(y1==0) = nan;
            y2(y2==0) = nan;
            y3(y3==0) = nan;
            y4(y4==0) = nan;
            y5(y5==0) = nan;
            y6(y6==0) = nan;
            y7(y7==0) = nan;
            y8(y8==0) = nan;
            y9(y9==0) = nan;
            y10(y10==0) = nan;
            line(x, y1, 'Color', 'red')
            line(x, y2, 'Color', 'blue')
            line(x, y3, 'Color', 'black')
            line(x, y4, 'Color', 'magenta')
            line(x, y5, 'Color', 'green')
            line(x, y6, 'Color', 'blue')
            line(x, y7, 'Color', 'red')
            line(x, y8, 'Color', 'cyan')
            line(x, y9, 'Color', 'black')
            line(x, y10, 'Color', 'magenta')
            legend ('T1','T2','T3','T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10')
            drawnow
        end
    end
end
fclose(b);

The actual results are below. Any help is really appreciated!
(https://www.mathworks.com/matlabcentral/answers/uploaded_files/235007/Capture.png)
(https://www.mathworks.com/matlabcentral/answers/uploaded_files/235006/Capture1.png)
(edit: the images are from mathworks because I posted the same question there last week but didn't receive any responses)

#include <Adafruit_MAX31865.h>
#include<SPI.h>
#include <Wire.h>

// Use software SPI: CS, DI, DO, CLK
//Adafruit_MAX31865 max_1 = Adafruit_MAX31865(A0,12,11,13);
//Adafruit_MAX31865 max_2 = Adafruit_MAX31865(2,12,11,13);
//Adafruit_MAX31865 max_3 = Adafruit_MAX31865(3,12,11,13);
//Adafruit_MAX31865 max_4 = Adafruit_MAX31865(4,12,11,13);
//Adafruit_MAX31865 max_5 = Adafruit_MAX31865(5,12,11,13);
//Adafruit_MAX31865 max_6 = Adafruit_MAX31865(6,12,11,13);
//Adafruit_MAX31865 max_7 = Adafruit_MAX31865(7,12,11,13);
//Adafruit_MAX31865 max_8 = Adafruit_MAX31865(8,12,11,13);
//Adafruit_MAX31865 max_9 = Adafruit_MAX31865(9,12,11,13);
//Adafruit_MAX31865 max_10 = Adafruit_MAX31865(10,12,11,13);

// use hardware SPI, just pass in the CS pin
Adafruit_MAX31865 max_1 = Adafruit_MAX31865(A0);
Adafruit_MAX31865 max_2 = Adafruit_MAX31865(2);
Adafruit_MAX31865 max_3 = Adafruit_MAX31865(3);
Adafruit_MAX31865 max_4 = Adafruit_MAX31865(4);
Adafruit_MAX31865 max_5 = Adafruit_MAX31865(5);
Adafruit_MAX31865 max_6 = Adafruit_MAX31865(6);
Adafruit_MAX31865 max_7 = Adafruit_MAX31865(7);
Adafruit_MAX31865 max_8 = Adafruit_MAX31865(8);
Adafruit_MAX31865 max_9 = Adafruit_MAX31865(9);
Adafruit_MAX31865 max_10 = Adafruit_MAX31865(10);

// The value of the Rref resistor. Use 430.0 for PT100 and 4300.0 for PT1000
#define RREF      430.0
// The 'nominal' 0-degrees-C resistance of the sensor
// 100.0 for PT100, 1000.0 for PT1000
#define RNOMINAL  100.0
float kelvin1;
float kelvin2;
float kelvin3;
float kelvin4;
float kelvin5;
float kelvin6;
float kelvin7;
float kelvin8;
float kelvin9;
float kelvin10;

void setup() {
  Serial.begin(115200);
  Wire.begin();

  //Serial.println("Adafruit MAX31865 PT100 Sensor Test!");
  max_1.begin(MAX31865_4WIRE);  // set to 2WIRE or 4WIRE as necessary
  max_2.begin(MAX31865_4WIRE);
  max_3.begin(MAX31865_4WIRE);
  max_4.begin(MAX31865_4WIRE);
  max_5.begin(MAX31865_4WIRE);
  max_6.begin(MAX31865_4WIRE);
  max_7.begin(MAX31865_4WIRE);
  max_8.begin(MAX31865_4WIRE);
  max_9.begin(MAX31865_4WIRE);
  max_10.begin(MAX31865_4WIRE);
}

void loop() {

  uint16_t rtd1 = max_1.readRTD();
  uint16_t rtd2 = max_2.readRTD();
  uint16_t rtd3 = max_3.readRTD();
  uint16_t rtd4 = max_4.readRTD();
  uint16_t rtd5 = max_5.readRTD();
  uint16_t rtd6 = max_6.readRTD();
  uint16_t rtd7 = max_7.readRTD();
  uint16_t rtd8 = max_8.readRTD();
  uint16_t rtd9 = max_9.readRTD();
  uint16_t rtd10 = max_10.readRTD();

  //  Serial.print("RTD value: "); Serial.println(rtd);
  float ratio1 = rtd1;
  ratio1 /= 32768;
  float ratio2 = rtd2;
    ratio2 /= 32768;
    float ratio3 = rtd3;
    ratio3 /= 32768;
    float ratio4 = rtd4;
    ratio4 /= 32768;
    float ratio5 = rtd5;
    ratio5 /= 32768;
    float ratio6 = rtd6;
    ratio6 /= 32768;
    float ratio7 = rtd7;
    ratio7 /= 32768;
    float ratio8 = rtd8;
    ratio8 /= 32768;
    float ratio9 = rtd9;
    ratio9 /= 32768;
    float ratio10 = rtd10;
    ratio10 /= 32768;

  kelvin1 = (max_1.temperature(RNOMINAL, RREF)) + 273;
  kelvin2 = (max_2.temperature(RNOMINAL, RREF))+273;
    kelvin3 = (max_3.temperature(RNOMINAL, RREF))+273;
    kelvin4 = (max_4.temperature(RNOMINAL, RREF))+273;
    kelvin5 = (max_5.temperature(RNOMINAL, RREF))+273;
    kelvin6 = (max_6.temperature(RNOMINAL, RREF))+273;
    kelvin7 = (max_7.temperature(RNOMINAL, RREF))+273;
    kelvin8 = (max_8.temperature(RNOMINAL, RREF))+273;
    kelvin9 = (max_9.temperature(RNOMINAL, RREF))+273;
    kelvin10 = (max_10.temperature(RNOMINAL, RREF))+273;

  //Serial.print("Ratio = "); Serial.println(ratio1,8);
  Serial.print(kelvin1);
  Serial.print(", ");
  Serial.print(kelvin2);
    Serial.print(", ");
    Serial.print(kelvin3);
    Serial.print(", ");
    Serial.print(kelvin4);
    Serial.print(", ");
    Serial.print(kelvin5);
    Serial.print(", ");
    Serial.print(kelvin6);
    Serial.print(", ");
    Serial.print(kelvin7);
    Serial.print(", ");
    Serial.print(kelvin8);
    Serial.print(", ");
    Serial.print(kelvin9);
    Serial.print(", ");
    Serial.print(kelvin10);
    Serial.print(", ");

  Serial.println();

  /*
      // Check and print any faults
      uint8_t fault = max_1.readFault();
      if (fault) {
        Serial.print("Fault 0x"); Serial.println(fault, HEX);
        if (fault & MAX31865_FAULT_HIGHTHRESH) {
          Serial.println("RTD High Threshold");
        }
        if (fault & MAX31865_FAULT_LOWTHRESH) {
          Serial.println("RTD Low Threshold");
        }
        if (fault & MAX31865_FAULT_REFINLOW) {
          Serial.println("REFIN- > 0.85 x Bias");
        }
        if (fault & MAX31865_FAULT_REFINHIGH) {
          Serial.println("REFIN- < 0.85 x Bias - FORCE- open");
        }
        if (fault & MAX31865_FAULT_RTDINLOW) {
          Serial.println("RTDIN- < 0.85 x Bias - FORCE- open");
        }
        if (fault & MAX31865_FAULT_OVUV) {
          Serial.println("Under/Over voltage");
        }
        max_1.clearFault();
      }
  */
  delay(50);

}

A: So, I checked out @Wolfie's suggestion (and found that an Arduino nano's buffer is 64 bits, fitting this theory) and added
flushinput(b);

after reading the values from the serial input, to flush the input buffer. Just tested it out and it works perfectly - thanks for your help!


text:
Q: Nesting Forms for Many to Many I have a model, Post, which has a many to many relationship with another model, Tag:
class Post < ActiveRecord::Base
  attr_accessible :body, :section_id, :solved, :subject, :tag_ids, :user_id
  belongs_to :user
  belongs_to :section
  has_and_belongs_to_many :tags
  has_many :comments

Here's Tag:
class Tag < ActiveRecord::Base
  attr_accessible :subject, :post_ids
  has_and_belongs_to_many :posts

  validates(:subject, presence: true, :length => { minimum: 3, maximum: 15})
end

When I'm creating a Post, I need to allow the user to add Tags to the post at creation in the same form as the Title and Body of a Post. The tags are pre-created and will never be created within a post. I don't know how to do this. I want to use form_for so I can easily populate the fields of Post, but I don't know how to incorporate Tags into this and send it to the controller. Any suggestions? Here is what my controller is sending to the view:
@post = Post.new
@tags = Tag.all

A: you'll need a field for user to input tags in the form, such as
<input type="text" id="tags" name="tags" />

when the request is posted to the controller, parsing the tags text,
tags = params["tags"].split(/\s+/) //assuming tags are separated by spaces
tags.each do |t|
  tag = Tag.find_or_create_by_name(t)
  your_post_object.tags << tag
end

and finally, don't forget to call save on your_post_object


text:
Q: Azure iot edge / built-in metrics / proxy I need to send the build-in metrics of IoT edge from "the metrics collector module" in the gateway to "Log analytics" in the Cloud
https://learn.microsoft.com/en-us/azure/iot-edge/how-to-collect-and-transport-metrics
there's a proxy between edge and Azure
with the UploadTarget=IoTMessage it is possible to go through the proxy with the telemetry messages : metrics collector->edgehub->PROXY->iothub->function->log analytics
BUT
Is it possible to send through a proxy with the configuration UploadTarget=AzureMonitor ?
metrics collector->PROXY->log analytics
thanks

A: This is covered in the documentation you linked. See: https://learn.microsoft.com/azure/iot-edge/how-to-collect-and-transport-metrics?view=iotedge-2020-11&tabs=iothub#proxy-considerations


text:
Q: How to always have empty values in the end of a sorting I have a list of string values. I use a comparator to sort them by a specific order as follow
public static final List<String> CUSTOM_LIST = Arrays.asList("Red", "Green", "Blue");
comparator = new Comparator<String>(){
             @Override
             public int compare(final String o1, final String o2){
                   return Integer.valueOf(CUSTOM_LIST.indexOf(o1))
                   .compareTo(Integer.valueOf(CUSTOM_LIST.indexOf(o2)));
              }
         };

So to compare I do
Collections.sort(listToSort,comparator);

Or for reverse sorting
Collections.sort(listToSort,Collections.reverseOrder(comparator));

Now my list have empty values and I want to have them always in the end. How do I achieve that ?

A: The compare interface return a number that marks the difference between both objects. Note that since will always want the empty values to go at the end we must ensure that the integer value returned is bigger (or smaller) than any other that way all empty values will be pulled to a corner of the Collection.
 comparator = new Comparator<String>(){
                @Override
                public int compare(final String o1, final String o2){
                    if(o1.isEmpty()) return Integer.MAX_VALUE;
                    else if (o2.isEmpty()) return Integer.MIN_VALUE;

                    else return Integer.valueOf(ModuleConstants.CUSTOM_LIST.indexOf(o1))
                                        .compareTo(
                           Integer.valueOf(ModuleConstants.CUSTOM_LIST.indexOf(o2)));
                }
            };


text:
Q: Server refused our key - Putty trying to connect to a new VPS server I am using Putty to connect to my VPS servers.
I have created a new VPS server (Hetzner cloud) and have chosen the existing SSH key, as a security measure.
When trying to connect to a newly created server over SSH (for the first time), Putty prints out "Server refused our key".
I chose the same SSH key that I had created 4 years ago - the one I use all the time to connect to my existing VPS servers. I do not have an idea why is not allowing me to
connect to a new server with absolutely the same key and same settings that I use to connect to my existing VPS servers without any problem.
Does someone have an idea what could I be missing?

A: The problem somehow was in Putty application itself - I've had a 0.73 version and after an update to 0.78 I finally managed to connect to my new VPS server.


text:
Q: How to prepare data to analyze two values simultaneously as one as a newbie in statistics I'm having trouble with preparing my data.
I have data where a measure is performed on left and right side. When comparing group means I need to take simultaneously both measurement from left and right.
So for example I have:
Case     Side_left    SIde_right
When analyzing means should be n=2xCases, so if I have 15 cases, my means is computed from 30 measurements, 15 from left and 15 from right.
Simply creating averaged from left and right won't do the trick, because  SD's are different, Also if I have missing value from one side, for 15 cases I'd have 29 measurements. By creating means first this information is omited. Is there a way to do it SPSS or any other software or manual solution.

A: I can see three possible approaches for dealing with this.
1. The "just focus on one side" approach
If you believe that the two measures are really closely related, and can produce a reasonably high correlation coefficient to back this up, then you could use data from only one side (whichever side has the least missing data).
I've done work in the past using eye-tracking where we only analyse movements with the right eye (right tends to be the dominant one). For most of the phenomena I've studied, I've had no reason to believe that the left eye will do anything substantively different, so I don't analyse that data (in reality, I don't collect it... Binocular eye-tracking is a hassle!)
2. The "just take an average and live with some missing data" approach
This is relatively similar to the first approach really. If you don't think the two sides are going to be all that different then just average them. Yes, the averaging will add a little noise, but if the effect you're interested in is robust enough then it probably won't make a difference.
3. The "take a sledgehammer to crack a nut" approach
Use PCA/FA to reduce the two sides, which we believe are going to be very closely related, to a single score. This score will probably not be on the same scale as the raw measurements, so you lose some interpretability.
As with 2, you'll lose some cases where there's missing data, but, really, I'm not sure there's an approach out there (short of imputation) where you won't suffer this problem.
Personally, as long as the correlation coefficient was good then I'd probably just do 1.


text:
Q: Can´t find "window" function in Spark Structured Streaming I´m coding a small example in Spark Structured Streaming where I´m trying to process the output of the netstatcommand and can´t figure out how to invoke the windowfunction.
These are the relevant lines of my build.sbt:
scalaVersion := "2.11.4"
scalacOptions += "-target:jvm-1.8"

libraryDependencies ++= {

  val sparkVer = "2.3.0"
  Seq(
    "org.apache.spark" %% "spark-streaming" % sparkVer % "provided",
    "org.apache.spark" %% "spark-streaming-kafka-0-8" % sparkVer % "provided",
    "org.apache.spark" %% "spark-core" % sparkVer % "provided" withSources(),
    "org.apache.spark" %% "spark-hive" % sparkVer % "provided",
  )
}

And the code:
case class NetEntry(val timeStamp: java.sql.Timestamp, val sourceHost: String, val targetHost: String, val status: String)

def convertToNetEntry(x: String): NetEntry = {
    // tcp        0      0 eselivpi14:icl-twobase1 eselivpi149.int.e:48442 TIME_WAIT
   val array = x.replaceAll("\\s+"," ").split(" ").slice(3,6)
   NetEntry(java.sql.Timestamp.valueOf(LocalDateTime.now()), array(0),array(1),array(2))
}

def main(args: Array[String]) {

    // Initialize spark context
    val spark: SparkSession = SparkSession.builder.appName("StructuredNetworkWordCount").getOrCreate()
    spark.sparkContext.setLogLevel("ERROR")

    val lines = spark.readStream
    .format("socket")
    .option("host", args(0))
    .option("port", args(1).toInt)
    .load()

    import spark.implicits._
    val df = lines.as[String].map(x => convertToNetEntry(x))

    val wordsArr: Dataset[NetEntry] = df.as[NetEntry]
    wordsArr.printSchema()

    // Never get past this point
    val windowColumn = window($"timestamp", "10 minutes", "5 minutes")

    val windowedCounts = wordsArr.groupBy( windowColumn, $"targetHost").count()

    val query = windowedCounts.writeStream.outputMode("complete").format("console").start()
    query.awaitTermination()
}

I have with Spark 2.1, 2,2 and 2.3 with the same results. What is really bizarre is that, I have a Spark Cluster, I log in the Spark Shell and copy all the lines... and it works! Any idea of what am I doing wrong?
The error at compilation time:
[error] C:\code_legacy\edos-dp-mediation-spark-consumer\src\main\scala\com\ericsson\streaming\structured\StructuredStreamingMain.scala:39: not found: value window
[error]     val windowColumn = window($"timestamp", "10 minutes", "5 minutes")
[error]                        ^
[warn] 5 warnings found
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 19 s, completed 16-mar-2018 20:13:40

Update: To make things weirder, I have check the API docs and I could not found a valid reference here either:
https://spark.apache.org/docs/2.3.0/api/scala/index.html#org.apache.spark.sql.SparkSession$implicits$

A: You need to import the window function to compile it, which is already imported in spark-shell.
Add this import statement:
import org.apache.spark.sql.functions.window


text:
Q: Confusion on the proof and meaning of negative binomial random variables Going through the book Introduction to Probability, Statistics and Random Processes, I stumbled across an interpretation of negative binomial random variables and its proof.
Suppose I have a coin with $P(H) = p$. I toss the coin n times until I see m heads. We define X to be the total number of coin tosses in this experiment. Then X is a negative random variable with parameters m and p.
$$X \sim Negative\ Binomial(m,p)$$
Deriving the PMF of a Negative Binomial Random Variable.
Let A be the event we get m heads. Notice that $A = B\cap C$ where B is the event we get a $m-1$ heads in the first k-1 trials and C is the event we get a heads on the $k^{th}$ trial. Since each coin toss is independent,
$$P(A) = P(B\cap C) = P(B)P(C)$$
$$P(C) = p$$
Then the proof finds P(B) by using the binomial distribution formula.
$$P(B) = {k-1\choose m-1}p^{m-1}(1-p)^{(k-1)-(m-1)} = {k-1\choose m-1}p^{m-1}(1-p)^{k-m}$$
Then P(A) is
$$P(A) = P(B)P(C) = {k-1\choose m-1}p^{m}(1-p)^{k-m}$$
I'm not sure how the binomial coefficient ${k-1\choose m-1}$ makes sense. Instead of choosing $m-1$ heads from $k-1$ trials, can't we just choose $m$ heads from $k$ trials such that
$$P(A) = {k\choose m}p^m(1-p)^{k-m}$$
What makes this different from the regular binomial distribution? Looking online, people said that the negative binomial distribution counts the number of failures fixed and the number of trials is not fixed. In the formula for the Negative Binomial distribution I don't see how it's counting failures?

A: There are at least four formulations of the negative binomial distribution if you consider in your word question:

*

*Are you counting tosses or tails until you get $m$ heads? I.e. is the minimum possible value $m$ or $0$?

*Does heads count as a failure (you go on until $m$ failures) or is tails a failure (you go on until $n$ successes? Which has probability $p$?

If you only count tails, then in a sense you are counting failures rather than attempts.  Either way, there is no limit to the number of tails you may see before the $m$th head.  So if tails are a failure then there is no limit to the possible number of failures.
Suppose, as you seem to be, you are counting tosses and the probability of a head is $p$.  Then for the $k$th toss to be the $m$th head you need $m-1$ of the first $k-1$ tosses to be heads and the $k$th toss to be a head.  This has probability ${k-1 \choose m-1}p^{m-1}(1-p)^{(k-1)-(m-1)} \times p$ which is $${k-1 \choose m-1}p^{m}(1-p)^{k - m}$$
and if you sum this from $k=m$ to $\infty$ you should get $1$
Wikipedia has a slightly different formulation but essentially the same result


text:
Q: Dynamic sql and case statement issue i have one dynamic sql where i use case with variable but it is giving error.
here is the snip.
DECLARE @SQL VARCHAR(MAX)
DECLARE @isrepaired INT

SET @isrepaired=1
SET @SQL=@SQL+'SELECT *
                FROM   (SELECT Row_number()
                               OVER (
                               ORDER BY [bbajobs].[customername] ) AS
                               RowNumber,
                               [bbajobs].[jid],
                               ourfeedback.rating,
                               ourfeedback.adddates as [Add Dates]
                   ,Repaired=
                case '+CAST(@isrepaired as varchar)+' when 1 then ''Yes''
                case '+CAST(@isrepaired as varchar)+' when 0 then ''No''
                END
                        FROM  dbo.bbajobs '

i am sending value for isrepaired at runtime. cant we write the statement like this way? please guide me where to fix. thanks
UPDATE
dynamic sql was my requirement so guide me how to do it in dynamic sql
DECLARE @SQL VARCHAR(MAX)
DECLARE @isrepaired INT

SET @isrepaired=1
SET @SQL=@SQL+'SELECT *
                FROM   (SELECT Row_number()
                               OVER (
                               ORDER BY [bbajobs].[customername] ) AS
                               RowNumber,
                               [bbajobs].[jid],
                               ourfeedback.rating,
                               ourfeedback.adddates as [Add Dates]
                   ,Repaired=
                case '+CAST(@isrepaired as varchar)+' when 1 then ''Yes''
                '+CAST(@isrepaired as varchar)+' when 0 then ''No''
                END
                        FROM  dbo.bbajobs '

my dynamic sql look like
SELECT *
                FROM   (SELECT Row_number()
                               OVER (
                               ORDER BY [bbajobs].[customername] ) AS
                               RowNumber,
                               [bbajobs].[jid],
                               ourfeedback.rating,
                               ourfeedback.adddates as [Add Dates]
                   ,Repaired=
                case 1 when 1 then ''Yes''
                when 0 then ''No''
                END
                        FROM  dbo.bbajobs '

A: There is no obvious need for dynamic SQL here. Just use
SELECT *
FROM   (SELECT Row_number() OVER ( ORDER BY [bbajobs].[customername] ) AS RowNumber,
               [bbajobs].[jid],
               ourfeedback.rating,
               ourfeedback.adddates                                    AS [Add Dates],
               Repaired= CASE @isrepaired
                           WHEN 1 THEN 'Yes'
                           WHEN 0 THEN 'No'
                         END
        FROM   dbo.bbajobs) AS T

If you do need dynamic SQL for reasons not shown then you should at least first start with a working non dynamic query then convert it.
You are missing a table alias for the derived table and case ... case ... end is not valid.
The semantics of the query seem very odd though. Why is the repaired status derived exclusively from the @isrepaired variable for all rows?

A: Your syntax is wrong.  You have two CASE 's.  It should be WHEN.
http://technet.microsoft.com/en-us/library/ms181765.aspx
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ]
     [ ELSE else_result_expression ]
END

Also, use this instruction to see the code being generated dynamically in a XML window.  Cut and paste into another window to debug.  That way you can verify the syntax.
-- Cool instruction ?
SELECT @SQL  as [processing-instruction(TSQL)] FOR XML PATH


text:
Q: Counting the posts of a loop (WP_Query)? I tried this way to display NO of post:
<?php
 $news_2 = new WP_Query( array ('post_type'=> 'jobs','posts_per_page'=> '10' , 'meta_key' => 'status_for_jobs','meta_value' => '1') );
  if ( $news_2->have_posts() ) { while ( $news_2->have_posts() ) { $news_2->the_post();

  $count = $news_2->post_count;

  ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php } } ?> <?php wp_reset_query(); ?>

if the NO of post = 0 i need to display this :-
<?php
 $news_2 = new WP_Query( array ('post_type'=> 'jobs','posts_per_page'=> '10' , 'meta_key' => 'status_for_jobs','meta_value' => '1') );
  if ( $news_2->have_posts() ) { while ( $news_2->have_posts() ) { $news_2->the_post();

  $count = $news_2->post_count;

  if ($count  == '0') {

  ?>

No Post

  <?php
  } else {
  ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php  }  ?>

    <?php } } ?> <?php wp_reset_query(); ?>

But instead of the total of posts, I not getting any thing.
Any suggestions to fix this?

A: You don't need to count the posts to show something different if no posts are found. You can just use the else part of your if($news_2->have_posts()) check.
$news_2 = new WP_Query( array ('post_type'=> 'jobs','posts_per_page'=> '10' , 'meta_key' => 'status_for_jobs','meta_value' => '1') );

if ( $news_2->have_posts() ) {

    while ( $news_2->have_posts() ) {

        $news_2->the_post();

    ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php  }

    } else { ?>

No Post

    <?php } ?>

<?php wp_reset_query(); ?>

But if you truly need to count the number of posts returned, you can use
$count = count( $news_2->posts );

A: Some additional information, no need to count the posts again, because WP_Query already did that for you. To clarify this, some information from the Class Reference of WP_Query as found in the »Properties« section:

$post_count
  The number of posts being displayed.
$found_posts
  The total number of posts found matching the current query parameters

What this means is

*

*$post_count won't give you the total post count. It will most likely give you the number of posts you've defined with the post_per_page parameter, unless you've fewer posts than that or you're on the last page and there are only fewer posts left.

*$found_posts can be used to get the total number of post related to a specific query. So there is no need to count them again.

In your case you can get the total count into your $count variable like this:
$count = $news_2->found_posts;

Besides of that @helgatheviking is right that, from what you've shown in your question, you don't need a extra conditional, but can just use the have_posts() method, in the conditional you already have, for that, like she suggested.


text:
Q: Mod-Rewrite and .htaccess Problems Having some issues with Mod_Rewrite. I must admit this is my first venture into the module so I could be going through something silly. I have been trying to get this to work on my own for a day or so off and on and I can not figure out why this is not working.
I am getting the following errors:
Notice: Undefined index: Dir in D:\wamp\www\WildForFashion\Portal\Index.php on line 31
What I am trying to accomplish is to be able to have one template page (index.php) and have Mod_Rewrite change the url for me so it can be Search Friendly and to also ease coding and design.
I was also having issues when it came to no Images / CSS files loading at all, I did read that by using an absolute url would work.
As of right now I am working in the PORTAL directory first (which is an admin page for website maintenance) and then will be moving onto the root directory. I am not sure if I need to have one .htaccess file or two (one being in root dir, second being in portal dir).
The DIR folder is to hold each category and page for the website like the following:
Domain.com/{CATAGORY}/{PAGE}/
ROOT / DIR / {CATAGORY} / {Page}.php

Domain.com/Portal/{CATAGORY}/{PAGE}/
ROOT / Portal / DIR / {CATAGORY} / {Page}.php

.htaccess Before
RewriteEngine on
RewriteRule ^/Portal/$      Portal/Index.php?Dir=Portal&Page=Home   [L,QSA]
RewriteRule ^Portal/(.*)/(.*)$  Portal/Index.php?Dir=$1&Page=$2 [L,QSA]
RewriteRule ^Portal/(.*)/$      Portal/Index.php?Dir=$1&Page=Home   [L,QSA]

.htaccess After (Working w/ Exceptions)
RewriteEngine on
RewriteRule Portal/$     Portal/Index.php?Dir=Portal&Page=Home   [L,QSA]
RewriteRule Portal/([^/]+)/$     Portal/Index.php?Dir=$1&Page=Home   [L,QSA]
RewriteRule Portal/([^/]+)/([^/]+)/$     Portal/Index.php?Dir=$1&Page=$2 [L,QSA]

Index.php
<?php
include_once("DIR/" . $_GET['Dir'] . "/" . $_GET['Page'] . ".php");
?>

Directory Tree

*

*CSS

*DIR

*IMG

*JS

*SRC

*Portal

*

*CSS

*DIR

*

*Portal

*Inventory

*Stats

*Orders

*IMG

*JS

*SRC

*Index.php

*.htaccess

*Index.php

A: You are including forward slashes in the matching rule that don't need to be there and excluding them from the redirect path where they do need to be. Try this:
RewriteRule Portal/$      Portal/Index.php?Dir=Portal&Page=Home   [L,QSA]

RewriteRule Portal/(.*)/(.*)$  Portal/Index.php?Dir=$1&Page=$2 [L,QSA]

RewriteRule Portal/(.*)/$      Portal/Index.php?Dir=$1&Page=Home   [L,QSA]

Note I removed the ^ from the matching portions of the rewrite rules as this indicated taht should be the beginning of the URI. I also removed the "/" in front of the substritution pattern.


text:
Q: How to get the angle in the triangle See the following pictures:
∠DBC=13°,∠BCD=30°,∠DCA=73°,∠CAB=51°
∠ADB=?

A: Let $\measuredangle ADB=x$.
Thus, by law of sines we obtain:
$$\frac{AD}{AB}=\frac{\sin\measuredangle DBA}{\measuredangle ADB}=\frac{\sin13^{\circ}}{\sin{x}},$$
$$\frac{AC}{AD}=\frac{\sin\measuredangle ADC}{\sin\measuredangle ACD}=\frac{\sin(223^{\circ}-x)}{\sin73^{\circ}}.$$
Thus, $$\frac{AC}{AB}=\frac{\sin13^{\circ}\sin(223^{\circ}-x)}{\sin{x}\sin73^{\circ}},$$
which gives
$$\frac{\sin13^{\circ}\sin(223^{\circ}-x)}{\sin{x}\sin73^{\circ}}=\frac{\sin26^{\circ}}{\sin103^{\circ}}$$ or
$$\frac{\sin13^{\circ}\sin(223^{\circ}-x)}{\sin{x}\sin73^{\circ}}=\frac{2\sin13^{\circ}\cos13^{\circ}}{\cos13^{\circ}}$$ or
$$\frac{\sin(x-43^{\circ})}{\sin{x}\sin73^{\circ}}=2$$ or
$$\frac{\sin{x}\cos43^{\circ}-\cos{x}\sin43^{\circ}}{\sin{x}}=2\sin73^{\circ}$$ or
$$\cos43^{\circ}-\sin43^{\circ}\cot{x}=2\sin73^{\circ}$$ or
$$\cot{x}=\frac{\cos43^{\circ}-2\sin73^{\circ}}{\sin43^{\circ}}.$$
Now, $$\frac{\cos43^{\circ}-2\sin73^{\circ}}{\sin43^{\circ}}=\frac{\cos43^{\circ}-\cos17^{\circ}-\cos17^{\circ}}{\sin43^{\circ}}=$$
$$=\frac{-2\sin13^{\circ}\sin30^{\circ}-\cos17^{\circ}}{\sin43^{\circ}}=-\frac{\sin13^{\circ}+\sin73^{\circ}}{\sin43^{\circ}}=$$
$$=-\frac{2\sin43^{\circ}\cos30^{\circ}}{\sin43^{\circ}}=-\sqrt3,$$
which gives  $x=150^{\circ}$.
Done!

A: Pls see the picture as follows:

Assume $\overline{CD}=2$, we have:
$$\frac{sin\alpha}{sin\beta}=2\bullet cos17^{\circ}$$
But: $$\alpha+\beta=51^{\circ}=3\bullet 17^{\circ}$$
So, we have: $\alpha=2\beta=2\times 17^{\circ}$, which is the only solution.
because the equation :$sin\alpha=2cos17^{\circ}\cdot sin(51^{\circ}-\alpha)$, left side is increasing function and right side is decreasing function, so there is only ONE solution in $(0,51^{\circ})$.
which gives $\theta=180^{\circ}-(13^{\circ}+17^{\circ}) = 150^{\circ}$


text:
Q: Problems with formatting dates in java I'm the doing the following
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss.SSSSSSSSS");
System.out.println(dateFormat.format(date));

The output is weird date patterns such as
2013-10-28 04:10:43.000000222 (its June, not October)
While the time, year and day seems to be fine, the month is playing games. Everytime I run the code, its coming out to be a different month, sometimes even going out of range, like
2013-58-28 04:15:43.000000654
Also, if I'm printing the date without formatting it, it seems to be fine, concluding (I think so) that my system date is fine.
Any idea what's the problem here?

A: Use (capital) MM to indicate month; mm is for minutes only.  The SimpleDateFormat javadoc page has all the date format symbols.

A: tl;dr
LocalDateTime.parse(
    "2013-10-28 04:10:43.000000222".replace( " " , "T" )
)

Using java.time
The Answer by rgettman is correct. But now both the Question and that Answer are outdated.
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Also, your input string has nanoseconds but those old classes are limited to milliseconds. Fortunately the java.time classes handle nanoseconds.
ISO 8601
Your input string nearly complies with the standard ISO 8601 formats. To comply fully, replace the SPACE in the middle with a T.
String input = "2013-10-28 04:10:43.000000222".replace( " " , "T" ) ;

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDateTime
Your input string lacks any indication of an offset-from-UTC or a time zone. So we parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( input ) ;

ldt.toString(): 2013-10-28T04:10:43.000000222

As a LocalDateTime, this does not represent a moment on the timeline. Is that 4 AM in India, 4 AM in France, or 4 AM in Québec? Those would all be different points on the timeline with the 4 AM in India happening several hours earlier in history than the 4 AM times in France or Québec.
ZonedDateTime
If you know for certain the intended time zone, apply it.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ldt.atZone( z );

zdt.toString(): 2013-10-28T04:10:43.000000222-04:00[America/Montreal]

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

*See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


text:
Q: need help with complex numbers $(1-\sqrt3i)(1-i)^2 + 1 + \sqrt3i = ?$
My result is: $-2i - 2\sqrt3 + 1 + \sqrt3i$
Is this the right result or am I doing something wrong?
Thank you.

A: $$(1-i\sqrt3)(1-i)^2+1+i\sqrt3=(1-i\sqrt3)(-2i)+1+i\sqrt3=$$
$$=-2\sqrt3-2i+1+i\sqrt3=(1-2\sqrt3)+(\sqrt3-2)i$$


text:
Q: Ajax submit using a button I am using the code from this page: http://www.w3schools.com/ajax/ajax_database.asp to build my ajax solution.
I am getting there, but this code use onchange, I would like to use a button to submit, instead.
One of my tries:
<!DOCTYPE html>

<form action="">
<select name="customers">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<input name="Submit1" type="submit" onclick="showCustomer(this.value)" />
</form>

Customer info will be listed here...

A: onchange is an event on a select element.
Just tie that event into a button element.
<button onclick="showCustomer()">Submit</button>

and then get the desired customer in the showCustomer() method
function showCustomer()
{
    var str = document.getElementById("customers").value;
    .
    .
    .
    xmlhttp.open("GET","getcustomer.asp?q="+str,true);
    xmlhttp.send();
}

A: they have the event attached to the select so you can just move it to the form instead
<form action="" onsubmit="showCustomer(document.getElementById('customers')).value);return false">
  <select id="customers" name="customers">
  <option value="">Select a customer:</option>
  <option value="ALFKI">Alfreds Futterkiste</option>
  <option value="NORTS ">North/South</option>
  <option value="WOLZA">Wolski Zajazd</option>
 </select>
 <input type="submit"/>
</form>

Edit:
Oh, and add a submit button

A: Something like that :
<!DOCTYPE html>

<select name="customers">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
<input name="Submit1" type="button" onclick="showCustomer()" />

Customer info will be listed here...

But you should try Jquery to avoid verbose syntax document.getElementById


text:
Q: Update the Connection Timeout Property in all the SSIS Packages We have around 600 SSIS packages running in our production Server. We need to update the Connection timeout property of one of the connection managers ( We to need update connection timeout from 0 to 30 seconds). This connection manager has been used in all the packages. I am looking a way to update this property in all the packages at one-time. So far I have fetched all package's XML data
SELECT s.name, CONVERT(XML,CONVERT(VARBINARY(MAX), packagedata))
FROM [msdb].[dbo].[sysssispackages] s

Need help to update only a particular property in a specific connection manager.
 Any help much appreciated.


text:
Q: C# ArgumentOutOfRange Exception, can not figure it out I am getting ArgumentOutOfRange Exception (Index was out of range. Must be non-negative and less than the size of the collection.) in my app that deals with graphics (but I guess that it is not that important to figure out where the error is).
Here is my method:
  public void InverznaFunkcia2(double a, double b, int n, List<Point> F, int m)
    {
        int i = 0;
        double yj = F[0].Y;
        double KrokX = (b - a) / n;
        double KrokY = (F[0].Y - F[n].Y) / m;

        for (int j = 0; j < m - 1; j++)
        {
            while (yj > F[i + 1].Y)
            {
                i = i + 1;
                if (F[i].Y > 200)
                {
                    break;
                }

            }
            invF.Add(j);

            //EXCEPTION THROWN ON THE FOLLOWING LINE:
            invF[j] =( a + (j + ((yj - F[i].Y) / (F[i + 1].Y - F[i].Y)) * KrokX));
           // invF[j].X = a + (j + ((yj - F[i].Y) / (F[i + 1].Y - F[i].Y)) * KrokX);
            yj = yj + KrokY;
            pomocneX.Add(j);
            double ux =  F[i].X -F[i+1].X;
            double uy =  F[i].Y - F[i+1].Y;
            double t = (invF[j] - F[i].Y) / uy;
            pomocneX[j] = F[i].X + (t * ux);

            //pomocneX[j] = ( a +  (j + ((yj - F[i].X) / (F[i + 1].X - F[i].X)) * KrokX));
            textBox3.Text += "invF" + j + "\t" + (invF[j] + "\r\n");
            textBox4.Text += "X" + j + "\t" + (pomocneX[j] + "\r\n");
        }
        //invF.Add(m);
       // invF[m] = (double)b;

    }

I know that this type of exception has been discussed here, but I have no idea how to solve this. Thank you.

A: k; so let's dissect:
//EXCEPTION THROWN ON THE FOLLOWING LINE:
invF[j] =( a + (j + ((yj - F[i].Y) / (F[i + 1].Y - F[i].Y)) * KrokX));

Now; I could start asking things like "j is bounded by m; how do we know if  invF[j] makes sense?"; however, it would be easier to just add some debug code:
try {
    invF[j] =( a + (j + ((yj - F[i].Y) / (F[i + 1].Y - F[i].Y)) * KrokX));
} catch(ArgumentOutOfRangeException) {
    Console.WriteLine("i={0},j={1},|invF|={2},|F|={3}",
        i, j, invF.Length, F.Length);
    throw;
}

That should show you where the problem is.


text:
Q: Determining shapes in metric spaces? I have a specific and a general question. My specific question is this: how would I determine the shape and location of the set of points satisfying $d(x,a) \leq 1$ in the metric space $(\mathbb{R}^2, d)$, where $d(x,y) = |x_{1} - a_{1}| + |x_{2} - a_{2}|$? Since the coordinates of $a$ are constant, the values of $x_{1}$ and $x_{2}$ must range from $a_{i} - 1$ and $a_{i} + 1$, for $i = 1,2$. However, I can't think of a way to determine possible values of the coordinates at these values.
In general, what are some methods that can be used to visualize these sorts of shapes in different metric spaces? I realize that in some exotic spaces things probably can't be visualized, but I'm sure there are tricks for simple ones like this, right?

A: Think about it this way:
If you want $d(x,a) \leq 1$, i.e., $|x_{1} - a_{1}| + |x_{2} - a_{2}| \leq 1$, then draw out your $XY$ plane, and label some point $a$.
Now put another point somewhere on the $XY$ plane, and connect the two points by a straight line.  Now, put your pencil on $a$, and get to $x$ by first going only horizontally (parallel to $x$-axis until you reach either above or below $x$ depending on your drawing, then draw parallel to the $y$-axis (i.e., vertically) up or down until you hit $x$.
The "length" of the horizontal line is represented by the number $|x_{1} - a_{1}|$.  The "length" of the vertical line is represented by the number $|x_{2} - a_{2}|$.  You want all points such that the sum of these lengths is still $\leq 1$.  You can see right away that the further $x_{1}$ is from $a_{1}$, the closer $x_{2}$ must be to $a_{2}$ in order to have the sum of the distances still be $\leq 1$.  With all of this in mind, try to figure out what shape you will get.


text:
Q: detect file difference (change) with `ansible` In this task I found a roundabout method to compare two files (dconfDump and dconfDumpLocalCurrent) and to set a variable (previously defined as false) to true if the two files differ.
The solution seem to work, but it looks ugly and, as a beginner with ansible, I have the impression a better solution should be existing.
---
# vars file for dconfLoad
local_changed : false
target_changed : false

---

- name: local changed is true when previous target different then local current
  shell:  diff /home/frank/dconfDump /home/frank/dconfDumpLocalCurrent
  register: diff_oldtarget_localCurrent
  register: local_changed
  ignore_errors: true
- debug:
    msg: CHANGED LOCALLY
  when: local_changed

Some background to the task, which is an attempt to synchronize files: A file LocalCurrent is compared with LocalOld and CurrentTarget, to determine if the LocalCurrent is changed and if it is different than currentTarget. If LocalCurrent is not changed and CurrentTarget is changed, then apply the change (and set LocalOld to CurrentTarget); if LocalCurrent is changed then upload to controller.
What is the appropriate approach with ansible? Thank you for help!

A: You can use stat to get the checksum and then compare it. Please see below.
   tasks:
   - name: Stat of dconfDump
     stat:
      path : "/tmp/dconfDump"
     register: dump

   - name: SHA1 of dconfDump
     set_fact:
      dump_sha1: "{{ dump.stat.checksum }}"

   - name: Stat of dconfDumpLocalCurrent
     stat:
      path : "/tmp/dconfDumpLocalCurrent"
     register: dump_local

   - name: SHA1 of dconfDumpLocalCurrent
     set_fact:
      local_sha1: "{{ dump_local.stat.checksum }}"

   - name: Same
     set_fact:
      val: "False"
     when:  dump_sha1 != local_sha1

   - name: Different
     set_fact:
      val: "True"
     when:  dump_sha1 == local_sha1

   - name: Print
     debug:
      msg: "{{val}}"

A: Use stat and create dictionary of checksums. For example
    - stat:
        path: "{{ item }}"
      loop:
        - LocalOld
        - LocalCurrent
        - CurrentTarget
      register: result
    - set_fact:
        my_files: "{{ dict(paths|zip(chkms)) }}"
      vars:
        paths: "{{ result.results|map(attribute='stat.path')|list }}"
        chkms: "{{ result.results|map(attribute='stat.checksum')|list }}"
    - debug:
        var: my_files

gives (abridged) if all files are the same
  my_files:
    CurrentTarget: 7c73e9f589ca1f0a1372aa4cd6944feec459c4a8
    LocalCurrent: 7c73e9f589ca1f0a1372aa4cd6944feec459c4a8
    LocalOld: 7c73e9f589ca1f0a1372aa4cd6944feec459c4a8

Then use the dictionary to compare the checksums and copy files. For example
    # If LocalCurrent is not changed and CurrentTarget is changed,
    # then apply the change (and set LocalOld to CurrentTarget)

    - debug:
        msg: Set LocalOld to CurrentTarget
      when:
        - my_files['LocalCurrent'] == my_files['LocalOld']
        - my_files['LocalCurrent'] != my_files['CurrentTarget']

    - debug:
        msg: Do not copy anything
      when:
        - my_files['LocalCurrent'] == my_files['LocalOld']
        - my_files['LocalCurrent'] == my_files['CurrentTarget']

gives
TASK [debug] ****
skipping: [localhost]

TASK [debug] ****
ok: [localhost] =>
  msg: Do not copy anything


text:
Q: NoSQL for searching any arbitrary attribute value without specifying indexes in advance I have spent a lot of time researching NoSQL systems to do something that sounds like it should be very common. I want to store JSON data (or any structured document I guess) then search on any tag/value pair.
The challenge is that I don't know ahead of time the top level attributes that will be contained in the  data, so I really want to avoid having to define every possible index ahead of time.
For example, I may have a lot of contacts such as
firstname: Bob
lastname: Smith
address: ...
city: Quincy
Some of the data set will have additional, solution specific attributes, such as:
twitter: @blah
gender: male
While others may have :
companyname: A great place to work
companycity: Boston
yearsemployed: 7
I would like to be  able to search companycity = Boston AND city = Quincy for one data set and city = Boston AND gender = male without having to define those indexes initially.
So, despite the rather contrived example, what is the best nosql system for arbitrary searches of this type? Currently all I know of is using a full text indexing solution such as Lucene. Unless I have missed something, Cassandra, MongoDB, CouchDB all require indexes to be written ahead of time for any real performance.
A little extra info:
Each data set may be 100000 records. Searches are interactive.
Any help and links appreciated. If you have experience of real solutions doing this would be great.

A: ElasticSearch provides the key requirements from my question (thanks to @ryan1234 for the tip). It provides support for rapid indexing and querying of data with a simple HTTP API.

*

*JSON documents automatically indexed

*arbitrary structured document schema

*searches defined at runtime

*no necessity to generate index or query definitions ahead of time

*scalability (I currently have about 10 million docs in 2GB memory instance)

Based on a few months experience using ElasticSearch on a couple of projects I'm definitely an advocate.


text:
Q: I can't click on anything using selenium on a virtual machine web browser [I'm kind of new using python/selenium]
I wrote a script where it extracts some data from a website, it was working just fine...! until recently the website migrated to an Amazon web server application. Now to access it I use a kind of web browser inside of web browser (like a virtual machine) and because of that I'm not able to click on anything with my script anymore.
I open the website with chrome web driver. and the virtual machine opens a firefox web browser inside the chromedriver.
I tried to switch to geckodriver.exe(firefox) but still can't click on anything.
I keep getting these errors:

NoSuchElementException: Message: Unable to locate element.


text:
Q: What formatting should I use on 'd' when writing an integral?
Possible Duplicate:
What's the proper way to typeset a differential operator?

What formatting should I use on 'd' when writing an integral?
I normally use
$$\int_{-\infty}^{infty} e^{-x^2} \mathoperator{d}\!x = \pi$$

which produces
$\int_{-\infty}^{infty} e^{-x^2} dx = \pi$

Is there a better formatting for dx?