text:
Q: actionlistener(this) not working import java.io.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class Casestudy extends JFrame implements ActionListener
{//making a facebook like program
    JButton Login,Register;
    JLabel lbl1, lbl2;
    JTextField txtEmail;
    JPasswordField txtPassword;

    public Casestudy()
    { //setting labels button etc
        super ("Casestudy2.0");
        setLayout(new FlowLayout());
        lbl1 = new JLabel (" Username ");
        lbl2 = new JLabel (" Password ");
        txtEmail = new JTextField(10);
        Login = new JButton("Login");
        Register= new JButton("Register");
        //this

        Login.addActionListener(this);//adding listener this

        Register.addActionListener(this);
        Register.setBounds(2,250,100,20);

    }

    public void actionPerformed(ActionEvent e){

        //my code supposedly im working but im just checkin the frame and it apppars to not work properly just a frame no buttons
    }

    public static void main (String  args []){
        Casestudy use= new Casestudy();//frame size
        use.setSize(250,280);
        use.setVisible(true);
        use.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

Supposedly I want to run this program and check the frame before working on it but its not displaying any buttons or whatsoever please help I'm in pinch :(
in other words I want my frame to have buttons first before I start with my actual program.

A: You forgot to add the button to the JFrame:
public ExperimentApplication()
    { //setting labels button etc
     super ("Casestudy2.0");
     setLayout(new FlowLayout());
     lbl1 = new JLabel (" Username ");
     lbl2 = new JLabel (" Password ");
     txtEmail = new JTextField(10);
     Login = new JButton("Login");
     Register= new JButton("Register");
     //this

     Login.addActionListener(this);//adding listener this

     Register.addActionListener(this);
     Register.setBounds(2,250,100,20);

     // ADD BUTTON TO THE FRAME
     this.add(Register);

    }


text:
Q: Using debounce in rxjs client side webapp I am moving into functional reactive code starting with rxjs and have some questions about how to best import it as I am getting mixed results.
Currently, I have a simple implementation where I check a web service for if a username already exists.
Here is the code that works perfectly:
$(window).load(function() {
    // setup an observable
    submission = Rx.Observable.fromEvent($("#submitbutton"), "click").map(
        event => {
            return "justsomeusername";
        }
    );

    submission
        .concatMap(username => {
            return Rx.Observable.fromPromise(
                $.get(
                    "{{ site.serveraddress }}/checkuser?&username=" + username
                )
            ).catch(() => Rx.Observable.empty());
        })
        .subscribe(rval => {
            console.log(rval);
        });
});

This all works great BUT when I try to add a debounce like submission.debounce(500).concatMap((username) =>
Rx.js:8512 Uncaught TypeError: this.durationSelector.call is not a function
at DebounceSubscriber._next (Rx.js:8512)
at DebounceSubscriber.Subscriber.next (Rx.js:424)
at MapSubscriber._next (Rx.js:5715)
at MapSubscriber.Subscriber.next (Rx.js:424)
at HTMLButtonElement.handler (Rx.js:3913)
at HTMLButtonElement.dispatch (jquery.min.js:3)
at HTMLButtonElement.r.handle (jquery.min.js:3)

That is what appears in the console.
I think that the way I am importing or referencing the library is the cause, this is where there is some confusion.
I am importing like this at the top of an HTML page:
<script src="https://unpkg.com/@reactivex/rxjs@5.5.6/dist/global/Rx.js"></script>

If I try to import any other reference the Rx object seems not to exist?  Does this have to do with the filename maybe becoming the object namespace?
For example, I downloaded all the latest rxjs release and in the dist see rx.all.js but if I import locally one of the latest dists  like:
<script src="/myapp/javascript/rx.all.js"></script>
I get Rx undefined.  What is the nuance occurring between these two different ways of reference.
What is the surefire way to import rxjs for client-side use?   Is this the likely cause of the debounce not working (not having the full lib)?
Thanks!

A: You should use debounceTime for this, not debounce. debounce takes a function parameter which must determine dynamically the debounce time, whereas debounceTime can be used exactly as you state:
$(window).load(function() {
    // setup an observable
    submission = Rx.Observable.fromEvent($("#submitbutton"), "click").map(
        event => {
            return "justsomeusername";
        }
    );

    submission
        .debounceTime(500)
        .concatMap(username => {
            return Rx.Observable.fromPromise(
                $.get(
                    "{{ site.serveraddress }}/checkuser?&username=" + username
                )
            ).catch(() => Rx.Observable.empty());
        })
        .subscribe(rval => {
            console.log(rval);
        });
});

If you wanted to use debounce, you'd do something like this:
    submission
        .debounce((val) => {
            // Add whatever logic for determining the right
            // debounce time for the value entered by the
            // user, in this case, simply returning a hard
            // coded 500 which will do exactly the same as
            // debounceTime(500)
            return 500;
        })
        .concatMap(username => {
            // ... snip ...
        });
});

It doesn't look like there is any problem with how you are importing RxJS - although I would advise if you're just starting with RxJS to go to v6 as it changes how a lot of things are done with operators like debounce and concatMap - it's a pain to change it all later so better to make the change when you're just starting!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Forwarding keyboard scroll events from one element to another when mouse is pressed I'm working on an application that has a side panel and main timeline view. Users are to be able to select an item from the side panel and drag it into the timeline view.
To drag the item, the user presses and holds the left mouse button down, and drags the item to the timeline view. The user should now be able to use arrow keys to scroll the time line up and down, however when these buttons are pressed the side panel is scrolled instead. On mousedown I've tried to set the focus to my timeline element but that is not working.
onMouseDown = () => {
  ...
  document.getElementById('timeLine').focus() // does not change the focus to the timeline
}

Is it possible to force the browser to change focus while the mouse button is being held down? My current fix is to force an animation to scroll the timeline view using jQuery, but this is results in quite a slow animation compared to a real browser scroll event.

A: Only certain HTML Elements can be focused, such as non-disabled inputs, iFrames, non-disabled-buttons, and anchors (links) which have an href property.
To allow other elements to be focusable you must give them a tab index. To have the browser automatically calculate the correct tabindex you should use tabindex = 0 in your html for your timeline element. This should fix your issue.
A quickly thrown together example is here. If you delete the tabindex = 0 then you'll notice the jQuery focus command stops working
https://codepen.io/kaisalmon/pen/BaNVmbL
EDIT: If you are using mousedown (but not click or mouseup also prevent the event's default action using:
    $('#timeline').focus();
    e.preventDefault();

A: You have to check first weather that content appears on the screen or not using onScroll() function or any other source. After that you have to add active class in that tab or focus that tab which content appears on the screen.
For finding weather the content appears on the screen or not for focus on particular element from timeline follow the link to get the content appears on scroll How to Check if element is visible after scrolling?


text:
Q: Verb for putting laundry to the drying rack What verb can I use to describe the process of takind the laundry out of the washing maching and putting it on the drying rack? Is "I have to take out the laundry" correct? Can I use another verb instead?
As a non native speaker, I feel like I am describing the process instead of using the actual verb of it. I am asking because I feel that it is not the proper way to say it.

A: A simple word to use would be to hang the laundry. Different people use different ways of drying, I'd say "Take the washing out the machine and hang it on the (washing) line"
Of course not everyone uses a line to dry clothes. You might "put it in the tumble drier" or "hang it on the radiator"


text:
Q: How could I split commas excepts it's in double quotes s1 ='a,b,c,"x,y,z" '
m1 = s1.split(',')

"x,y,z" should not be splitted by comma
The expected result should be ['a','b','c',"x,y,z"], total size is 4
How could I do that in Ruby

A: Use the csv module:
irb(main):001:0> require 'csv'
=> true
irb(main):002:0> CSV.parse_line('a,b,c,"x,y,z"')
=> ["a", "b", "c", "x,y,z"]

A: Try this:
s1 ='a,b,c,"x,y,z" '

quotes = s1.match(/".+"/)

s1.split(/,(?![#{quotes}])|,(?=")/)

A: Could it be? Is it possible? Do I finally have a chance to use Ruby's bordering-on-bizarre flip-flop operator?
Let's try:
str ='a,b,c,"x,y,z",d,e,"1,2,3",f '

u = ''
str.split(?,).each_with_object([]) do |s,a|
  t = s.strip
  if (t[0]==?") .. (t[-1]==?")
    u = '' if t[0]==?"
    u << t
    if t[-1]==?"
      a << u
    else
      u << ?,
    end
  else
    a << t
  end
end
  #=> ["a", "b", "c", "\"x,y,z\"", "d", "e", "\"1,2,3\"", "f"]

A: You can do a one liner def like this that will separate the string by commas, unless the commas are inside simple OR double quotes
def separate params
  params.split(/(?!\B\b('|")[^\"']*),(?![^\"']*('|")\B\b)/)
end


text:
Q: Problema ao fazer deploy no heroku com apigility Estou tentando subir uma api criada com Apigility para o heroku. A aplicação compila corretamente, porém ao fazer qualquer request, eu recebo um erro 500 como retorno. No log do heroku, eu vejo o seguinte erro:

PHP Fatal error:  Uncaught Error: Class 'Zend\Console\Console' not
  found in
  /app/vendor/zfcampus/zf-content-negotiation/src/Factory/RequestFactory.php:22

Não encontrei muitos tutoriais por ai, e aqueles que encontrei não disponibilizavam muitos detalhes do passo a passo para subir a aplicação.
Alguém já passou pelo mesmo problema? Qual a solução para esse erro?


text:
Q: C++: Reading and Sorting Binary Files I've been scratching my head and putting this homework off for a couple days but now that I hunker down to try and do it I'm coming up empty. There's 4 things I need to do.
1) Read a binary file and place that data into arrays
2) Sort the list according to the test scores from lowest to highest
3) Average the scores and output it
4) Create a new binary file with the sorted data
This is what the binary data file looks unsorted
A. Smith    89
T. Phillip 95
S. Long 76
I can probably sort since I think I know how to use parallel arrays and index sorting to figure it out, but the reading of the binary file and placing that data into an array is confusing as hell to me as my book doesn't really explain very well.
So far this is my preliminary code which doesn't really do much:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;

int get_int(int default_value);
int average(int x, int y, int z);

int main()

   {

    char filename[MAX_PATH + 1];
    int n = 0;
    char name[3];
    int grade[3];
    int recsize = sizeof(name) + sizeof(int);
    cout << "Enter directory and file name of the binary file you want to open: ";
    cin.getline(filename, MAX_PATH);

    // Open file for binary write.
    fstream fbin(filename, ios::binary | ios::in);
    if (!fbin) {
    cout << "Could not open " << filename << endl;
    system("PAUSE");
    return -1;
   }

}

Sorry for such a novice question.
edit: Sorry what the data file stated earlier is what it SHOULD look like, the binary file is a .dat that has this in it when opened with notepad:
A.Smith ÌÌÌÌÌÌÌÌÌÌÌY    T. Phillip ÌÌÌÌÌÌÌÌ_    S. Long ip ÌÌÌÌÌÌÌÌL    J. White p ÌÌÌÌÌÌÌÌd

A: Reading a file in c++ is simple:
create a stream from file [so that to read from the stream] (you have filestream[input/output], stringstream ... )
    ifstream fin;  //creates a fileinput stream

    fin.open(fname.c_str(),ifstream::binary);        // this opens the file in binary mod

    void readFile(string fname)
    {
        ifstream fin;
        fin.open(fname.c_str());            //opens that file;
        if(!fin)
            cout<<"err";
        string line;
        while(getline(fin,line))            //gets a line from stream and put it in line (string)
        {
            cout<<line<<endl;
            //reading every line
            //process for you need.
            ...
        }
        fin.close();
    }

as you specify, the file is simply a text file, so you can process each line and do whatever you want.

A: Reading from a binary file may seem confusing, but it is really relatively simple. You have declared your fstream using your file name and set it to binary, which leaves little to do.
Create a pointer to a character array (typically called a buffer, since this data is typically extracted from this array after for other purposes). The size of the array is determined by the length of the file, which you can get by using:
fbin.seekg(0, fbin.end); //Tells fbin to seek to 0 entries from the end of the stream
int binaryLength = fbin.tellg(); //The position of the stream (i.e. its length) is stored in binaryLength
fbin.seekg(0, fbin.beg); //Returns fbin to the beginning of the stream

Then this is used to create a simple character array pointer:
char* buffer = new char[binaryLength];

The data is then read into the buffer:
fbin.read(buffer, binaryLength);

All the binary data that was in the file is now in the buffer. This data can be accessed very simply as in a normal array, and can be used for whatever you please.
The data you have, however, does not at all seem binary. It looks more like a regular text file. Perhaps, unless explicitly stated, you ought to consider a different method for reading your data.

A: You know, with that low range of sorting index you can avoid actual sorting (with comparing indices and moving data forth and back). All you have to do is to allocate a vector of vector of strings, resize it to 101. Then traverse the data, storing each: "A. Smith" in 89-th element; "T. Phillip" in 95-th; "S. Long" in 76-th and so on.
Then by iterating the vector elements from begin() to end() you would have all the data already sorted.
It's almost linear complexity (almost, because allocation/resizing of subvectors and strings can be costly) easy and transparent.


text:
Q: ffmpeg missing image frames in generated video from images Similar question here, but not yet answered.
Problem:
I'm combining images (.png) of same resolution/size (they all came from the same matplotlib.pyplot), but the resulting video is missing several frames.
Command:
ffmpeg -f image2 -r 1 -i .\\images\\image%02d.png -c:v libx264 -r 30 .\\images\\output.mp4

Resulting Video

*

*Length of 0:09

*Missing more than half the images

Images

*

*.\images

*

*image00.png

*image01.png

*image02.png

*image03.png

*image04.png

*image05.png

*image06.png

*image07.png

*. . .
Notes:
I followed examples from here. I'm new to using ffmpeg, so I may not be completely sure of what each of the command line options I've used means, though I have a pretty good idea.
Thanks, any help/advice/suggestions will be greatly appreciated. I am also perfectly willing to provide further information that may help resolve this issue.

A: Sometimes this happens if the images are not all exactly the same size. Your command looks fine to me.

A: I saved my images as:
Images
.\images
    image00.png
    image01.png
    image02.png
    image03.png
    image04.png
    image05.png
    image06.png
    image08.png
    image09.png
    image010.png #<---- crap. all hells gone loose now.
    image011.png
    image012.png
    image013.png
    image014.png
    image015.png

Because I saved them in a for loop and tried to do some fancy name generating script that failed miserably. For reference though, this is the code that works:
for i in range(len(frames)):
    fig.savefig('images\\' + 'image'+ ('{0:0'+str(len(str(len(frames))))+'}').format(i)+'.png')


text:
Q: TCP Socket Server setup for receive/process/reply This is a new question following up on this older question and answer (specifically the comment that says "don't comment on old answers, ask a new question"), as well as these examples in GitHub.
I know the answer and examples are minimal working "trivial examples", but I don't know enough about how "things work in Spring" (or should work) to understand how to decompose those generic, trivial examples into separate servers and clients that suit my purpose.  I currently have a working Spring-Boot daemon application that is client to / calls on (without any "spring integration") a legacy daemon application over a TCP Socket connection.  It's all working, running in production.
But now I am tasked with migrating the legacy daemon to Spring Boot too.  So I only need to configure and set up a cached/pooled TCP connection "socket listener" on the server-side.  However, the "client parts" of the existing (self contained) examples confuse me. In my case the "client side" (the existing Spring Boot daemon) is not going to change and is a separate app on a separate server, I only need to set up / configure the "server-side" of the socket connection (the "legacy-daemon freshly migrated to Spring Boot" daemon).
I've copied this example configuration (exactly) into my legacy-migration project
@EnableIntegration
@IntegrationComponentScan
@Configuration
public static class Config {

@Value(${some.port})
private int port;

@MessagingGateway(defaultRequestChannel="toTcp")
public interface Gateway {

    String viaTcp(String in);

}

@Bean
@ServiceActivator(inputChannel="toTcp")
public MessageHandler tcpOutGate(AbstractClientConnectionFactory connectionFactory) {
    TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(connectionFactory);
    gate.setOutputChannelName("resultToString");
    return gate;
}

@Bean
public TcpInboundGateway tcpInGate(AbstractServerConnectionFactory connectionFactory)  {
    TcpInboundGateway inGate = new TcpInboundGateway();
    inGate.setConnectionFactory(connectionFactory);
    inGate.setRequestChannel(fromTcp());
    return inGate;
}

@Bean
public MessageChannel fromTcp() {
    return new DirectChannel();
}

@MessageEndpoint
public static class Echo {

    @Transformer(inputChannel="fromTcp", outputChannel="toEcho")
    public String convert(byte[] bytes) {
        return new String(bytes);
    }

    @ServiceActivator(inputChannel="toEcho")
    public String upCase(String in) {
        return in.toUpperCase();
    }

    @Transformer(inputChannel="resultToString")
    public String convertResult(byte[] bytes) {
        return new String(bytes);
    }

}

@Bean
public AbstractClientConnectionFactory clientCF() {
    return new TcpNetClientConnectionFactory("localhost", this.port);
}

@Bean
public AbstractServerConnectionFactory serverCF() {
    return new TcpNetServerConnectionFactory(this.port);
}

}

...and the project will start on 'localhost' and "listen" on port 10000.  But, when I connect to the socket from another local app and send some test text, nothing returns until I shut down the socket listening app. Only after the socket listening app starts shutting down does a response (the correct 'uppercased' result) go back to the sending app.
How do I get the "listener" to return a response to the "sender" normally, without shutting down the listener's server first?
Or can someone please provide an example that ONLY shows the server-side (hopefully annotation based) setup?  (Or edit the example so the server and client are clearly decoupled?)

A: Samples usually contain both the client and server because it's easier that way. But there is nothing special about breaking apart the client and server sides. Here's an example using the Java DSL:
@SpringBootApplication
public class So60443538Application {

    public static void main(String[] args) {
        SpringApplication.run(So60443538Application.class, args);
    }

    @Bean
    public IntegrationFlow server() {
        return IntegrationFlows.from(Tcp.inboundGateway(Tcp.netServer(1234)))
                .transform(Transformers.objectToString()) // byte[] -> String
                .<String, String>transform(p -> p.toUpperCase())
                .get();
    }

}

@SpringBootApplication
public class So604435381Application {

    private static final Logger LOG = LoggerFactory.getLogger(So604435381Application.class);

    public static void main(String[] args) {
        SpringApplication.run(So604435381Application.class, args);
    }

    @Bean
    public IntegrationFlow client() {
        return IntegrationFlows.from(Gate.class)
                .handle(Tcp.outboundGateway(Tcp.netClient("localhost", 1234)))
                .transform(Transformers.objectToString())
                .get();
    }

    @Bean
    @DependsOn("client")
    public ApplicationRunner runner(Gate gateway) {
        return args -> LOG.info(gateway.exchange("foo"));
    }

}

interface Gate {

    String exchange(String in);

}

2020-02-28 09:14:04.158  INFO 35974 --- [           main] com.example.demo.So604435381Application  : FOO


text:
Q: Recover deleted document I would like to recover deleted document. I did following
To get id of doc:
curl http://127.0.0.1:5984/shareddb/_changes

{"seq":"138-g1AAAACbeJzLYWBgYMpgTmEQTM4vTc5ISXLIyU9OzMnILy7JAUklMiTV____PyuDOdE9FyjAnmxmbmiemohNAx5j8liAJEMDkPoPNc0ZbJpJiqG5iUEyNn1ZAJoKMSU","id":"25df5fb6-9a9d-43fa-9bb2-2b7dc6f67e51","changes":[{"rev":"5-a116b399e972ef9353c418e907b0eaaa"}],"deleted":true}

After getting the id
curl http://127.0.0.1:5984/shareddb/25df5fb6-9a9d-43fa-9bb2-2b7dc6f67e51?revs=true&open_revs=all

{"error":"not_found","reason":"deleted"}

Also, I tried following
curl http://127.0.0.1:5984/shareddb/25df5fb6-9a9d-43fa-9bb2-2b7dc6f67e51?revs_info=true

{"error":"not_found","reason":"deleted"}

Basically I want to put the doc again as suggested in http://garmoncheg.blogspot.com/2013/11/couchdb-restoring-deletedupdated.html
Please suggest if there is any other solution to recover deleted documents. As far as I know, there is no rollback in CouchDB. Please correct me if I'm wrong.


text:
Q: JavaFX Error: Incompatible types: ContentDisplay cannot be converted to VPos I use a GridPane as layout for Main, but when I add a Button like in my code... Show this type of Error..
Incompatible types: ContentDisplay cannot be converted to VPos

My controller  and
Main class
public class Main extends Application
{

    public static void main(String[] args)
    {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage)
    {

        GridPane grid =new GridPane();

        grid.setStyle("-fx-background-color: black;");
        Button b1=new Button();
        grid.setGridLinesVisible(true);
        grid.setConstraints(new Button("Check"),3,4,1,2,LEFT,CENTER,Priority.SOMETIMES,Priority.SOMETIMES);
        grid.add(new Button ("like"), 2, 4);
        Scene scene =new Scene(grid);
        primaryStage.setScene(scene);
        primaryStage.show();
  }
}

A: You've added a static import for ContentDisplay.CENTER. Therefore it's used in this line:
grid.setConstraints(new Button("Check"),3,4,1,2,LEFT,CENTER,Priority.SOMETIMES,Priority.SOMETIMES);

However this method expects VPos, which is not assignable from ContentDisplay, which is why this doesn't compile.
You could simply fix this import by changing the class you import from, but I do not recommend using static imports, since it makes the code harder to read (You have to check the imports to know where the member comes from).
I recommend importing HPos and VPos and using this code instead.
Furthermore setColumnConstraints is a static method and should not be referenced using an variable. (It's not wrong, but it's bad practice.) Being a static method this does not add the Button as child of grid. You need to do this in addition to setting the constraints.
Button button = new Button("Check");
GridPane.setConstraints(button,
                        3, 4,
                        1, 2,
                        HPos.LEFT, VPos.CENTER,
                        Priority.SOMETIMES, Priority.SOMETIMES);

grid.getChildren().add(button);


text:
Q: incorrect results of IsolationForest I inspired by this notebook, and I'm experimenting IsolationForest algorithm for anomaly detection context on the SF version of KDDCUP99 dataset, including 4 attributes. The data is directly fetched from sklearn and after preprocessing (label encoding the categorical feature) passed to the IF algorithm with default setup (except for n_estimator, which I used GridsearchCV to find the optimum number of trees).
The problem is based on the KDDCUP99 dataset documentation, and its User guide and my calculation in the following implementation the anomaly rate is 0.5% and it means if I set contamination=0.005, it should give me the best results but surprisingly, it does not!
The full code is as follows:
from sklearn import datasets
from sklearn import preprocessing
from sklearn.model_selection import train_test_split

from sklearn.ensemble import IsolationForest
from sklearn.metrics import classification_report, ConfusionMatrixDisplay
from sklearn.metrics import confusion_matrix
from sklearn.metrics import recall_score, silhouette_score, roc_curve, roc_auc_score, f1_score, precision_recall_curve, auc
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score

import pandas as pd
import numpy as np
import seaborn as sns
import itertools
import matplotlib.pyplot as plt
import datetime

%matplotlib inline

def byte_decoder(val):
    # decodes byte literals to strings

    return val.decode('utf-8')
def plot_confusion_matrix(cm, title, classes=["Normal", "Anomaly"],
                          cmap=plt.cm.Blues, save=False, saveas="MyFigure.png"):

    # print Confusion matrix with blue gradient colours

    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=90)
    plt.yticks(tick_marks, classes)

    fmt = '.1%'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                horizontalalignment="center",
                color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

    if save:
        plt.savefig(saveas, dpi=100)

#Load Dataset KDDCUP99 from sklearn
target = 'target'
sf = datasets.fetch_kddcup99(subset='SF', percent10=False)
dfSF=pd.DataFrame(sf.data,
                  columns=["duration", "service", "src_bytes", "dst_bytes"])
assert len(dfSF)>0, "SF dataset no loaded."

dfSF[target]=sf.target
anomaly_rateSF = 1.0 - len(dfSF.loc[dfSF[target]==b'normal.'])/len(dfSF)

"SF Anomaly Rate is:"+"{:.1%}".format(anomaly_rateSF)
#'SF Anomaly Rate is: 0.5%'

#Data Processing
toDecodeSF = ['service']
# apply hot encoding to fields of type string
# convert all abnormal target types to a single anomaly class

dfSF['binary_target'] = [1 if x==b'normal.' else -1 for x in dfSF[target]]

leSF = preprocessing.LabelEncoder()

for f in toDecodeSF:
    dfSF[f + " (encoded)"] = list(map(byte_decoder, dfSF[f]))
    dfSF[f + " (encoded)"] = leSF.fit_transform(dfSF[f])

for f in toDecodeSF:
  dfSF.drop(f, axis=1, inplace=True)

dfSF.drop(target, axis=1, inplace=True)

#check rate of Anomaly for setting contamination parameter in IF
dfSF["binary_target"].value_counts() / np.sum(dfSF["binary_target"].value_counts())

#train & data split
X_train_sf, X_test_sf, y_train_sf, y_test_sf = train_test_split(dfSF.drop('binary_target', axis=1), dfSF['binary_target'],
                                                                test_size=0.33, random_state=11, stratify=dfSF['binary_target'])

clfIF = IsolationForest(max_samples="auto", random_state=11, contamination = "auto", n_estimators=100, n_jobs=-1)

clfIF.fit(X_train_sf,y_train_sf)
y_pred_train = clfIF.predict(X_train_sf)

#Results on SF training set:
print(classification_report(y_train_sf, y_pred_train, target_names=["Anomaly", "Normal"]))
print("AUC: ", "{:.1%}".format(roc_auc_score(y_train_sf, y_pred_train)))
#AUC is about 93%.

#Results on SF training set:
clfIF = IsolationForest(max_samples="auto", random_state=11, contamination = "auto", n_estimators=100, n_jobs=-1)

clfIF.fit(X_train_sf, y_train_sf)
y_pred_test = clfIF.predict(X_test_sf)
#AUC is about 93%.

scoring = {'AUC': 'roc_auc', 'Recall': make_scorer(recall_score, pos_label=-1)}
gs = GridSearchCV(IsolationForest(max_samples="auto", random_state=11, n_jobs=-1),
                  param_grid={'n_estimators': range(1, 110, 5)},
                  scoring=scoring, refit='Recall', return_train_score=True, cv=3, verbose=1, n_jobs=-1)
gs.fit(X_train_sf, y_train_sf)
results = gs.cv_results_
gs.best_estimator_
max_recall_n_estimators = pd.DataFrame(results).iloc[np.argmax(pd.DataFrame(results)["mean_test_Recall"])]["param_n_estimators"]
print(max_recall_n_estimators)

fig, ax = plt.subplots(figsize=(8, 20))
# fig.tight_layout()

for idx, cont in zip(range(1, 4), [0.005, 0.1, 0.2]):
    iso_for_ = IsolationForest(random_state=11,
                             n_estimators=max_recall_n_estimators,
                             max_samples="auto",
                             contamination=cont,
                             n_jobs=-1)
    iso_for_.fit(X_train_sf, y_train_sf)

    y_pred_ = iso_for_.predict(X_test_sf)

    ax = plt.subplot(1, 3, idx)
    cm = confusion_matrix(y_test_sf, y_pred_)
    cm = np.round(cm / cm.sum(axis=1)[:, np.newaxis], decimals=2)
    cmd = ConfusionMatrixDisplay(cm, display_labels=["Anomaly", "Normal"])
    cmd.plot(ax=ax, xticks_rotation=45, cmap=plt.cm.Blues, values_format=".2%")
    cmd.ax_.set_title(f"IF (contamination = {cont}) \nconfusion matrix - SF")
    cmd.im_.colorbar.remove()
    cmd.ax_.set_xlabel('')
    cmd.ax_.set_ylabel('')

fig.text(0, 0.5, "True Label", rotation=90, va='center')
fig.text(0.4, 0.4, 'Predicted Label', ha='left')
plt.subplots_adjust(wspace=0.9)
plt.suptitle("Confusion matrix of sklearn IF for various contaminations (SF)", y=0.63)
plt.show()

This is the results of the confusion matrix:

Probably I am missing something here, and any help will be highly appreciated.
Edit: We know that IF algorithm label anomaly labels based on outliers score results and try to plot them on train and test set for better realization as follows:
outlier_scores_train = iso_for_sf.decision_function(X_train_sf)
outlier_scores_test  = iso_for_sf.decision_function(X_test_sf)

train_df = pd.concat([X_train_sf.reset_index(drop=True), pd.DataFrame(outlier_scores_train, columns=["outlier score"])], axis=1)
test_df = pd.concat([X_test_sf.reset_index(drop=True), pd.DataFrame(outlier_scores_test, columns=["outlier score"])], axis=1)

sns.distplot(outlier_scores_train, kde=True, norm_hist=True, color="b", label="Trainset outlier scores")
sns.distplot(outlier_scores_test,  kde=True, norm_hist=True, color="r", label="Testset outlier scores", hist_kws={'alpha': 0.3})

plt.xlabel("outlier score")
plt.ylabel("frequency")
plt.title("Outlier scores Distribution")

plt.legend()
plt.show()

A: Contamination in isolation forest is basically a hyperparameter. It is used to pick the threshold for the score to distinguish anomalies from non-anomalies. It should be close to the proportion of anomalies assuming that your training data is perfectly representative to the test (real!) data and that the algorithm was able to learn the representation of the data reasonably well for this task. As you can see, those are quite a big assumptions to be met.
This may be more obvious with simpler algorithm like EllipticEnvelope, that fits a multivariate Gaussian to your data and cuts-off the values from low density regions based on the value of the contamination hyperparameter. It would work perfectly if you set the value of contamination to the proportion of anomalous samples if your data is distributed as a multivariate Gaussian, but gives no such guarantees for other kinds of data. Isolation forest is a bit more complicated, but same problems apply.
TL;DR Just treat it as a hyperparameter.


text:
Q: How to prove $(\ell_1\ |.\|)$ is Gateaux differentiable at $x$ if and only if $x_i\not= 0$ for all $i\in\mathbf{N}$? I am in trouble  to prove that $\|x\|=\sum\limits_{i=1}^{\infty}|x_i|$  of $x=(x_i)\in\ell_1$ is Gateaux differentiable at $x$ if and only if $x_i\not= 0$ for all $i\in \mathbf{N}$. I want to use this theorem

the norm $\|.\|$ is Gateaux differentiable at $x\in S_X$ if and only if there is a unique  $f\in S_{X^*}$ such that $f(x)=1.$

Since $\ell_{1}^{*}=\ell_{\infty},$  so we have that foe every $f\in\ell_{1}^{*}$ there is a unique $(a_i)\in\ell_{\infty}$ such that $f(x)=\sum\limits_{i=1}^{\infty}a_ix_i$ for all $x=(x_i)\in \ell_1$
Please help me how to continue? Thanks.

A: Given $x$ such that $\sum |x_i|=1$, you are looking for $a$ with $\sup |a_i|=1$ such that $\sum x_i a_i=1$.
By the triangle inequality,
$$\sum x_i a_i\le \sum |x_i  a_i|\le \sum |x_i|=1$$
so equality is required at every step. This means $x_ia_i=|x_ia_i|$ for every $i$.

*

*If all $x_i$ are nonzero, the only choice of $a_i$ is $\operatorname{sign} x_i$. This is why $a$ is uniquely determined.

*If some $x_i$ is zero, you can choose $a_i=\pm 1$ (or in between) as you wish. So,  $a$ is  not uniquely determined.


text:
Q: Cross-Site Scripting: DOM Fortify shows there is Cross-Site Scripting: DOM for the below code snippet of jquery files:
I am getting in both line of code Cross- site scripting:Dom. How to fix this attack?
deleteAccount: function () {

var id = $('#DeleteAccount').val(); //what should i change here to stop Cross- site scripting?

//Few lines of code

var accountName = $.trim($('.display' + id).text());//what should i change here to stop Cross- site scripting?

}


text:
Q: General solution of second order differential equations that are not equal to 0. My question is "Compute the general solution of $y''+2y'+y= (t^{-1})(e^{-t})$."
So far, I know that my characteristic equation is $r^2+2r+1=0$ and therefore my repeated root is $r= -1$.
From that, I know that $y(t)=C_1e^{-t} + C_2te^{-t}$.
I don't know where to go from here to complete the question.
Any corrections or suggestions?

A: Hint
The differential equation being $$y''+2 y'+y=\frac{e^{-t}}{t}$$ you could start using $$y=z e^{-t}\qquad y'= \left(z'-z\right)e^{-t}\qquad y''= \left(z''-2 z'+z\right)e^{-t}$$ This makes the differential equation to be $$ z''e^{-t}=\frac{e^{-t}}{t}$$ that is to say $$z''=\frac 1 t$$ which seems to be quite simple to integrate.
I am sure that you can take it from here.


text:
Q: Common table expressions and memory usage I'm using a common table expression to perform some updates within a batch statement.
Is it recommended to DROP the table after I'm done with it within the loop and re-declare it on the next pass? I am deploying this script to a fairly unknown environment, am concerned about resource utilization and would like to keep memory usage to a minimum.
Edited to include source (this is within a while loop):
WITH UpdatedRecords AS (
    SELECT TOP 50000
           unique_id,
           is_processed
    FROM
          _TempSnapshots
    WHERE
          is_processed = 0
    ORDER BY
          unique_id DESC
)
UPDATE UpdatedRecords
   SET is_processed = 1

A: This question was answered by @MartinSmith in the comments on the question:
Following the edit that is a common table expression. It is basically like a derived table though and you can't drop it as it doesn't exist as a table in its own right. It doesn't get materialized into a temporary table up front it just gets inlined into the query that references it


text:
Q: specialize a template with expression parameter I have a class like this:
template <class T>
class Foo;

I want to have a specialization of
template <>
class Foo < size_t N >;

but that doesn't compiles for me:
my main is like:
Foo<int> p;  // OK
Foo<15> p2;  // fails to compile

What am I missing?

A: You can't - your template takes one type parameter, always. Specializations can only be more special than that, but not different (hence the name).
Maybe you can use an auxiliary template to store value information:
template <typename T, T Val> struct ValueWrapper { };

template <typename T> struct Foo;

templaet <typename T, T Val> struct Foo<ValueWrapper<T, Val>>
{
    typedef T type;
    static type const value = Val;

    // ...
};

Usage:
Foo<char> x;
Foo<ValueWrapper<int, 15>> y;

A: There are three kinds of template parameters: Those that represent a type (e.g. class T or typename T), those that represent a non-type (e.g. int N or size_t N), and those that represent a template (e.g. template <class T2> class T).
The parameter defined for your template is of the first kind (a type parameter), but the specialization assumes the second kind (a non-type parameter). That doesn't work. The parameters of the specialization must be of the same kind as the corresponding parameters of the primary template definition.

A: You can specialize the class using an intermediate class:
template <class T>
class Foo
{
public:
  static const bool is_number = false;
};
template <size_t number>
struct ic
{};
template <size_t N>
class Foo < class ic<N> >
{
public:
   static const bool is_number = true;
   size_t getN() const
   {
      return N;
   }
};

int main()
{
   Foo<int> p;
   Foo<ic<15> > p2;
   cout << "p.is_number = " << p.is_number << endl;
   cout << "p2.is_number = " << p2.is_number  << endl;
   cout << "p2.getN() = " << p2.getN() << endl;
   return 0;
}


text:
Q: Nativescript mapbox custom marker tooltip I am using mapbox in nativescript, how we can add a custom view (HTML or XML) to the marker tooltip.
Markers show only title and subtitle, I need to view my own layout instead
map.addMarkers([{
    lat: 52.3602160,
    lng: 4.8891680,
    title: 'marker title',
    subtitle: 'marker subtitle',
    image: 'https://farm9.staticflickr.com/8571/15844010757_63b093d527_n.jpg'
}]);

A: According to the plugin README you can add you own icons for the markers via icon and iconPath
  var onTap = function(marker) {
    console.log("Marker tapped with title: '" + marker.title + "'");
  };
  var onCalloutTap = function(marker) {
    alert("Marker callout tapped with title: '" + marker.title + "'");
  };

  mapbox.addMarkers([
    {
      id: 2, // can be user in 'removeMarkers()'
      lat: 52.3602160, // mandatory
      lng: 4.8891680, // mandatory
      title: 'One-line title here', // no popup unless set
      subtitle: 'Infamous subtitle!',
      icon: 'res://cool_marker', // preferred way, otherwise use:
      icon: 'http(s)://website/coolimage.png', // from the internet (see the note at the bottom of this readme), or:
      iconPath: 'res/markers/home_marker.png',
      onTap: onTap,
      onCalloutTap: onCalloutTap
    },
    {
      ..
    }
  ])

There is also the official demo which demonstrates how to use the icons for markers


text:
Q: Deserialize arbitrary XML I'm working on a general system which requires the ability to deserialize arbitrary XML, meaning I don't know ahead of time what tags/attributes are going to be in the XML document. Ideally, XML like this:

Would become an object like this:
new Tag { name = "a",
  attributes = new Dictionary<string,string> {{"att", "1"}},
  elements = new List<Tag> { new Tag { name = "b" } } }

It's perfectly fine if everything deserializes to strings.

A: As suggested, with LINQ to XML you can parse and extract data from an arbitrary XML file:
var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>an elementwith sub-element";
// load XML from string
var xmlDocument = XDocument.Parse(xml);
// OR load XML from file
//var xmlDocument = XDocument.Load(@"d:\temp\input.xml");
// find all elements of type b and in this case take the first one
var bNode = xmlDocument.Descendants("b").FirstOrDefault();
if (bNode != null)
{
    Console.WriteLine(bNode.Value);
}
// find the first element of type a and take the attribute name (TODO error handling)
Console.WriteLine(xmlDocument.Element("a").Attribute("name").Value);

Output is:
with sub-element
test

You can also very easily convert your object to an XML file:
// sample class
public class Entry
{
    public string Name { get; set; }
    public int Count { get; set; }
}

// create and fill the object
var entry = new Entry { Name = "test", Count = 10 };
// create xml container
var xmlToCreate = new XElement("entry",
                    new XAttribute("count", entry.Count),
                    new XElement("name", entry.Name));
// and save it
xmlToCreate.Save(@"d:\temp\test.xml");

Newly created XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<entry count="10">
  <name>test</name>
</entry>

LINQ is very powerful and easy (and IMO intuitive) to use. This MSDN article gives a good insight on LINQ and his range of functions and abilities through good samples. LINQPad - minimalistic but very powerful IDE for .NET comes with very good build-in LINQ to XML tutorials and examples. Finally here is the list of all LINQ to XML extension methods at MSDN.
Another possibility is to use the XmlReader class to parse an arbitrary XML file. Here you are responsible to implement the parsing logic, so it might be cumbersome sometimes. Parsing the same input file using XmlReader looks like this:
public void parseUsingXmlReader(string xmlString)
{
    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
    {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.Indent = true;
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    Console.WriteLine(string.Format("Element - {0}", reader.Name));
                    if (reader.HasAttributes)
                    {
                        for (var i = 0; i < reader.AttributeCount; i++)
                        {
                            Console.WriteLine(string.Format("Attribute - {0}", reader.GetAttribute(i)));
                        }
                        reader.MoveToElement();
                    }
                    break;
                case XmlNodeType.Text:
                    Console.WriteLine(string.Format("Element value - {0}", reader.Value));
                    break;
                //case XmlNodeType.XmlDeclaration:
                //case XmlNodeType.ProcessingInstruction:
                //  Console.WriteLine(reader.Name + " - " + reader.Value);
                //  break;
                case XmlNodeType.Comment:
                    Console.WriteLine(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    Console.WriteLine(reader.Value);
                    break;
            }
        }
    }
}
// use the new function with the input from the first example
parseUsingXmlReader(xml);

The output is:
Element - a
Attribute - 1
Attribute - test
Element value - an element
Element - b
Element value - with sub-element

As you can see, you need to take care of node types, current position, attributes and so on manually.

A: Not a lot of info here.  As an alternative external interface to the Linq for XML approach you can try a dynamic approach.  Here is an example program:
class Program {
    static void Main(string[] args) {
        var xmlstr =
@"

      <c att2='text'>value</c>

";
        dynamic xml = new DynamicXml(xmlstr);
        Console.WriteLine(xml.a[0].att);
        Console.WriteLine(xml.a[0].b[0].attb);
        Console.WriteLine(xml.a[0].b[0].c[0].att2);

        }

    public class DynamicXml: DynamicObject {
        XElement _root;
        IEnumerable<XElement> _xele;

        public DynamicXml(string xml) {
            var xdoc = XDocument.Parse(xml);
            _root = xdoc.Root;
            }

        DynamicXml(XElement root) {
            _root = root;
            }

        DynamicXml(XElement root, IEnumerable<XElement> xele) {
            _root = root;
            _xele = xele;
            }

        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) {
            // you should check binder.CallInfo, but for the example I'm assuming [n] where n is int type indexing
            var idx = (int)indexes[0];
            result = new DynamicXml(_xele.ElementAt(idx));
            return true;
            }

        public override bool TryGetMember(GetMemberBinder binder, out object result) {
            var atr = _root.Attributes(binder.Name).FirstOrDefault();
            if (atr != null) {
                result = atr.Value;
                return true;
                }
            var ele = _root.DescendantsAndSelf(binder.Name);
            if (ele != null) {
                result = new DynamicXml(_root, ele);
                return true;
                }
            result = null;
            return false;
            }
        }
    }

Things to note with this is that XML elements can contain a value as well as attributes.  You need a way to deal with a value.  In the above code you could use a special name like "Value" but then you would not be able to handle and attribute of the same name.


text:
Q: Disable dates in datepicker which are already saved in mysql database I am trying to disable dates in datepicker that have been saved in mysql database and also deactivate all the past dates that one can't do booking on a past date.. I have the following code but its not working and even the datepicker can't pop out please help
Book.php
<?php
include("includes/db.php");
if(isset($_GET['book'])){
    $id_book = $_GET['book'];
    $sql1="SELECT date,date_return,id
            FROM booking
            where id_book ='$id_book'";
    $query = $con->query($sql1);
    $dates_ar = [];
}
if($query !== false && $searchResult->num_rows>0) {
    while ($r=$query->fetch_array()) {
        $begin = new DateTime( $r["date"] );
        $end = new DateTime( $r["return_date"] );
        $end = $end->modify( '+1 day' );
        $interval = new DateInterval('P1D');
        $daterange = new DatePeriod($begin, $interval ,$end);
        foreach ($daterange as $date) {
            $dates_ar[] = $date->format("Y-m-d");
        }
    }
}
?>

<input type="text" name="date" class="form-control" id="date">
<input type="text" name="return_date" class="form-control" id="return_date">

<script type="text/javascript">
$(function() {
    var disabledDays = <?php echo json_encode($date_arr)?>;
    var date = new Date();
    $( "#date").datetimepicker({
        dateFormat: 'Y-m-d',
        beforeShowDay: function(date) {
            var m = date.getMonth() + 1,
            d = date.getDate(),
            y = date.getFullYear(),
            strdate = [y,m,d].join('-');
            if (disabledDays.indexOf(strdate) == -1) {
                return [true, 'ui-state-active', ''];
            }
            return [false];
    }
});
});
</script>

reservation.php
<form action="book.php" method="post" name="a">
    <select  type="text" id="id_book"  name="id_book" />
        <option value"1">ID 1</option>
        <option value="2">ID 2</option>
    </select>
    <input type="submit" name="a"  value="val"/>
</form>

A: This code worked for me;
book.php
<?php

if(isset($_GET['book'])){
$book_id = $_GET['book'];
$sql1 = "select * from booking where equipment_id='$book_id'";
$query = $con->query($sql1);
$dates_ar = [];
}

if($query->num_rows>0) {
    while ($r=$query->fetch_array()) {
        $begin = new DateTime( $r["date"] );
        $end = new DateTime( $r["return_date"] );
        $end = $end->modify( '+1 day' );
        $interval = new DateInterval('P1D');
        $daterange = new DatePeriod($begin, $interval ,$end);
        foreach ($daterange as $date) {
        $dates_ar[] = $date->format("Y-m-d");
    }
}
}
?>

<script type="text/javascript">
$(function () {

    var disabledDate = <?php echo json_encode($dates_ar)?>;

    $('#date').datetimepicker({

    disabledDates: disabledDate,
    minDate:new Date()

    });

});

</script>


text: Q: How to Change google script ownership to another user? How do you change ownership with Google Scripts? I have changed ownerships of the Google Sheet and script library, but the ownership still resides with the existing owner.


text:
Q: How to deserialize json string into object {
   "LocalLocationId [id=1]":{
      "type":"folderlocation",
      "id":{
         "type":"locallocationid",
         "id":1
      },
      "parentId":{
         "type":"locallocationid",
         "id":0
      },
      "name":"Test",
      "accessibleToUser":true,
      "defaultLocation":false,
      "timezoneId":"Asia/Calcutta",
      "children":[]
   },
   "LocalLocationId [id=0]":{
      "type":"folderlocation",
      "id":{
         "type":"locallocationid",
         "id":0
      },
      "parentId":null,
      "name":"Locations",
      "accessibleToUser":false,
      "defaultLocation":false,
      "timezoneId":"Asia/Calcutta",
      "children":[{
         "type":"locallocationid",
         "id":1
      }]
   },
   "allAllowedChildren":[{
      "type":"locallocationid",
      "id":1
   }]
}

How to deserialize above string into java object.
Class im using is
public class Tree {

    @SerializedName("allAllowedChildren")
    private List<Id> allAllowedChildren;

    @SerializedName("LocalLocationId")
    private Map<String, LocalLocationId> localLocationId;

    public class LocalLocationId {
        @SerializedName("type")
        private String type;

        @SerializedName("name")
        private String name;

        @SerializedName("accessibleToUser")
        private boolean accessibleToUser;

        @SerializedName("defaultLocation")
        private boolean defaultLocation;

        @SerializedName("timezoneId")
        private String timezoneId;

        @SerializedName("id")
        private Id id;

        @SerializedName("parentId")
        private Id parentId;

        @SerializedName("children")
        private List<Id> children;

        public String getType() {
            return type;
        }
        public String getName() {
            return name;
        }
        public boolean isAccessibleToUser() {
            return accessibleToUser;
        }
        public boolean isDefaultLocation() {
            return defaultLocation;
        }
        public String getTimezoneId() {
            return timezoneId;
        }
        public Id getId() {
            return id;
        }
        public Id getParentId() {
            return parentId;
        }
        public List<Id> getChildren() {
            return children;
        }
    }

    public class Id {
        private String type;
        private Integer id;

        public String getType() {
            return type;
        }
        public Integer getId() {
            return id;
        }
    }

    public List<Id> getAllAllowedChildren() {
        return allAllowedChildren;
    }
    public Map<String, LocalLocationId> getLocalLocationId() {
        return localLocationId;
    }
}

A: @Kedar
I'll assume you are in control of how the JSON input string is created.
I think the JSON string is not formatted correctly for default GSON deserialization of Map types.
I have modified the input string for your consideration and this results in a non null LocalLocationId
{
   "LocalLocationId":[
   [
     "1",
       {
          "type":"folderlocation",
          "id":{
             "type":"locallocationid",
             "id":1
          },
          "parentId":{
             "type":"locallocationid",
             "id":0
          },
          "name":"Test",
          "accessibleToUser":true,
          "defaultLocation":false,
          "timezoneId":"Asia/Calcutta",
          "children":[]
       }
   ],
   [
     "2",
       {
          "type":"folderlocation",
          "id":{
             "type":"locallocationid",
             "id":0
          },
          "parentId":null,
          "name":"Locations",
          "accessibleToUser":false,
          "defaultLocation":false,
          "timezoneId":"Asia/Calcutta",
          "children":[{
             "type":"locallocationid",
             "id":1
          }]
       }
   ]
   ],
   "allAllowedChildren":[{
      "type":"locallocationid",
      "id":1
   }]
}

Please comment if my assumption about the input string is incorrect.
EDIT 1:
Since input cannot be modified, consider writing custom Deserializer.
Below is the way to register custom deserialisation class
GsonBuilder gsonb = new GsonBuilder();
        gsonb.registerTypeAdapter(Tree.class, new TreeDeserializer());
        Gson gson = gsonb.create();

Below is the TreeDeserializer
public class TreeDeserializer implements JsonDeserializer<Tree> {

    public Tree deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Tree out = new Tree();

        if (json != null) {
            JsonObject obj  = json.getAsJsonObject();
            Set<Map.Entry<String,JsonElement>> entries = obj.entrySet();
            for (Map.Entry<String, JsonElement> e: entries) {
                if (e.getKey().equals("allAllowedChildren")) {
                    Type ft = List.class;
                    System.out.println(context.deserialize(e.getValue(), ft));
                    // TODO add this back into the Tree out object
                } else {
                    // LocalLocationId
                    System.out.println(e.getKey());
                    System.out.println(context.deserialize(e.getValue(), Tree.LocalLocationId.class));

                    // TODO add this back into the Tree out object
                }
            }
        }
        return out;
    }

}

Here is the console output from the Sysouts.
LocalLocationId [id=1]
org.test.StackOverflowAnswers.Tree$LocalLocationId@464bee09
LocalLocationId [id=0]
org.test.StackOverflowAnswers.Tree$LocalLocationId@f6c48ac
[{type=locallocationid, id=1.0}]
org.test.StackOverflowAnswers.Tree@589838eb

I have left TODOs in the deserialiser where you'll need to write custom code to inject the values from deserialisation into the Tree class just created. Hope this helps. Can't provide full implementation, but I think this would be a partial solution

A: User JSONParser which is faster one.
Below is sample. there can be a btter example if you google. Hope this helps.
JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=parser.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2=(JSONObject)array.get(1);
System.out.println("======field \"1\"==========");
System.out.println(obj2.get("1"));
s="{}";
obj=parser.parse(s);
System.out.println(obj);
s="[5,]";
obj=parser.parse(s);
System.out.println(obj);
s="[5,,2]";
obj=parser.parse(s);
System.out.println(obj);

A: You can use Gson ..
String json = "Your json string "
Tree treeObj= new Gson().fromJson(json, Tree .class);

A: You can use ObjectMapper from Jackson -
Tree deserializedTree = new ObjectMapper().readValue(jsonStringOfTree, Tree.class);


text:
Q: Redraw plt figure after adding new axes in a loop After spending hours and hours I still can't figure this, seemingly simple, question out. Here is small snippet of code I am trying to make work (I am running this as a jupyter notebook cell):
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
for i in range(1, 11):
  ax = fig.add_subplot(1, 10, i)
  fig.canvas.draw()
  plt.draw()
  time.sleep(1)

I see my whole figure plotted after cell completes:

But I would like to see image redrawn every time when I add a new axes to it. Am I asking too much of matplotlib?


text:
Q: Could stealing the private key compromise RSA security? I am developing a windows desktop app where the clients applications need to download some data file from a public shared folder. in order to protect the data from tempering i would like to generate RSA private and public keys. keep the public key in my own machine at home and include the private key in all clients.
when i want to send a new file for the clients to download (at well) i hash the file and encrypt the hash with the public key and store it as .sig file alongside the data file in a public shared folder.
now if one of the client users is malicious he can steal the private key from his machine.
the question is : provided that the public key is secret and this is the only use of that key pair and i absolutely don't need any encryption on the data file. does stealing the private key from a client compromise my public key? i.e can the malicious user craft a file signature so that the data file appear to be coming from me?

A: I belive you've designed this backwards.You want to send the public key to the clients and keep the private to yourself. The public key is public; anyone should be able to know it. The private key is private; only the owner should know it.
Rather than hashing the file and encrypting the hash with the public key, you want to sign the file with your private key and let the clients use the public key to verify the signature. The signing operation performs the same idea as your "encrypt the hash" but is the standard construction, and your RSA tools likely include a signing function.


text:
Q: Creating a table with percentiles from raw database I have a database with 160 million something records in it, that is segmented by an code called TMC. The TMC represents a section of highway that is then measured every five minutes for speed and travel time. So the TMC isn't a unique identifier as it the same for every five minutes for all days of the year for that one section of highway. There are 3,440 unique TMCs, as for each TMC, I am trying to calculate a percentile of travel times for an entire year for a specific time of day.
I can get the code for the percentiles to work, but I do not understand how to create and update a table in SQL so the percentiles can be dumped and stored within it. Something to do with the with statement being used to get the percentile does not mesh well with update functions. I normally just use select and copy the data into excel, and then reimport the data into my SQL database, but I am trying to see if I can automate this process as much as possible.
Here is the code that I got so far.
create table TMCF5 (
TMC_code varchar(50),
P95M varchar(50),
P50M varchar(50),
P95A varchar(50),
P50A varchar(50))

go

WITH PERCENTILES_Afternoon AS (SELECT TMC_code, EPOCH, percentile_CONT(.95)
WITHIN GROUP (ORDER BY cast(travel_time_minutes as float)) OVER (PARTITION BY TMC_code) AS P95afternoon, percentile_CONT(.50)
WITHIN GROUP (ORDER BY cast(travel_time_minutes as float)) OVER (PARTITION BY TMC_code) AS P50afternoon  FROM [dbo].[AR_2018_TRUCKS_1_3]
WHERE DATEPART(HOUR, EPOCH) between 16 and 17  AND (WKDAY != 'SAT' and WKDAY != 'SUN'))

insert tmcf5 (tmc_code) select tmc_code from percentiles_afternoon group by tmc_code

go

WITH PERCENTILES_Afternoon2 AS (SELECT TMC_code, EPOCH, percentile_CONT(.95)
WITHIN GROUP (ORDER BY cast(travel_time_minutes as float)) OVER (PARTITION BY TMC_code) AS P95afternoon, percentile_CONT(.50)
WITHIN GROUP (ORDER BY cast(travel_time_minutes as float)) OVER (PARTITION BY TMC_code) AS P50afternoon  FROM [dbo].[AR_2018_TRUCKS_1_3]
WHERE DATEPART(HOUR, EPOCH) between 16 and 17  AND (WKDAY != 'SAT' and WKDAY != 'SUN'))

update TMCF5 set tmcF5.p95A = percentiles_Afternoon2.P95Afternoon from percentiles_afternoon2
join percentiles_afternoon2 on tmcf5.tmc_code = percentiles_afternoon2.tmc_code

A: The text in your error message that you provided in the comments leads me to identify the problem as being present in this statement:
update TMCF5 set tmcF5.p95A = percentiles_Afternoon2.P95Afternoon from percentiles_afternoon2
join percentiles_afternoon2 on tmcf5.tmc_code = percentiles_afternoon2.tmc_code

It has 'percentiles_afternoon2' listed as both tables.  It seems you wanted to reference 'tmcf5' as one of your objects.
Also, if your first insert statement purely serves the purpose of bringing in your tmc_codes, then just simplify the query to:
-- no cte's

insert     tmcf5 (tmc_code)
select
distinct   tmc_code
from       AR_2018_TRUCKS_1_3;


text:
Q: Passing a Bash exit code into another script from .bashrc hey guys I'm having an issue passing a exit code from my ~/.bashrc file into another script continually (as in, a new code each time a command is executed). I currently have the following
.bashrc
generateFlag()
{
    local flag="$?" ; PS1=''
}
PROMPT_COMMAND=generateFlag

. ~/.scipts/prompt.sh $flag

My prompt script is pretty much this
echo $1

Anyone know a way to get this working??

A: .bashrc :
# some code before
export FLAG=$?

exec script :
~/.scripts/prompt.sh $FLAG


text:
Q: What is a good way to store metadata for an mp3 sound database in iOS? I will be writing a music program and need to store many sounds in mp3 format.  I anticipate needing some form of database containing information other than the sound itself so that the sounds can be used procedurally.  How can I do this so that (1) it is useful and convenient for me as I write my app, and (2) so that I can efficiently manage this sound database in my app, and scale it easily as I go.  Do I need a data structure that encompasses the mp3 file plus additional data, or is it possible to store the data elsewhere, cataloging the filenames and paths of the physical mp3s in this datafile?
There must be examples out there that have done this very efficiently - any suggestions or sample code I should study?

A: Sound in DB??

*

*You may host the files in somewhere and download it ,Save the url
path to the DB and work on

*Otherwise You need to store files in application in the filestructure
itself add the filepath to db and fetch it accordingly

A: Depending on the information you need to store, each mp3 itself actually (potentially) holds the title, artist, album cover and more. In python there are a few modules for reading and writing this data, mutagen being a pretty solid one.
sudo pip install mutagen


text:
Q: Collecting random year from Random Date So I have generated a random date from two dates
var dateOfInterest =  function randomDate(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}

randomDate(new Date(2012, 0, 1), new Date());

Now I need to collect the year of the random date generated with the code:
var yearOfInterest = dateOfInterest.getFullYear();
This does not work. I would appreciate the assistance. Thank you.

A: A function definition does not need the var, just assign the function itself, then call it to receive the return value.
I've placed the getFullYear in the function after creating a new Date and changed the function name to a more describing one: getRandomYearBetweenDates

function getRandomYearBetweenDates(start, end) {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())).getFullYear();
}

const res = getRandomYearBetweenDates(new Date(2012, 0, 1), new Date());
console.log(res);


text:
Q: Where to write code in Appium iOS test automation software? I am new to automation and trying to use Appium(Mac app) for writing test scripts on iOS app.
I have managed to load my app successfully on Appium and also used Appium Inspector.
There is a Record button which records my actions in Appium inspector.
However, my question is how do I save these recorded scripts for reuse?
Secondly, I also want to manually write test scripts using Java, but currently don't know where to write code using Appium Mac app.
I have read the starter guide on Appium website and seen some videos but cannot find any app usage related information.
Any help(links, tutorial video) will be appreciated.
P.S. I do not use Selenium.

A: *

*My suggestion is to not use the record feature in Appium, it's not stable and hard to maintain.

*You can write your java-automation-code on Eclipse/intellij(and all java IDE)
You have a lot of information on internet, you can start here:
Appium - Git - Sample - java
Try to make it run, and take it from there.
You always can ask at discuss.appium.io and see examples.
Good luck, hope it's helps a little.

A: You can write your script in the same way as you used to right in Selenium means you can choose any IDE (in my case I'm working on Eclipse Juno) and then just pass all the capabilities if you will use TestNG framework then run as TestNG.

A: You can use any programming language supported by Appium where you feel better.
Setup environment and create test scripts. you can learn from:
Appium
Jave Sample


text:
Q: trouble installing haskell on mac So, I am eager to learn haskell and thought of setting my mac (mavericks) for the same..
I downloaded the package from :https://www.haskell.org/platform/mac.html
but when I try to run ghci
I get this
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... <command line>: can't load .so/.DLL for: libiconv.dylib (dlopen(libiconv.dylib, 9): image not found)

and then it just exits?

A: The Haskell Platform has been a great boon in starting Haskell for a long time, but is known to not always work for all versions of system libraries and platforms. In this case, it looks like you're missing a common library to handle character encodings (libiconv).
One alternative for installing a working version of ghc/ghci and working with Haskell is a newer project - the Haskell Tool Stack. This is a program that can be used to automatically download and configure GHC and Haskell libraries on a per project basis. In your case, one of its features is a reduced dependence on global state; every new project makes sure to install a version of GHC and libraries that are known to work with your project and its configuration. You can find more documentation about it here.

A: You must make sure that your paths don't point to an alternate libiconv beyond the system standard.
If you can run ghci under sudo it may well be that you have the problem described here:
Requiring sudo to run ghci on OSx


text:
Q: How do I restart apache as non-root (using a git-hook)? For one specific user I want to be able to restart Apache. This user does have sudo privileges and I could run sudo /etc/init.d/apache2 reload, but I want to include this restart script in a git post-receive hook. So this would prompt for the password and fail. So the question is: what is the proper way to allow this user to restart apache, without requiring sudo? I want to restrict option to only restarting Apache, and only this particular user.

A: You should consider using sudo with the NOPASSWD config.
See man 5 sudoers
Ex:
Host_Alias     LOCAL=192.168.0.1
user_foobar    LOCAL=NOPASSWD: /etc/init.d/apache2


text:
Q: What's the act of drawing "squiggles" over something wrong you have written called Let's say if I write 2 + 2 = 5 with a pen, and realize that was wrong. What's the act of drawing "squiggles"/lines over the answer called?

A: When you draw over something in that sense, you cross out (or are crossing out) a mistake:

[Merriam-Webster]
: to draw a line through (something) to show that it is wrong · cross out a mistake · He had crossed his name out.

It doesn't need to be a squiggle; it can be anything that shows you are covering up the mistake.

A: If you want to distinguish between neat "crossing out" and the messy appearance from drawing lots of "squiggles" you can say "scribble out"

{teacher} If you make a mistake just take your ruler and draw a line through it. Don't scribble out your mistakes, because that makes your book look messy.


text:
Q: Is there a way to execute a command in behavior from eventrigger? The title pretty much explains the question.
I have the following in the view in a Template:
<i:Interaction.Triggers>
    <i:EventTrigger EventName="SizeChanged">
        <i:InvokeCommandAction>
            <i:InvokeCommandAction.Command>
                <Binding Source="{StaticResource eventBindingHelper}" Path="DataC.SizeChangedCommand"></Binding>
            </i:InvokeCommandAction.Command>
            <i:InvokeCommandAction.CommandParameter>
                <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type igDP:LabelPresenter}}"/>
            </i:InvokeCommandAction.CommandParameter>
        </i:InvokeCommandAction>
    </i:EventTrigger>
</i:Interaction.Triggers>

The command binding works if it's bound to the viewmodel. But i would like to bind it to a behavior and i can't seem to find a way.

A: Make sure to add the reference to Behaviours SDK, and then you can do the following:
<Interactivity:Interaction.Behaviors>
  <Core:EventTriggerBehavior EventName="Tapped" SourceObject="{Binding ElementName="Control to trigger"}"> //Bind behaviour the the element you want to trigger
    <Core:InvokeCommandAction Command="{Binding Command}" CommandParameter="{Binding parameter}"/> // Bind command and parameter to behaviour
  </Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>

Then you can switch between the EventNames in EventTriggerBehaviour to trigger the controls as you want.

A: I used
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Tapped"
                    SourceName="myControlName">
        <i:InvokeCommandAction Command="{Binding Command}"
                               CommandParameter="{Binding parameter}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Similar to the accepted answer but with different namespaces/class names.


text:
Q: How to manage json in html template sent through SSE flask I need to push json to my HTML template endlessly. On html template I want to manage this json and insert data from it to html page.
Here is my code:
@app.route('/stream')
def stream():
    def event_stream():
        counter = 0
        while True:
            yield "data: {}\n\n".format({"a": "1", "b": "2"})
            time.sleep(10)
    return Response(event_stream(), mimetype="text/event-stream")

and html template:
<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Webpage</title>
</head>
<body>
    <script>
        var eventSource = new EventSource("/stream");
            eventSource.onmessage = function(e) {
            alert(e.data);
        };
    </script>
</body>
</html>

For now alert does not work. And my json is displayed on HTML page even if to remove js script from html. How can I manipulate with json in my html?

A: You can return a json to your AJAX call and use it from "success".
Flask:
@app.route('/my_route',methods=['GET','POST'])
def my_function():
    request_json=request.get_json()
    html_string= some_processing(request_json)
    return jsonify(result=html_string)

AJAX:
success : function(data){ $('#id-where_html_goes').html(data.result); },


text:
Q: How can you add text to a string and then save and print it on the screen in Kaboom.js? Kia ora everyone!
I'm trying to make my own input system in Kaboom.js by adding functions like the below and adding each key to a string called i (short for input).
keyPress("j", () => { i.concat("j"); });
Then, I try and console.log i. (i do it like console.log(i);) And for some reason I get nothing. I think it's because it's not logging an update to the string?
Is there a better method I can use, and what is wrong with my program?
Ngā mihi
Florence

A: If your big long string is called inputString then something like this ought to come close:
let inputString = "";
k.onKeyPress("a", event => {
   inputString.concat("a");
   console.info(inputString);
   console.info(event);
});

Rather than copy this out for every different key you're probably best trying to catch all keypresses and then check the properties of the event to determine if it's a relevant key, not an arrow key etc..


text:
Q: MySQL Unknown InnoDB Options on Command Line I'm trying to set some innodb settings when starting mysql on the command line:
mysql -p*password* --skip-innodb_doublewrite

mysql -p*password* --innodb_flush_log_at_trx_commit=2

Which appear to be possible from the MySQL docs:

Command-Line Format  --innodb-doublewrite ... This variable can be turned off with --skip-innodb_doublewrite
Command-Line Format  --innodb_flush_log_at_trx_commit[=#]

However, when executing I get:
mysql: unknown option '--skip-innodb_doublewrite'

mysql: unknown variable 'innodb_flush_log_at_trx_commit=0'

What's going on? Have I completely missinterpreted the docs?
I'm using MySQL 5.5.45

A: These are server options, not client options, so they need to be specified on the mysqld command line. However, as the documentation says:

Many system variables can be changed at runtime (see Section 6.1.6.2, "Dynamic System Variables").

If you go to that page, the first line says:

Many server system variables are dynamic and can be set at runtime using SET GLOBAL or SET SESSION.

There's a table that lists all the dynamic variables. innodb_doublewrite is not one of them, so it can only be specified at server startup (either with a command-line argument or in the configuration file). But innodb_flush_log_at_trx_commit is listed as a global variable, so you can do:
mysql -u root -p"password" -e "set global innodb_flush_log_at_trx_commit = 0"

A: If anyone is receiving the message unknown variable 'innodb_flush_log_at_trx_commit=0' trying to set this configuration in a my.ini or mysql.cnf file, the line innodb_flush_log_at_trx_commit=0 must be written under [mysqld] section.


text:
Q: CakePHP 3 : How to prepare cakephp table paginate header for localization? My table header look below
<?= $this->Paginator->sort('name')?>

After generate POT file 'name' has not generate 'msgid' and 'msgstr'.
I have tried like below code but result is same.
<?= __($this->Paginator->sort('name')) ?>

How I will prepare it before POT file generate ?

A: The name of the key in sort function is used to sort the recordset. You cannot use it to generate 'msgid' and 'msgstr' in your POT file.
You can generate msgid and msgstr simply by defining it elsewhere like
<? = __('name') ?>;

PaginatorHelper::sort($key, $title = null, $options = array())

For your reference:
https://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html

A: You can write your label like
<?= $this->Paginator->sort('name',__('Name')) ?>


text:
Q: HTML page not rendering properly on Apache on Raspberry Pi I purchased a template from monstertemplates.com - and put it on my Raspberry Pi that is running the LAMP stack.  I also have jQuery installed.  When I pull up the page it is only text - no CSS and no graphics.
These are the modules that are currently loaded:
libjs-jquery is already the newest version.
libjs-jquery set to manually installed.
The following packages were automatically installed and are no longer required:
  apache2.2-bin apache2.2-common lesstif2 liblcms1 libopenjpeg2 libpoppler19
  libxp6

And this is the information on the template...
1170 Grid System, CSS 3, HTML 5, JQuery, LESS, Semantic Code, Valid Coding
What am I missing?
UPDATE ---  It was a simple rights issue - no rights setup on the sub-directories that contain javascript, images, and css

A: Need some more information on what kind of errors you can see in your browser console, but my first guess is that there's something wrong with the location of the sites assets (images and css files etc).
Have you renamed any files or folders? Make sure everything is named correctly.
If that isn't the case, can you open the console on any browser and edit your comment with any error messages?


text:
Q: List of dictionaries of lists into organised pandas df I have a dictionary:
[
  {
    'dates': ['2019-12-01'],
    'periods': ['1', '1', '1', '1']
  },
  {
    'dates': ['2019-12-02', '2019-12-03', '2019-12-04', '2019-12-05'],
    'hh_periods': ['1', '1', '1', '20']
  }
]

Ideally, I would like to build a pd.Dataframe() with colums=["p1", "p2", "p3", "p4"]
That would look like this:
           p1 p2 p3 p4
dates
2019-12-01  1  1  1  1
2019-12-02  1  1  1  20
2019-12-03  1  1  1  20
2019-12-04  1  1  1  20
2019-12-05  1  1  1  20

For my use case I need something fast, I have tried:
p = pd.DataFrame(data).explode('dates')
p.set_index('dates', inplace=True)

Which is close but ends up with:
               hh_periods
dates
2019-12-01   [1, 1, 1, 1]
2019-12-01   [1, 1, 1, 1]
2019-12-02  [1, 1, 1, 20]
2019-12-03  [1, 1, 1, 20]

Which is not ideal.
* UPDATE *
So I have used anky_91 answer of:
cols = ["dates", "p1", "p2", "p3", "p4"]
p = pd.DataFrame(self.build()).explode('dates')
var = p[['dates']].join(pd.DataFrame(p.ffill(axis=1).iloc[:, -1].tolist()))
var.columns = cols

Now this returns which visually looks correct:
dates          p1   p2  p3   p4
0  2019-12-07  1    0    0    0
0  2019-12-14  1    0    0    0
0  2019-12-07  1    0    0    0
0  2019-12-14  1    0    0    0
1  2019-12-01  1    0    0    0

But when I test with:
[
 {
  'dates': ['2019-12-07', '2019-12-14'],
  'periods': ['333333', '0', '0', '0']
 },
 {
  'dates': ['2019-12-01', '2019-12-08', '2019-12-15'],
  'periods': ['1', '1', '333', '1']
 }
]

I get a df like this:
        dates            p1 p2 p3 p4
0  2019-12-07  333333    0    0    0
0  2019-12-14  333333    0    0    0
0  2019-12-07  333333    0    0    0
0  2019-12-14  333333    0    0    0
1  2019-12-01  333333    0    0    0
1  2019-12-08  333333    0    0    0
1  2019-12-15  333333    0    0    0
1  2019-12-01  333333    0    0    0

So only p1 is getting picked up... :/
p = pd.DataFrame(self.build()).explode('dates')
print(p)

Produces the old form as expected :
      dates         hh_periods
0  2019-12-07  [333333, 0, 0, 0]
0  2019-12-14  [333333, 0, 0, 0]
1  2019-12-01     [1, 1, 333, 1]
1  2019-12-08     [1, 1, 333, 1]

    ( ... )

A: You can fix your p with
p = p.reset_index().join(pd.DataFrame(p.hh_periods.tolist()))

A: You can use:
p = pd.DataFrame(data).explode('dates')
p = p[['dates']].join(pd.DataFrame(p.ffill(axis=1).iloc[:,-1].tolist())
                 .rename(columns=lambda x: f"p{x+1}"))

        dates p1 p2 p3  p4
0  2019-12-01  1  1  1   1
1  2019-12-02  1  1  1  20
1  2019-12-03  1  1  1  20
1  2019-12-04  1  1  1  20
1  2019-12-05  1  1  1  20

EDIT per new list of dicts:
p = pd.DataFrame(data).explode('dates').reset_index(drop=True)
var = p[['dates']].join(pd.DataFrame(p.ffill(axis=1).iloc[:,-1].tolist()))
#var.columns = your_list_of_columns
print(var)

        dates       0  1    2  3
0  2019-12-07  333333  0    0  0
1  2019-12-14  333333  0    0  0
2  2019-12-01       1  1  333  1
3  2019-12-08       1  1  333  1
4  2019-12-15       1  1  333  1


text:
Q: Painless tips to work with MS word after using LaTeX during the past 7 years I have used LaTeX during the past 7 years and I have forgotten all about MS Word. Now I need to start using MS Word for my job (and exclusively, no LaTeX).
Have you been in similar positions? what are some tips to do the same stuff in MS Word without going crazy and loosing my patience?
Maybe you master both typesetting systems and would like to share hints and aids for this desperate.

A: Biggest tip, and an easy one if you're used to LaTeX or even html: use styles properly rather than formatting commands.
If you use citations and cross references, use named references until the final version (e.g. "see figure fig_system_layout"), and put "fig_system_layout" in the caption to that figure. You may want to make sure that anything like this that you use fails a spell check.
I'm a little out of date on word so you may need to adapt this: when creating a figure, create a drawing canvas (if that's still the term they use), add something (like a placeholder caption) then import the figure into the canvas. This will stop the caption escaping. Last time I tried there was an official solution to this but that didn't work as well.


text:
Q: How to build parameters for System.cmd? I want to use System.cmd run "convert" from ImageMagick, but I am having difficulty
System.cmd("convert", ["origin.jpg", "-fill", "black", "-pointsize", "12", "-gravity", "SouthWest", "-draw", "\"text +4,+4 'Test hello world!'\"", "output.jpg"])

The args -draw 's value is \"text +4,+4 'Test hello world!'\", but ImageMagick requires "text +4,+4 'Test hello world!'" Do not need to escape double quotes.
How can I do it?

A: You don't need the outer double quotes here with System.cmd/3. You need them when running the command from the shell because the argument contains spaces and without the outer double quotes the shell will split the whole thing on every space and end up passing the equivalent of ["text", "+4,+4", "Test hello world!"]. The following should work:
System.cmd(..., [..., "text +4,+4 'Test hello world!'", ...])


text:
Q: Selectable - skip elements I have:

a1	a2	a3	a4	a5

b1	b2	b3	b4	b5

c1	c2	c3	c4	c5

d1	d2	d3	d4	d5

e1	e2	e3	e4	e5

f1	ff2	f3	f4	f5

and:
$( "#table" ).selectable({
    filter: 'td:not(.no)',
    stop: function( event, ui ) {
        var selected = $(this).find('.ui-selected');

        console.log(selected);
    }
});

FIDDLE: http://jsfiddle.net/5RxB2/
How is the best way to skip elements? I would like have always a rectangle or square.
Some examples:
1) I selected a1, a2, b1, b2 - this is OK
2) I selected a1, a2, a3, b1, b2, b3 - this is OK
3) I selected a2, b2 - this is OK
4) I selected:
a1, a2, a3, a4
b1, b2, b3, b4
c1, c2,  a4  //a3 haveclass no
d1, d2, d3, d4
So, I would like to receive a rectangle or square. This should get always first selected (in this example a1) and reject others than (a1, a2, b1, b2) - so this should reject TD upward and sideward from c3 (class no).
Is this possible? If yes, how? :)

A: Option 1) Using selector in a filter:
$( "#table" ).selectable({
    filter: 'td:not(.no)',
    stop: function( event, ui ) {
        var selected = $(this).find('.ui-selected');

        console.log(selected.filter(':first,:last'));
    }
});

Fiddle

Option 2) Using selector in the find:
$( "#table" ).selectable({
    filter: 'td:not(.no)',
    stop: function( event, ui ) {
        var selected = $(this).find('.ui-selected:first,.ui-selected:last');

        console.log(selected);
    }
});

Fiddle


text:
Q: The meaning of ./ before a command While I was executing a C program in terminal I wrote:
gcc -o demo demo.c
./demo

Actually my doubt is why we write ./ before demo and what does it mean?

A: When we execute any command in the terminal it is going to look for it in the PATH environment variable. By using ./ (relative path) we are telling the shell to look for that command in our current directory.
Check echo $PATH
There are two way to execute any commands

*

*Putting its path in the PATH environment variable

*Using the full path or a relative path to that programme (Ex. /opt/xyz/bin/someprogramme )

A:
When bash interprets the command line, it looks for commands in
  locations described in the variable $PATH. To see it type:
echo $PATH

Normally, he current directory is not in that list.
  The reason for not having the current directory on that list is security.
The ./ says: look in the current directory for my command rather than looking at all the directories specified in $PATH.

More about:

*

*About the Use of Dot-Slash in Commands

*Why do you need ./ (dot-slash) before script name to run it in bash?

*What is the meaning of ./ before a given path?

A: You put "./" before every program you wish to execute.
Otherwise the terminal doesn't know what to do with "demo" file

A: The "./" before a file name stand for "execute this file in th current directory" if the file that you want to execute is not in the same directory you are in you will need to specify the path o the file like this:
Xxxxx@xxxx /Documents/filetoexecute


text:
Q: Statistical test of fairness of partitioning I have a question about a statistical test, but I lack the proper terminology so I'll try to explain in my own words.
Say I have a collection of $N$ objects. The collection is partitioned into $p$ chunks of $n$ objects each (so $N = np$). I do not have access to the method of chunking but I would like to know if it is fair in the following sense.
Each object has a numerical score. I determine a threshold and count the number of elements of each chunk that are above that threshold. These counts are $x_1, ..., x_p$. What statistical test can I apply to these counts which might tell me whether the chunking method is fair or biased?

A: You can use goodness of fit chi square test.
Let $\bar x = \frac 1 p \sum _{i=1}^px_i$.
$S=\sum_{i=1}^p (x_i-\bar x)^2$
Then $$ \chi^2 = \frac S {\bar x} +\frac S{n-\bar x}$$ follows chi square distribution with $q-1$ degree of freedom asymptotically.


text:
Q: Best practices for serializing objects to a custom string format for use in an output file I was just about to implement an override of ToString() on a particular business class in order to produce an Excel-friendly format to write to an output file, which will be picked up later and processed. Here's what the data is supposed to look like:
5555555 "LASTN SR, FIRSTN"  5555555555  13956 STREET RD     TOWNSVILLE  MI  48890   25.88   01-003-06-0934

It's no big deal for me to just make a format string and override ToString(), but that will change the behavior of ToString() for any objects I decide to serialize this way, making the implementation of ToString() all ragged across the library.
Now, I've been reading up on IFormatProvider, and a class implementing it sounds like a good idea, but I'm still a little confused about where all this logic should reside and how to build the formatter class.
What do you guys do when you need to make a CSV, tab-delimited or some other non-XML arbitrary string out of an object?

A: As rule of thumb I advocate only overriding toString as a tool for debugging, if it's for business logic it should be an explicit method on the class/interface.
For simple serialization like this I'd suggest having a separate class that knows about your CSV output library and your business objects that does the serialization rather than pushing the serialization into the business objects themselves.
This way you end up with a class per output format that produces a view of your model.
For more complex serialization where you're trying to write out an object graph for persistence I'd consider putting it in the business classes - but only if it makes for cleaner code.

A: Here is a generic fashion for creating CSV from a list of objects, using reflection:
public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
    Type t = typeof(T);
    FieldInfo[] fields = t.GetFields();

    string header = String.Join(separator, fields.Select(f => f.Name).ToArray());

    StringBuilder csvdata = new StringBuilder();
    csvdata.AppendLine(header);

    foreach (var o in objectlist)
        csvdata.AppendLine(ToCsvFields(separator, fields, o));

    return csvdata.ToString();
}

public static string ToCsvFields(string separator, FieldInfo[] fields, object o)
{
    StringBuilder linie = new StringBuilder();

    foreach (var f in fields)
    {
        if (linie.Length > 0)
            linie.Append(separator);

        var x = f.GetValue(o);

        if (x != null)
            linie.Append(x.ToString());
    }

    return linie.ToString();
}

Many variations can be made, such as writing out directly to a file in ToCsv(), or replacing the StringBuilder with an IEnumerable and yield statements.

A: Here is a simplified version of Per Hejndorf's CSV idea (without the memory overhead as it yields each line in turn). Due to popular demand it also supports both fields and simple properties by use of Concat.
Update 18 May 2017
This example was never intended to be a complete solution, just advancing the original idea posted by Per Hejndorf. To generate valid CSV you need to replace any text delimiter characters, within the text, with a sequence of 2 delimiter characters. e.g. a simple .Replace("\"", "\"\"").
Update 12 Feb 2016
After using my own code again in a project today, I realised I should not have taken anything for granted when I started from the example of @Per Hejndorf. It makes more sense to assume a default delimiter of "," (comma) and make the delimiter the second, optional, parameter. My own library version also provides a 3rd header parameter that controls whether a header row should be returned as sometimes you only want the data.
e.g.
public static IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist, string separator = ",", bool header = true)
{
    FieldInfo[] fields = typeof(T).GetFields();
    PropertyInfo[] properties = typeof(T).GetProperties();
    if (header)
    {
        yield return String.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p=>p.Name)).ToArray());
    }
    foreach (var o in objectlist)
    {
        yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString())
            .Concat(properties.Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
    }
}

so you then use it like this for comma delimited:
foreach (var line in ToCsv(objects))
{
    Console.WriteLine(line);
}

or like this for another delimiter (e.g. TAB):
foreach (var line in ToCsv(objects, "\t"))
{
    Console.WriteLine(line);
}

Practical examples
write list to a comma-delimited CSV file
using (TextWriter tw = File.CreateText("C:\testoutput.csv"))
{
    foreach (var line in ToCsv(objects))
    {
        tw.WriteLine(line);
    }
}

or write it tab-delimited
using (TextWriter tw = File.CreateText("C:\testoutput.txt"))
{
    foreach (var line in ToCsv(objects, "\t"))
    {
        tw.WriteLine(line);
    }
}

If you have complex fields/properties you will need to filter them out of the select clauses.

Previous versions and details below:
Here is a simplified version of Per Hejndorf's CSV idea (without the memory overhead as it yields each line in turn) and has only 4 lines of code :)
public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
    FieldInfo[] fields = typeof(T).GetFields();
    yield return String.Join(separator, fields.Select(f => f.Name).ToArray());
    foreach (var o in objectlist)
    {
        yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString()).ToArray());
    }
}

You can iterate it like this:
foreach (var line in ToCsv(",", objects))
{
    Console.WriteLine(line);
}

where objects is a strongly typed list of objects.
This variation includes both public fields and simple public properties:
public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
    FieldInfo[] fields = typeof(T).GetFields();
    PropertyInfo[] properties = typeof(T).GetProperties();
    yield return String.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p=>p.Name)).ToArray());
    foreach (var o in objectlist)
    {
        yield return string.Join(separator, fields.Select(f=>(f.GetValue(o) ?? "").ToString())
            .Concat(properties.Select(p=>(p.GetValue(o,null) ?? "").ToString())).ToArray());
    }
}

A: The problem with the solutions I found so far is that they don't let you export a subset of properties, but only the entire object. Most of the time, when we need to export data in CSV, we need to "tailor" its format in a precise way, so I created this simple extension method that allows me to do that by passing an array of parameters of type Func<T, string> to specify the mapping.
public static string ToCsv<T>(this IEnumerable<T> list, params Func<T, string>[] properties)
{
    var columns = properties.Select(func => list.Select(func).ToList()).ToList();

    var stringBuilder = new StringBuilder();

    var rowsCount = columns.First().Count;

    for (var i = 0; i < rowsCount; i++)
    {
        var rowCells = columns.Select(column => column[i]);

        stringBuilder.AppendLine(string.Join(",", rowCells));
    }

    return stringBuilder.ToString();
}

Usage:
philosophers.ToCsv(x => x.LastName, x => x.FirstName)

Generates:
Hayek,Friedrich
Rothbard,Murray
Brent,David

A: I had an issue the HiTech Magic's variation were two properties with the same value, only one would get populated. This seems to have fixed it:
        public static IEnumerable<string> ToCsv<T>(string separator, IEnumerable<T> objectlist)
    {
        FieldInfo[] fields = typeof(T).GetFields();
        PropertyInfo[] properties = typeof(T).GetProperties();
        yield return String.Join(separator, fields.Select(f => f.Name).Union(properties.Select(p => p.Name)).ToArray());
        foreach (var o in objectlist)
        {
            yield return string.Join(separator, (properties.Select(p => (p.GetValue(o, null) ?? "").ToString())).ToArray());
        }
    }

A: Gone Coding's answer was very helpful. I made some changes to it in order to handle text gremlins that would hose the output.
 /******************************************************/
    public static IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist, string separator = ",", bool header = true)
    {
       FieldInfo[] fields = typeof(T).GetFields();
       PropertyInfo[] properties = typeof(T).GetProperties();
       string str1;
       string str2;

       if(header)
       {
          str1 = String.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p => p.Name)).ToArray());
          str1 = str1 + Environment.NewLine;
          yield return str1;
       }
       foreach(var o in objectlist)
       {
          //regex is to remove any misplaced returns or tabs that would
          //really mess up a csv conversion.
          str2 = string.Join(separator, fields.Select(f => (Regex.Replace(Convert.ToString(f.GetValue(o)), @"\t|\n|\r", "") ?? "").Trim())
             .Concat(properties.Select(p => (Regex.Replace(Convert.ToString(p.GetValue(o, null)), @"\t|\n|\r", "") ?? "").Trim())).ToArray());

          str2 = str2 + Environment.NewLine;
          yield return str2;
       }
    }

A: ServiceStack.Text is a popular NuGet package that supports CSV serialization. Then this will be all the code you need:
CsvSerializer.SerializeToCsv(foo)

If you don't want the headers, use this code first:
CsvConfig<Foo>.OmitHeaders = true;

A: Gone Coding's answer is great! I made a couple changes to Gone Coding's answer to qualify fields with double quotes and for the properties iterator to ignore any properties without index parameters i.e. properties in a class that enable property name getters and setters:
FieldInfo[] fields = typeof(T).GetFields();
PropertyInfo[] properties = typeof(T).GetProperties().Where(x => x.GetIndexParameters().Length == 0).ToArray();
yield return string.Join(separator, fields.Select(f => f.Name).Concat(properties.Select(p => p.Name)).ToArray());
foreach (var o in objectlist)
{
    yield return string.Join(separator, fields.Select(f => "\"" + (( f.GetValue(o) ?? "").ToString()) + "\"")
                    .Concat(properties.Select(p => ("\"" + (p.GetValue(o, null) ?? "").ToString()) + "\"")).ToArray());
}