text:
Q: Confused by RefererDeniedMapError I'm trying to use the Google Maps Javascript Geocoder code.  I figured I'd start with their example at https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
I copied their code exactly, putting in my Browser Key where it said YOUR_API_KEY,
and the page seems to load for a moment, and then I get this error in my console:

Google Maps API error: RefererDeniedMapError

And a Javascript alert telling me that it was unable to load.
I have checked my developer console and I have enabled the Google Maps JavaScript API, and I don't have any referrers set up for that key (which is supposed to let all requests through), and yet I still get this error.
I have to believe I still have a setting wrong somewhere, but the console is so simple to use I can't identify where.  Can anyone give me the benefits of their experiences on setting up the Browser key to work properly?
Thanks in advance,
DW


text:
Q: Are there non-orthogonal "normal" modes for non-identical coupled oscillators? The question is broad, I will specify an example to elaborate what I'm asking.
Suppose I have two different LC circuits inductively coupled (or capacitively, but the question I have will be relevant to both so for simplicity lets consider inductive coupling) as below.

Starting from Kirchoff's Voltage and Current Laws, and using the constitutive relations one can arrive at the equations of motion which look something like $$ \boldsymbol{A}\ddot{\vec{v}}= \boldsymbol{B}\vec{v}$$
here $\vec{v}=(v_1 \, v_5)^{T}$ where $v_1$ is the voltage across $C_1$ and $v_5$ is the voltage across $C_5$. One can easily check that this circuit has 2 degrees of freedom. Now I left $\boldsymbol{A},\boldsymbol{B}$ without explicitly stating them because the question is more general than this particular equation. Now I'm trying to find the normal modes of this circuit. But it occurs to me that $\boldsymbol{A},\boldsymbol{B}$ are guaranteed to be of rank $2$ and diagonalizable so we can find the eigenvectors for this generalized eigenvalue problem and be guaranteed they form a basis for $\mathbb{R}^2$. So we can decouple the equations of motion into 2 independent second order ODEs.
The problem is that normal modes are defined to be the orthogonal, that is the resulting eigenvectors are orthogonal and hence it is a different decoupling. It specifically requires $\boldsymbol{A},\boldsymbol{B}$ to be symmetric such that the resulting eigenvectors form an orthogonal basis.
Check this discussion on transforming second order linear systems of ODEs of same form as this.
So this leads me to think that if the matrices are not symmetric, the eigenvectors will not be orthogonal therefore no normal modes. But a decoupling is possible it seems. What is this decoupling and is this true - non-identical coupled oscillators don't have normal modes?
One note is that the lack of symmetry in the oscillators could justify not being able to exploit symmetric and anti symmetric normal modes (for a basic example like this) so perhaps not too surprising, but I was under the impression all coupled oscillators have normal modes.
Any help is appreciated!

A: The math in the link or post is not very clear. When done carefully, the prescription to find the modes becomes intuitive: it is equation $(*)$ below.
Start by writing $\boldsymbol{A}\ddot{\vec{v}}= \boldsymbol{B}\vec{v}$ as
$$
 -\boldsymbol{A}\omega^2 \vec{v}_0= \boldsymbol{B}\vec{v}_0
\quad \Rightarrow  \quad   (\boldsymbol{A}\omega^2+\boldsymbol{B}) \vec{v}_0= 0,
$$
thanks to the usual substitution $\vec{v}(t) = \vec{v}_0 e^{-i \omega t}$.
Now, call $\boldsymbol{C}(\omega) =  \boldsymbol{A}\omega^2+\boldsymbol{B}$. The above system only has the trivial solution $ \vec{v}_0=0$ if $\boldsymbol{C}(\omega)$ has maximum rank (in this case 2). Therefore, to have non-trivial oscillatory solutions you have to require that $\omega$ takes some special value so that a solution with a non-zero amplitude $\vec{v}_0$ can exist. This amounts to require that the determinant of $ \boldsymbol{C}(\omega)$ is zero.
To summarize, you can find the frequencies of the natural modes of the system by solving the equation
$$
det[\boldsymbol{C}(\omega)]  = 0
\quad \quad (*)
$$
that is a polynomial equation in $\omega$. The solutions are the frequencies of the mode: for you 2D case you will find two (complex) solutions. As usual, the real part tells you the frequency of the oscillation, the imaginary part tells you how fast the mode decays or grows (depending on its sign).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to avoid this "brute force" idea regarding my project? I'm working on a school project right now which is based on the Vine website. Basically the goal of my project is to display on a screen many videos (from vines url) playing one by one.
First I use the following process : I put an Iframe in my html code and then I update the src of this Iframe every 6 seconds, for the moment this step works perfectly ! Every 6000 milliseconds videos are switching between them.
If this step works it's because I already have my three links stored as Strings in an array and then I simply called a function which chose a random index in this array.
BUT now I encounter a bigger problem, what I want to do is to add working
links (by "working" I obviously mean valid, when I try to reach the URL it does not return 404) into my array, and the issue is that I don't really know how to handle this but I guess there is no thousands solutions.
My main idea was a kind of brute force : I wanted to generate random links and tried every generated links' connection. The function which creates the random links is done but my issue is when it comes to check the connectivity.. I tried a XML method from this thread then I found other topics about it and I ended up with it :
function testUrlConnection(urlCheck){

"use strict";

var xhr = new XMLHttpRequest();

xhr.open('HEAD', file, true);
xhr.setRequestHeader("Access-Control-Allow-Origin","*")
xhr.send();

console.log(xhr.status); //return 0 no matter what

        if (xhr.status != "404") {
            console.log(urlCheck + " connection exist!");
    } else {
            console.log(urlCheck+ " connection doesn't exist!");
        }
}

Thus I tried a lot of modifications but I discovered that it was an Origin or Domain issue.
Sorry for making it long but actually this is not really a code issue but more a way of handling this, do you think this "brute force" idea can be pursued or do I need to handle this in any other way ? If yes which advice can you give me ?
Thank you,
NEAK

A: While this idea works I think you should try a different approach, like infinite scrolling. Like Facebook, it works so that as a user is scrolling down the page more and more content gets loaded. This means you don't have to load a bunch of content at once, but you have to keep track of where the user on the page.
Regardless of what way you load the videos, you have to get valid urls to your videos. It sounds like you got the URL generator, and to make sure the URL doesn't return a 404 I'd do something like this: Checking if a URL is broken in Javascript.
Good luck!


text:
Q: Airflow with KubernetesExecutor: how to get network access to worker pods from outside? I have to run airflow DAGs in KubernetesExecutor (with mostly PythonVirtualenvOperators). And I want to receive incoming connections in my operators.
How can it be done? I really need it to run SparkSession in .master("yarn") mode.


text:
Q: How AWS EMR react after reaching the 256 pending/running jobs limit is reached? According to
https://docs.aws.amazon.com/emr/latest/ManagementGuide/AddMoreThan256Steps.html
AWS EMR "Beginning with AMI 3.1.1 (Hadoop 2.x) and AMI 2.4.8 (Hadoop 1.x), you can submit an unlimited number of steps over the lifetime of a long-running cluster, but only 256 can be active or pending at any given time"
My questions are:

*

*If you already reached the 256 limit, where and how you'll find the rest of submitted jobs that were submitted?

*Is EMR keeping a queue of the submitted jobs, and when a job is done (succes/failed) it will pick another job from the "invisible client job queue"?

*If EMR has such a queue (as explained in 2), for how long it will keep these jobs?

*Can we access via EMR API, the submitted jobs that are not among the 256 jobs?
I look forward for your answers/
Regards,
Florin

A: I've discussed with the Amazon Support Center and they gave the following answers:
"1. This limit is imposed by the EMR Step API (this is on the AWS side), not by YARN or Spark themselves. This is what you see when you look at the cluster properties in the console and navigate to 'Steps' within the cluster details, or make a 'list-steps' call from the CLI. You'll know when you've hit this limit, because when you submit a new step through the step API (either through the console or 'add-steps' call from CLI), you'll get an error stating that there are already 256 steps in a running or pending state, and the step will not be accepted. Therefore, there will not be a record of that step's submission

*I'm not sure how to answer this one in exact terms, so I'll just explain how an EMR cluster is going to handle jobs. In a cluster running Hadoop 2.x, YARN (the cluster's resource manager) is responsible for tracking jobs. When a job is submitted to YARN (either via the AWS api as a step or directly to YARN,) YARN will keep track of the submitted jobs and process them as the cluster's scheduler and resources allow. The step API is just an abstraction layer that lets you leverage the AWS API to submit jobs to YARN without directly accessing the cluster, using the EMR service endpoint instead. When the request is received at the step API, that information is collected by a daemon on the cluster called the 'instance-controller', and passed to YARN as a job submission. Step submissions can be seen in the console in the cluster's details on the 'Steps' tab, and YARN jobs can be seen by accessing the cluster's shell and running 'yarn application -list -appStates ALL'. Jobs are processed by order of submission and/or priority, based on the configuration of the YARN scheduler being used.

*The cluster will track each job for the life of the cluster.

*Again, I want to clarify that the limit is specific to jobs submitted via the EMR Step API; jobs can still be submitted directly to YARN via its own API if you want, and you can access both the list of pending/active steps and YARN jobs separately.
YARN has a huge capacity for storing and managing information; the step API's limits have to do with the storage layers that keep persistent information about the cluster's configuration on the EMR back-end."
My resume, confirmed by the AWS support team:

*

*256 jobs limit is posed by the EMR jobs API and it is a HARD limit.

*As a client, when I'll reach the limit, I'll get an exception that this limit
is already reached and all the step submissions will be rejected.

*When this limit is reached, it is still possible to submit jobs via YARN client.
I hope these will help others that have these questions.
Regards,
 Florin


text:
Q: Making website elements align to a (small) grid So I have an idea for a site design where the background is a grid of small (say 10px) color-shifting squares.  Ideally, I'd like to have the elements on the page line up with this grid, however most of the guides for website grids revolve around the 960 grid system, which isn't small enough for my purposes.
Anyone have any suggestions for how to achieve this?  Also, if anyone has any ideas for how to do the color-shifting grid thing, I'd definitely appreciate that as well!

A: Here's how to create a constantly changing, multi-colored grid

You can fill an 8x8 grid with rectangles (one at a time) like this:
    var n=parseInt(Math.random()*64);
    var r=parseInt(n/8);
    var c=n-r*8;
    ctx.fillStyle=randomColor();
    ctx.fillRect(c*20,r*20,20,20);

You can generate a random color like this:
    function randomColor(){
        return("#"+Math.floor(Math.random()*16777215).toString(16));
    }

Add an animation loop and you're good to go!
Here is code and a Fiddle:  http://jsfiddle.net/m1erickson/n2ymp/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<script src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");

        window.requestAnimFrame = (function(callback) {
          return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
          function(callback) {
            window.setTimeout(callback, 1000 / 60);
          };
        })();

        var fps = 30;
        function animate() {
            setTimeout(function() {
                requestAnimFrame(animate);

                // Drawing code goes here
                var n=parseInt(Math.random()*64);
                var r=parseInt(n/8);
                var c=n-r*8;
                ctx.fillStyle=randomColor();
                ctx.fillRect(c*20,r*20,20,20);

            }, 1000 / fps);
        }

    // create a random color object {red,green,blue}
    function randomColor(){
        return("#"+Math.floor(Math.random()*16777215).toString(16));
    }

    animate();

    }); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=600 height=400></canvas>
</body>
</html>


text:
Q: how can i stop these 2 wordpress functions from interfering with each other? i have a specific word press theme and a plugin for counting downloads.... however when i activate the plugin it makes all my "featured thumbnails" disappear for all the post types in my wordpress... in other words there is no "featured image box" when adding any kind of post AFTER i activate the plugin......
after looking through my theme code and the plugin code i believe i have found the problem but i am not sure hoe to fix it.....
the theme i am using has the following function
// Add Thumbnail support
if (function_exists('add_theme_support')) { // Adding thumbnail support to all post types.

add_theme_support( 'post-thumbnails', array( 'store', 'dlm_download', 'service', 'album', 'mixtape', 'merch', 'photos', 'video' , 'download' , 'homebanner', 'post' ) );
add_image_size('storeimage', 200, 200, true); //Store homepage Thumbnails
add_image_size('beat_page', 160, 160, true); // Single beat page
add_image_size('photo', 200, 200, true); // Thumbnail image
add_image_size('photowidget', 165, 165, true); // Thumbnail image
add_image_size('videowidget', 270, 151, true); // Thumbnail image
add_image_size('photobig', 570, 570, true); // Image for single page
add_image_size('videoimage', 273, 200, true); // Video Gallery Homepage Thumbnails
add_image_size('homebannerimage', 920, 350, true); //Homepage Banner Image
add_image_size('featuredimage', 580, 250, true); //Post Featured image Image 580x250
}

and then the plugin has the following function
public function compatibility() {
    // Post thumbnail support
    if ( ! current_theme_supports( 'post-thumbnails' ) ) {
        add_theme_support( 'post-thumbnails' );
        remove_post_type_support( 'post', 'thumbnail' );
        remove_post_type_support( 'page', 'thumbnail' );
    } else {

        // Get current supported
        $current_support = get_theme_support( 'post-thumbnails' );

        // This can be a bool or array. If array we merge our post type in, if bool ignore because it's like a global theme setting.
        if ( is_array( $current_support ) ) {
            add_theme_support( 'post-thumbnails', array_merge( $current_support, array( 'dlm_download' ) ) );
        }

        add_post_type_support( 'download', 'thumbnail' );
    }
}

i noticed they both use "add_theme_support" , "post-thumbnails" and a few other similar things...... not sure why the two functions are interfering with each other or how i could fix it...... i tried to add the "dlm_download" post type (this is the post type for the the plugin) to the theme functions array of post types and it didnt make any difference.....
i tried to totally remove the thumbnail function from the plugin and kept getting a "failed to call header : head already called" error....
any help would be much appreciated!

A: Try changing this line in your theme
add_theme_support( 'post-thumbnails', array( 'store', 'dlm_download', 'service', 'album', 'mixtape', 'merch', 'photos', 'video' , 'download' , 'homebanner', 'post' ) );

to
add_theme_support( 'post-thumbnails' );


text:
Q: When is a property needed instead of just exposing the variable in Python? This is the example of using properties given in the Python documentation:
Class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

As far as I can tell, this behaves just like a regular property-less instance variable:
Class D(object):
    def __init__(self):
        self.x = None

Of course this doesn't have the ability to add additional logic to the getter or setter, but, since there is no difference in how other code interacts with C and D, you could always add a property later if you needed it without breaking any other code.
I know that this creates a problem if you use mutable types that are declared at the class level, i.e.:
class E(object):
    x = [1,2,3]

Apart from that case, though, is it bad practice to leave out the properties until it they are needed or is it acceptable?
Thanks!

A: You use property to evaluate the value an object attribute that is a funciton of other attributes. Consider the following class:
class shape:
    def __init__(self,l,w):
        self.length = l
        self.width  = w
    @property
    def area(self):
        return self.length*self.width

If we change the value of either length or width, the value of area will be updated immediately when we ask for it.
[In:]  s = shape(2,3)

[In:]  print s.length, s.width, s.area
[Out:] 2 3 6

[In:]  s.length = 5

[In:]  print s.length, s.width, s.area
[Out:] 5 3 15

To help clarify how this works, consider the following case: if we try to define area in __init__():
class shape2:
    def __init__(self,l,w):
        self.length = l
        self.width  = w
        self.area = self.length * self.width

area will only be evaluated when the class is instantiated. Changing the values of length or width won't modify the value of area:
[In:]  s = shape2(2,3)

[In:]  print s.length, s.width, s.area
[Out:] 2 3 6

[In:]  s.length = 5

[In:]  print s.length, s.width, s.area
[Out:] 5 3 6

A: What I think personally is that Python exposes variables as part of its philosophy, so you do not need to make properties out of everything. You can use properties to add logic to what was once a simple variable, or in order to keep the (client) code clean.
Classes like C in are useless outside tutorials/documentation.
(This is my own opinion. I don't know what is "considered" bad practice, as I am not an experienced developer or something)


text:
Q: Display Sales information in TreeTableView What I want to achieve is more or less having Sale object which when expanded to display SaleTransaction objects under that Sale object. Similar to want is displayed in this image from Code Project

where i can also do other CRUD functionality apart from just read(i.e Create, Update and delete).
I tried implementing it using TreeTableView like so:
 List<CreditSale> lstData = new ArrayList<CreditSale>(creditsaleservice.findAllCreditSales());

    TreeItem root = new TreeItem<>();
    for (CreditSaleTransaction cst : lstData.get(0).getCreditSaleTransaction()) {
        root.getChildren().addAll(new TreeItem<>(cst));
    }

    TreeTableColumn<CreditSaleTransaction, Product> productColumn = new TreeTableColumn<>("Product Name");

    productColumn.setPrefWidth(150);
    productColumn.setEditable(true);

    productColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<CreditSaleTransaction, Product> p)
            -> new ReadOnlyObjectWrapper<>(p.getValue().getValue().getProduct()));

    TreeTableColumn<CreditSaleTransaction, Float>  quantityColumn = new TreeTableColumn<>("Quantity");
    quantityColumn.setPrefWidth(150);
    quantityColumn.setEditable(true);
    quantityColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<CreditSaleTransaction,Float> p)
            -> new ReadOnlyObjectWrapper<>(p.getValue().getValue().getAmount()));

    TreeTableColumn<CreditSaleTransaction, Float>  unitPColumn = new TreeTableColumn<>("Unit Price");
    unitPColumn.setPrefWidth(150);
    unitPColumn.setEditable(true);
    unitPColumn.setCellValueFactory((TreeTableColumn.CellDataFeatures<CreditSaleTransaction,Float> p)
            -> new ReadOnlyObjectWrapper<>(p.getValue().getValue().getUnitPrice()));

    TreeTableView<CreditSaleTransaction> treeTableView = new TreeTableView<>();
    treeTableView.setRoot(root);

    treeTableView.getColumns().addAll(productColumn,quantityColumn,unitPColumn);
    treeviewanchorpane.getChildren().add(treeTableView);

but nothing is displayed.

A: It's possible to achieve a similar output with a TreeTableView provided you don't mind losing these inner headers:

Jewelsea has a good example of how to approach this here:

*

*creating nested TreeItem in javafx

**Suggested approach for a custom implementation**
If the headers are important you can create a custom control to get the desired layout. My suggestion would be multiple TitledPane's within a container such as a VBox, with the outer item as the title and the inner items as the content within a TableView. TitledPane expects a String as the title, but with a combination of setGraphic  and setContentDisplay , this can be changed to a Node allowing you to maintain a consistent layout
This approach would allow for multiple items (both inner and outer) to be visible at the same time.
In the event you only wish to be able to see the inner one at a time, an Accordian would be a suitable alternative to a VBox as it only allows one TitledPane to be expanded at any given time
Both TitledPane and Accordian are covered within this Oracle tutorial:

*

*Titled Pane and Accordion
(I've included an example on how this approach could be implemented and an image displaying the output at the end of this answer)

**Monitoring changes**
JavaFX offers an ObservableList, which notifies listeners of any changes. Effective use of this would allow for the user interface to automatically reflect any changes.
For example, a ListChangeListener  to detect when elements have been added/removed, which is covered here.
Note: If a child element within the ObservableList is modified (such as a price within a nested sales item), there may not be an update event. In this situation an extractor should be added to the list which specifies the additional values should be observed, firing the event updates if any of these values change
There are also a range of properties / bindings available, which are covered in the following pieces of documentation:

*

*Bindings

*Using JavaFX Properties and Binding
(The example contains examples of how to use the above)

Suggestions for implementing the CRUD functionality on `TableView`'s:

*

*Creating a Button bar: You could place this under each TableView  or the nestedView, using selected cells to determine when to enable the buttons and which objects to modify

*Place an EventHandler on the TableView: See setOnEditCommit()

*Adding custom cells to the TableView: There are several examples available on how to create custom TableCell's that delete the row when clicked. For example: Delete Rows using row buttons in Javafx TableView

*Using ContextMenu's

Example:
I've added code comments where possible, but if there are any questions or suggested improvements please leave a comment
NestedTableView:
public class NestedTableView extends VBox {
    private ObservableList<Node> titledPanes = FXCollections.observableArrayList();
    private Region parent;

    public NestedTableView(Region parent, ObservableList<ProductBundle> bundlesToDisplay){
        this.parent = parent;
        VBox nestedView = new VBox();
        Bindings.bindContentBidirectional(nestedView.getChildren(), titledPanes);
        titledPanes.addAll(bundlesToDisplay.stream()
                .map(TablePane::new).collect(Collectors.toList()));
        getChildren().setAll(createHeader(), nestedView);
        getStylesheets().add("CSS/nestedTableViewStyles.css");
    }

    private HBox createHeader(){
        //Set up widths to align with the content headers beneath the header
        Label symbol = new Label("#");
        symbol.setPrefWidth(25); //Sum of the values used by the "arrow" region

        Label productId = new Label("Product Id");
        productId.prefWidthProperty().bind(parent.widthProperty().multiply(0.15));

        Label productName = new Label("Product Name");
        productName.prefWidthProperty().bind(parent.widthProperty().multiply(0.35)); //Give name extra space

        Label amount = new Label("Amount");
        amount.prefWidthProperty().bind(parent.widthProperty().multiply(0.15));

        Label date = new Label("Order Date");
        date.prefWidthProperty().bind(parent.widthProperty().multiply(0.15));

        Label quantityAvailable = new Label("#Available");
        quantityAvailable.prefWidthProperty().bind(parent.widthProperty().multiply(0.15));

        HBox header = new HBox(symbol, productId, productName, amount, date, quantityAvailable);
        header.getStyleClass().add("header");
        return header;
    }

    private class TablePane extends TitledPane {
        private ProductBundle productBundle;

        private HBox header;
        private TableView contentTableView;
        private MenuItem addToBundle, deleteBundle;

        public TablePane(ProductBundle productBundle){
            this.productBundle = productBundle;
            setupMenuItems();
            setupContentHeader();
            setGraphic(header);
            setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            if(!productBundle.getBundleItems().isEmpty()){
                createTableView();
                setContent(contentTableView);
            }

            //Only display the expandable "arrow" if there is content to display
            collapsibleProperty().bind(contentProperty().isNotNull());
            //If the "arrow" isn't displayed, pad the area to mimic the arrow being present to align headers
            header.paddingProperty().bind(
                    Bindings.when(collapsibleProperty()).then(Insets.EMPTY).otherwise(new Insets(0,0,0,15)));
            /*  For testing purposes. With more rows this will clutter the UI
                ToDo: add logic to determine how many panes to expand before the viewport has been filled
             */
            setExpanded(true);
        }

        private void setupMenuItems(){
            addToBundle = new MenuItem("Add to bundle");
            addToBundle.setOnAction(event -> {
                //ToDo: Add CRUD create logic here
                System.out.println("Add to bundle: " + productBundle.idProperty());
            });
            deleteBundle = new MenuItem("Delete bundle");
            deleteBundle.setOnAction(event -> {
                //ToDo: Add CRUD delete logic here
                System.out.println("Delete bundle: " + productBundle.idProperty());
            });
        }

        private void setupContentHeader(){
            header = new HBox();
            //Bind the content header to the root so that it aligned with the initial header
            header.prefWidthProperty().bind(parent.widthProperty());
            header.maxWidthProperty().bind(parent.widthProperty());

            /* Set up each TextField with widths to align with the TableView
               Each TextField is editable with the exception of id as it would be the primary key
               and amount as it's value is calculated from the sub items */
            TextField id = new TextField();
            id.setEditable(false);
            modifyTextFieldContextMenu(id);
            id.textProperty().bind(productBundle.idProperty());
            id.prefWidthProperty().bind(header.widthProperty().multiply(0.15));

            TextField name = new TextField();
            modifyTextFieldForCRUDFunctionality(name);
            name.textProperty().bindBidirectional(productBundle.nameProperty());
            name.prefWidthProperty().bind(header.widthProperty().multiply(0.35)); //Give name extra space

            TextField amount = new TextField();
            amount.setEditable(false);
            Bindings.bindBidirectional(amount.textProperty(), productBundle.amountProperty(),
                    new NumberStringConverter(NumberFormat.getCurrencyInstance(Locale.US)));
            amount.prefWidthProperty().bind(header.widthProperty().multiply(0.15));

            TextField date = new TextField();
            modifyTextFieldForCRUDFunctionality(date);
            date.textProperty().bind(productBundle.orderDateProperty());
            date.prefWidthProperty().bind(header.widthProperty().multiply(0.15));

            TextField quantityRemaining = new TextField();
            modifyTextFieldForCRUDFunctionality(quantityRemaining);
            //Only display a quantity if it's a valid value (to match example screen shot)
            quantityRemaining.textProperty().bind(
                    Bindings.when(productBundle.quantityAvailableProperty().greaterThan(0))
                            .then(productBundle.quantityAvailableProperty().asString()).otherwise("N/A"));
            quantityRemaining.prefWidthProperty().bind(header.widthProperty().multiply(0.15));

            header.getChildren().setAll(id, name, amount, date, quantityRemaining);
            header.getStyleClass().add("content-header");
        }

        private void modifyTextFieldContextMenu(TextField textField){
            TextFieldSkin skin = new TextFieldSkin(textField){
                @Override
                public void populateContextMenu(ContextMenu contextMenu) {
                    super.populateContextMenu(contextMenu);
                    contextMenu.getItems().add(0, addToBundle);
                    contextMenu.getItems().add(1, deleteBundle);
                    contextMenu.getItems().add(2, new SeparatorMenuItem());
                }
            };
            textField.setSkin(skin);
        }

        private void modifyTextFieldForCRUDFunctionality(TextField textField){
            textField.setEditable(true);
            textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
                private String previousText;
                @Override
                public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
                    String currentText = textField.getText();
                    if(newValue){
                        previousText = currentText;
                    }
                    //ToDo: Add CRUD update logic here
                    else if(!previousText.equals(currentText)){
                        System.out.println("Value has been changed from: " + previousText + " to: " + currentText);
                    }
                }
            });
        }

        private void createTableView(){
            TableColumn<BundleItem, String> idColumn = new TableColumn<>("#ID");
            idColumn.setCellValueFactory(param -> param.getValue().getItem().itemIdProperty());

            TableColumn<BundleItem, String> nameColumn = new TableColumn<>("Item");
            nameColumn.setCellValueFactory(param -> param.getValue().getItem().itemNameProperty());

            TableColumn<BundleItem, String> amountColumn = new TableColumn<>("Amount");
            amountColumn.setCellValueFactory(param -> param.getValue().getItem().amountProperty().asString("$%.2f"));

            TableColumn<BundleItem, Number> quantityColumn = new TableColumn<>("Qty");
            quantityColumn.setCellValueFactory(param -> param.getValue().quantityProperty());

            TableView<BundleItem> tableView = new TableView<>(productBundle.getBundleItems());
            tableView.setPadding(new Insets(10));
            //Equal column widths
            tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
            tableView.getColumns().setAll(idColumn, nameColumn, amountColumn, quantityColumn);
            //Only show visible shows
            tableView.setFixedCellSize(30);
            tableView.prefHeightProperty().bind(Bindings.size(productBundle.getBundleItems())
                    .multiply(tableView.getFixedCellSize()).add(tableView.getFixedCellSize()*1.5));
            contentTableView = tableView;
        }
    }
}

Sales related objects:
public class ProductBundle {
    private ObservableList<BundleItem> bundleItems = FXCollections.observableArrayList();
    private SimpleStringProperty productId, productName, orderDate;
    private SimpleDoubleProperty amount = new SimpleDoubleProperty();
    private SimpleIntegerProperty quantityAvailable;

    private ProductBundle(String productId, String productName, String orderDate, int quantityAvailable){
        this.productId = new SimpleStringProperty(productId);
        this.productName = new SimpleStringProperty(productName);
        this.orderDate = new SimpleStringProperty(orderDate);
        this.quantityAvailable = new SimpleIntegerProperty(quantityAvailable);
    }

    public ProductBundle(String productId, String productName, String orderDate,
                         int quantityAvailable, ObservableList<BundleItem> bundleItems){
        this(productId, productName, orderDate, quantityAvailable);
        //Setup an extractor to "Observe" changes on the amount/quantity of any items in the bundle
        this.bundleItems = FXCollections.observableArrayList(new Callback<BundleItem, Observable[]>() {
            @Override
            public Observable[] call(BundleItem param) {
                return new Observable[]{param.amountProperty(), param.quantityProperty()};
            }
        });
        this.bundleItems.addAll(bundleItems);
        //Calculate the total worth of this bundle
        amount.bind(Bindings.createDoubleBinding(()->
                bundleItems.stream().collect(Collectors.summingDouble(BundleItem::getAmount)), this.bundleItems)
                .multiply(quantityAvailable));
    }

    public ProductBundle(String productId, String productName, String orderDate,
                         int quantityAvailable, double amount){
        this(productId, productName, orderDate, quantityAvailable);
        this.amount.set(amount);
    }

    public ObservableList<BundleItem> getBundleItems(){
        return bundleItems;
    }

    public SimpleStringProperty idProperty(){
        return productId;
    }

    public SimpleStringProperty nameProperty(){
        return productName;
    }

    public SimpleIntegerProperty quantityAvailableProperty(){
        return quantityAvailable;
    }

    public SimpleStringProperty orderDateProperty(){
        return orderDate;
    }

    public SimpleDoubleProperty amountProperty(){
        return amount;
    }

    public double getAmount(){
        return amount.get();
    }
}

public class BundleItem {
    private Item item;
    private SimpleIntegerProperty quantity;
    private SimpleDoubleProperty amount = new SimpleDoubleProperty();

    public BundleItem(Item item, int quantity){
        this.item = item;
        this.quantity = new SimpleIntegerProperty(quantity);
        amount.bind(item.amountProperty().multiply(quantity));
    }

    public Item getItem(){
        return item;
    }

    public SimpleIntegerProperty quantityProperty(){
        return quantity;
    }

    public SimpleDoubleProperty amountProperty(){
        return amount;
    }

    public double getAmount(){
        return amount.get();
    }
}

public class Item {
    private SimpleStringProperty itemId, itemName;
    private SimpleDoubleProperty amount;

    public Item(String itemId, String itemName, double amount){
        this.itemId = new SimpleStringProperty(itemId);
        this.itemName = new SimpleStringProperty(itemName);
        this.amount = new SimpleDoubleProperty(amount);
    }

    public SimpleStringProperty itemIdProperty(){
        return itemId;
    }

    public SimpleStringProperty itemNameProperty(){
        return itemName;
    }

    public SimpleDoubleProperty amountProperty(){
        return amount;
    }

    public double getAmount(){
        return amount.get();
    }

    public void setAmount(double newValue){
        amount.set(newValue);
    }
}

nestedTableViewStyles.css:
.header {
    -fx-background-color: darkorange;
    -fx-pref-height: 30;
    -fx-padding: 5 0 0 0;
}

.header > .label {
    -fx-text-fill: white;
}

.header > .label, .content-header > .text-field {
    -fx-alignment: center;
    -fx-text-alignment: center;
}

.content-header > .text-field, .content-header > .text-field:focused {
    /* Make the TextField's display similar to a Label */
    -fx-background-color: transparent;
}

.content-header, .titled-pane > .title, .table-view {
    -fx-background-color: white;
}

.titled-pane > .title {
    -fx-border-color: lightgray;
    -fx-border-width: 0 0 1 0;
}

.table-view {
     -fx-table-cell-border-color: transparent;
}

.table-view .column-header-background {
    -fx-border-radius: 5 5 0 0;
    -fx-background-radius: 5 5 0 0;
}

.table-view .column-header-background, .table-row-cell {
    -fx-background-color: lightgray;
    -fx-border-color: gray;
    -fx-border-width: 0 0 1 0;
}

.table-view .column-header-background .label {
    -fx-background-color: lightgray;
    -fx-text-fill: black;
    -fx-font-weight: bold;
}

.table-view .column-header {
    -fx-background-color: transparent;
}

.table-column {
    -fx-alignment: center;
}

Usage:
public class NestedTableViewExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        ObservableList<ProductBundle> bundles =
                FXCollections.observableArrayList(
                        new ProductBundle("1001456", "Spring Season Gift", "02/14/2015", 1,
                                FXCollections.observableArrayList(
                                        new BundleItem(new Item("17890", "PS 3", 150.00), 1),
                                        new BundleItem(new Item("17891", "Heart shape ring", 100.00), 1)
                                )),
                        new ProductBundle("1001457", "Christmas Season Gift", "04/14/2015", 1,
                                FXCollections.observableArrayList(
                                        new BundleItem(new Item("17900", "Chocolate Giftbox", 150.00), 1),
                                        new BundleItem(new Item("17901", "Xbox 360", 199.00), 1)
                                )),
                        new ProductBundle("1001458", "Birthday Gift", "", 1, 200)
                );

        VBox root = new VBox();
        root.getChildren().setAll(new NestedTableView(root, bundles));
        Scene scene = new Scene(root, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Nested TableView example");
        primaryStage.show();
    }
}

**Output:**


text:
Q: FlatList horizontal onViewableItemsChanged not firing if I use getItemLayout I have horizontal FlatList and try to get visible item with onViewableItemsChanged
event and if I use getItemLayout props. event not firing on Android if its horizontal.iOS working well.
Here is  demo .if you remove horizontal or getItemLayout props. working fine. but I also need getItemLayout
https://snack.expo.io/@nazrdogan/flatlist-getitemlayout

A: this looks like it's happening because you're setting waitForInteraction: true. When the list is vertical, scrolling registers an interaction from the vertical scroll, calling the callback. In order to trigger the interaction when the list is vertical, you have to scroll horizontally on the list.
To fix you can set waitForInteraction to false

A: The solution to this is you have to use any parameter for determining the item is on visible on screen or not.
If you are using the viewabilityConfig and getItemLayout then you might get this problem, you can remove the viewabililtyConfig then it will work.


text:
Q: How can I determine whether a table row immediately follows a page break Given a Word table which spans several pages, how can my code determine that a table row is the first following an automatic page break?  Note that table rows are of different heights thus a solution of the form "every 13th row is the first row on a new page" won't work.
The point of this would be to add extra text in the first cell at the top of every new page.

A: Use wdActiveEndPageNumber for that table row.  Be sure that row is as big as it's going to get before checking the page number.
n = word.ActiveDocument.Tables(a).rows(b).Range.Information(wdActiveEndPageNumber)

A: If the table is sufficiently large that it splits over several pages then you compare the page number of consecutive rows until the page number changes. There are no pagebreaks to speak of.


text:
Q: Using fp_trap to find cause of floating point exceptions in PETSc? I'm not sure if this question belongs here or not. But I am having a problem with my code with PETSc saying that there is a floating point error. It is similar to the problem discussed in the links below:
http://lists.mcs.anl.gov/pipermail/petsc-users/2012-November/015858.html
https://www.mail-archive.com/petsc-users@mcs.anl.gov/msg22930.html
Some people in those threads just said to ust "fp_trap". But where am I supposed to enter that? I tried to go into gdb and valgrind and then enter "fp_trap", but it's not working

A: Here is a piece of code that needs some debugging... This program prints norm is -nan.
static char help[] = "Floating point exception.\n\n";

#include <petscvec.h>

#undef __FUNCT__
#define __FUNCT__ "ShouldTriggerFloatingPointException"
extern PetscErrorCode ShouldTriggerFloatingPointException(){

    PetscErrorCode     ierr;

    PetscFunctionBegin;

    PetscScalar a=0.0;
    PetscScalar b=0.0;
    PetscScalar c=a/b;
    Vec x;

    ierr=VecCreate(PETSC_COMM_WORLD,&x);CHKERRQ(ierr);
    ierr= VecSetSizes(x,PETSC_DECIDE,1000);CHKERRQ(ierr);
    ierr=  VecSetFromOptions(x);CHKERRQ(ierr);

    ierr=VecScale(x,c);CHKERRQ(ierr);
    PetscScalar norm;
    ierr=VecNorm(x,NORM_2,&norm);CHKERRQ(ierr);

    PetscPrintf(PETSC_COMM_WORLD,"norm is %g\n",norm);

    PetscFunctionReturn(0);
}

#undef __FUNCT__
#define __FUNCT__ "main"
int main(int argc,char **argv)
{

    PetscErrorCode ierr;
    PetscInitialize(&argc,&argv,(char*)0,help);
    ierr=ShouldTriggerFloatingPointException();CHKERRQ(ierr);
    ierr = PetscFinalize();
    return 0;
}

The following makefile is used to build the executable main
https://scicomp.stackexchange.com/questions/905/compiling-and-running-a-hello-world-program-in-petsc
include ${PETSC_DIR}/conf/variables
include ${PETSC_DIR}/conf/rules

main: main.o  chkopts
    -${CLINKER} -o main main.o  ${PETSC_LIB}
    ${RM} main.o

The option -fp_trap of Petsc helps detecting the origin of this issue :
mpirun -np 2 main -fp_trap

will print a warning with the name of the function where the problem was detected :
[0]PETSC ERROR: [0] ShouldTriggerFloatingPointException line 14 main.c
[0]PETSC ERROR: ------- Error Message----------
[0]PETSC ERROR: Floating point exception!
[0]PETSC ERROR: trapped floating point error!

Hence -fp_trap is an option of the petsc program, nothing to do with the debugger.
Using a debugger is required to find the exact line where the issue occured. For instance, with gdb (and petsc configure --with-debugging) :
gdb --args  main -fp_trap
(gdb) run

args states that Arguments after executable-file are passed to the executable. It produces :
Program received signal SIGFPE, Arithmetic exception.
0x00000000004011a2 in ShouldTriggerFloatingPointException () at main.c:18
18  PetscScalar c=a/b;

The issue is now detected !
Further information about debugging and mpi : How do I debug an MPI program?


text:
Q: Create hour of day from DF index I have a pandas DF with datetime index.
Created_Ts           value
2001-01-01 06:00:00  199
2001-01-01 06:15:00  299
2001-01-01 07:30:00  399
2001-01-01 07:45:00  400

I want to create the hour of the day from the datetime index.
Current Approach:
df = df.reset_index()
df["hour"] = df["Created_Ts"].dt.hour

It works, but is there a pandas way to create the hour column directly and without resetting the index

A: Use index and remove .dt:
df["hour"] = df.index.hour


text:
Q: Why do some tricks in homological algebra work over the category of C*-algebras? The category of $C^*$-algebras is not abelian (a "proof" that it is pre-abelian can be found here, but it does not seem correct; I can't find any authoritative sources). However, it's possible to do K-theory over the category of $C^*$-algebras, and one can often directly use tricks and techniques from homological algebra, especially when working with exact sequences. Sometimes people even use directly definitions and terms in homological algebra that are not really well-defined if the underlying category is not abelian.
The question is, why does this "just work"? Is it that the category of $C^*$-algebras have some good properties that allow one to use techniques from homological algebra, or is it that a lot of homological algebra don't really require the category one is working in to be abelian (e.g., pre-abelian is actually enough)?
I apologize if this question is not research-level enough.


text:
Q: If $f(x)$ is differentiable, can $1/f$ be locally integrable at a zero of $f$? Let $(a,b) \subset \mathbb{R}$ be some finite-length interval, let $f : (a,b)\rightarrow \mathbb{R}$ be some (everywhere-)differentiable function.
Suppose $f$ has a zero in its domain.
My question is: In the above case, it possible for $\int_{(a,b)} \frac{dt}{|f(t)|}$ to be finite?
For example, this integral is $\infty$ for e.g. $f(t) = |t|^{\alpha-1}t$ for $\alpha\in\mathbb{R}\,,\,\alpha\geq 1$, with $(a,b)$ some open interval containing $0$. [If I'm not mistaken this is differentiable with derivative $0$ at $t=0$.]
However, I'm not sure how to approach the more general case, or how to look for a counter-example.

A: Let $f(c)=0$ Then there exists $\delta >0$ such that $|f(t)|=|f(t)-f(c)| <(1+|f'(c)| |t-c|$ for $|t-c| <\delta$. Now $\int_a^{b}\frac 1 {|f(t)|} dt\geq a\int_{c-\delta}^{c+\delta}\frac 1 {|t-c|} dt$ where $a=(1+|f'(c)|)^{-1}$. It follows that $\int_a^{b}\frac 1 {|f(t)|} dt=\infty$. This uses only the definition of $f'(c)$ and it is not necessary to assume that $f$ is continuously differentiable.


text:
Q: configuring nginx to serve static json files Switching to nginx for a site, one issue I'm having is serving up static json files.
I added to the mime types:
application/zip                         zip;
...
application/json                        json;
...

and restarted but it tried serving it up as a download (ie http://domain.com/json-tmp/locations.json). What else would I need to configure?
thx

A: I had to add
    application/json                      json;

in /etc/nginx/mime.types and restart nginx to make it work.

A: I know this post is quite old but adding application/json mime type to nginx configuration file plus restarting the server should work.
When you request the json file try to debug the response header and check if the Content-Type header was successfully changed to application/json.

A: Try serving it as javascript ...
application/javascript                json;

Or as plain text ...
text/plain                            txt json;

I'll try the javascript first.


text:
Q: Flash: Movieclips, Graphics, Buttons Why does Flash still offer to declare library items as either MovieClip, Graphic or Button? Is this just for backwards compatibility or is there any reason not to use MovieClip for everything? (Well, Button does have some additional functionality, but what about Graphic? does a Graphic have any advantage over a MovieClip?)

A: This tree might give you a good idea of what you're asking:

Basically, the further up the tree you are, the more lightweight the object is going to be. As you can see, SimpleButton is going to be lighter and more suitable for situations where you only need the functionality of a click-able button with different states, rather than using MovieClip that can act as a container, have a timeline, etc etc.
It's good practice to try and aim for the use of the most primitive types possible. For example, if you're not going to have timeline animation for a graphic, use Sprite. If ontop of that you're not going to be adding anything additional into the graphic, use Shape, and so on.
Something major to note is that MovieClip is the heaviest DisplayObject you can use.


text:
Q: Infinite network of resistors: an alternative solution (let's discuss about it!) I was trying to solve analytically the infinite network of resistor problem, but I did not make it. So I looked up for the solution:
Infinite network of resistors
But I did not like it. It might be that I am misunderstanding something but I would like to hear your opinion about it.
Here there is a picture of how I think about it.
sketch
I think to have simply stretched the wires. For this reason I don't like when in the previous solution they simply add two resistances in series, I don't think they are simply in series.
I tried to compute the value of this resistance by recursion (until the solution seem to converge, Python):
import sys
sys.setrecursionlimit(1500)

def deep(R_base, number, limit):

    if number<limit:
        number = number+1
        R_final = 2.0*R_base + (1.0/R_base + 1.0/deep(R_base, number,limit))**(-1.0)
    else:
        R_final = 2.0*R_base + R_base/2.0

    return(R_final)

R_basic = 1.0

n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 500, 750, 1000]

for nn in n:

    R_eq = (1.0/R_basic + 2.0/deep(R_basic, 1, nn))**(-1)

    print nn, R_eq, R_basic*(1.0+3.0**(0.5))

and I got this result:
1 0.555555555556 2.73205080757
2 0.575757575758 2.73205080757
3 0.577235772358 2.73205080757
4 0.57734204793 2.73205080757
5 0.577349678926 2.73205080757
6 0.577350226811 2.73205080757
7 0.577350266147 2.73205080757
8 0.577350268971 2.73205080757
9 0.577350269174 2.73205080757
10 0.577350269188 2.73205080757
100 0.57735026919 2.73205080757
500 0.57735026919 2.73205080757
750 0.57735026919 2.73205080757
1000 0.57735026919 2.73205080757

The second column value is < than the expected value (third column) and the second column value seem to have converged.
I think this is the right value. What do you think about it?

A: Your approach is OK, but you solve a different problem. In the first solution you calculate the equivalent resistance of an infinite ladder, but in fact is semi-infinite. It starts at a given point, and you keep adding resistors only on the right side.
Your sketch is different. You start from the middle of the ladder, and keep adding resistors on both sides. To get how your problem is related to the previous one, consider the resistor $R$ between the brown points, and it is in parallel with two semi-infinite ladders as in the previous problem. If $R_E$ for the semi-infinite ladder is 2.732, then the equivalent resistor for your problem is $$\frac{1}{\frac{1}{1}+\frac{1}{2.732}+\frac{1}{2.732}}=0.5773$$


text:
Q: Refresh the GUI windows I have a Client(C++) to Server (Python) Project.
The client sent a Message to the server, and each Message contains three attributes.
The Gui should show all the attributes over the screen.
When the client sent the first message, everything works.
But when he sent the next message I need to close the window, and when I do that it opens a new window and shows the following message, if I don't do that he doesn't show the new messages that received.
I suspect that app.exec_() stop the program from getting a new message like in this case, but I'm not sure.
my question is :

*

*Is this really the case? And if so, where should I put the Thread?

*I never used QThread before, and I saw that we are doing Override for Run()
and in the Run() method we put in all the logic, what logic I should put into my particular problem.
you can find the full project here
Relevant code:
def recive(self):

        global income
        global table2

        msg = Payload(0, 0, 0)

        while (True):

            print('waiting for a connection..')
            conn, addr = self.My_socket.accept()
            print("connection has been established | " + repr(addr))
            logger.info("connection has been established | " + repr(addr))

            while conn:
                myThread = MyThread()

                buff = conn.recv(sizeof(msg))

                print("recv %d bytes" % sizeof(msg))
                payload_in = Payload.from_buffer_copy(buff)

                print(f"Received id={payload_in.id}, counter={payload_in.counter}, opcode={payload_in.opcode}")

                payload_out = payload_in

                self.opcode = payload_in.opcode

                if self.opcode == 1:
                    self.export()
                elif self.opcode == 2:
                    payload_out.counter += 1
                else:
                    logger.info("Unexpected opcode %d" % self.opcode)

                nsent = conn.send(payload_out)
                print("send %d bytes" % nsent)
                print("send id=%d, counter=%d, opcode=%d" % (payload_out.id,
                                                             payload_out.counter,
                                                             payload_out.opcode))
                self.setNewTable(payload_in, payload_out)

        print("Closing connection to client")
        print("----------------------------")

        sys.exit()

    def setNewTable(self,payload_in, payload_out):
            self.insertValues(table1, payload_in)
            self.insertValues(table2, payload_out)
            ex.show()
            app.exec_()

    def insertValues(self,table, payload):
            table.setItem(0, 1, QTableWidgetItem(str(payload.id)))
            table.setItem(1, 1, QTableWidgetItem(str(payload.counter)))
            table.setItem(2, 1, QTableWidgetItem(str(payload.opcode)))

A: I know couple of things about QThread ui think you need to use python signal and slot to update  ui. refer following code
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import datetime
import sys
import struct
import threading
import os
import datetime
import time
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
class MySignal(QObject):
        signelforWritemsg=Signal(str)
class EchoThread(QThread):
    #def __init__(self,Inf_found1,inf_cleaned1,Auto_clean,timer,movie,Scan_btn,cancel_btn,status_text):
    def __init__(self,parent = None):
        QThread.__init__(self,parent)
        self.exiting = False
        self.signal = MySignal()

    def run(self):
        while True:
            scantimenow= datetime.datetime.now()
            scantime=scantimenow.strftime('%Y-%m-%d %H:%M:%S')
            print(scantime)
            self.signal.signelforWritemsg.emit(scantime)
            time.sleep(5)
class Ui_Clientserver(object):
    def setupUi(self, Clientserver):
        Clientserver.setObjectName(_fromUtf8("Clientserver"))
        Clientserver.resize(400, 300)
        self.label = QtGui.QLabel(Clientserver)
        self.label.setGeometry(QtCore.QRect(150, 70, 200, 200))
        self.label.setObjectName(_fromUtf8("label"))
        self.retranslateUi(Clientserver)

        self.thread = EchoThread()
        self.thread.start()
        self.thread.signal.signelforWritemsg.connect(self.signelforWritemsg)

    def signelforWritemsg(self,data):
        self.label.setText(_translate("Clientserver",str(data), None))
    def retranslateUi(self, Clientserver):
        Clientserver.setWindowTitle(_translate("Clientserver", "Clientserver", None))

        self.label.setText(_translate("Clientserver", "inProgess", None))
if __name__ == "__main__":
    import sys
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
    app = QtGui.QApplication(sys.argv)
    Clientserver = QtGui.QWidget()
    ui = Ui_Clientserver()
    ui.setupUi(Clientserver)
    Clientserver.show()
    sys.exit(app.exec_())


text:
Q: Django Form inheritance problem Why can't I do this?
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):

    def __init__(self,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.tester = 'asdf'

    username = forms.CharField(label='Username',max_length=100,initial=self.tester)

More specifically, why cant the forms.CharField grab the variable tester that I set during construction?
I feel like I am missing something about the way Python handles this sort of thing...
edit :
What I am actually trying to do is this:
class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.tester = request.session['some_var']

    username = forms.CharField(label='Username',max_length=100,initial=self.tester)

In other words, I need to grab a session variable and then set it to an initial value...
Is there any way to handle this through the __init__ or otherwise?

A: What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created.  self.tester doesn't exist until you call __init__ at instance creation time.

A: You can just do it this way
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
    username = forms.CharField(label='Username',max_length=100,initial=self.tester)
    tester = 'asdf'

A: You could do this:-
class UserProfileConfig(forms.Form):

    username = forms.CharField(label='Username',max_length=100)

def view(request):
    user_form = UserProfileConfig(initial={'username': request.session['username',})

Which is the generally accepted method, but you can also do this:-
class UserProfileConfig(forms.Form):

    def __init__(self,request,*args,**kwargs):
        super (UserProfileConfig,self).__init__(*args,**kwargs)
        self.fields['username'] = request.session['some_var']

    username = forms.CharField(label='Username',max_length=100)

def view(request):
    user_form = UserProfileConfig(request=request)


text:
Q: How can I create a most recently used file list in Delphi 2009? I have an TActionManager, and a TActionMainMenuBar, and I know how to add an TActionClientItem for each MRU file to the main menu bar.  But do I have to create a separate action for each MRU file in the list?  Or is there a way to create just one action, and somehow pass a tag or something to the action's OnExecute event based on which MRU file was clicked?
Delphi's help says: "For more information about MRU lists, sample code, and methods for finding actions in lists, see FindItemByAction and FindItemByCaption in the online Help."  But I can't find anything in those subjects that is helpful, and certainly not sample code.  I'd really like to avoid using a 3rd party component to get this done.

A: I use code as follows, but you may need to knock it around some. The only thing very obviously missing is IAbbreviatedFileName which essentially wraps up the Windows API function PathCompactPath. You'll want some way to abbreviate very long file names and that's my preferred choice. Sorry for such a huge dump of code, but somebody may find something of use within!
type
  TFileAwareMenuItem = class(TMenuItem)
  private
    FFileName: string;
  public
    property FileName: string read FFileName write FFilename;
  end;

  TMRU = class
  private
    FParent: array of TMenuItem;
    FMenuItemStart: array of TMenuItem;
    FMenuItemFinish: array of TMenuItem;
    FMenuCount: Integer;
    FRegistryKey: string;
    FOwner: TCustomForm;
    FMRUFileNames: TStringList;
    FAction: TAction;
    function GetCount: Integer;
    function GetItem(Index: Integer): string;
    procedure SetAction(Value: TAction);
    procedure Read;
    procedure Write;
    procedure UpdateMenu;
  public
    constructor Create(const RegistrySubKey: string; const Owner: TCustomForm);
    destructor Destroy; override;
    procedure RegisterBoundingMenuItems(Start, Finish: TMenuItem);
    procedure Add(const FileName: string);
    procedure Delete(ItemNum: Integer);
    property Count: Integer read GetCount;
    property Action: TAction read FAction write SetAction;
    property Items[Index: Integer]: string read GetItem; default;
  end;

const
  MRUSize=9;
  AppRegistryKey='??put your apps registry key here??';

var
  Registry: TRegistry;

constructor TMRU.Create(const RegistrySubKey: string; const Owner: TCustomForm);
begin
  inherited Create;
  FRegistryKey := Format('%s\%s', [AppRegistryKey, RegistrySubKey]);
  FOwner := Owner;
  FMRUFileNames := TStringList.Create;
  Read;
end;

destructor TMRU.Destroy;
begin
  Write;
  FreeAndNil(FMRUFileNames);
  inherited;
end;

procedure TMRU.RegisterBoundingMenuItems(Start, Finish: TMenuItem);
begin
  inc(FMenuCount);
  SetLength(FParent, FMenuCount);
  SetLength(FMenuItemStart, FMenuCount);
  SetLength(FMenuItemFinish, FMenuCount);

  FMenuItemStart[FMenuCount-1] := Start;
  FMenuItemFinish[FMenuCount-1] := Finish;
  Assert(Start.Parent=Finish.Parent);
  FParent[FMenuCount-1] := Start.Parent;

  UpdateMenu;
end;

procedure TMRU.UpdateMenu;
var
  Intf: IAbbreviatedFileName;
  i, j: Integer;
  FileName: string;
  NewMenuItem: TFileAwareMenuItem;
begin
  Intf := FOwner as IAbbreviatedFileName;
  for i := 0 to FMenuCount-1 do begin
    j := FMenuItemStart[i].MenuIndex+1;
    while j<FMenuItemFinish[i].MenuIndex do begin
      FParent[i][j].Free;
    end;
    for j := 0 to Count-1 do begin
      NewMenuItem := TFileAwareMenuItem.Create(FMenuItemStart[i].Owner);
      NewMenuItem.Action := Action;
      NewMenuItem.FileName := FMRUFileNames[j];
      FileName := ReplaceString(Intf.AbbreviatedFileName(NewMenuItem.FileName, False), '&', '&&');
      NewMenuItem.Caption := Format('&%d. %s', [j+1, FileName]);
      FParent[i].Insert(FMenuItemFinish[i].MenuIndex, NewMenuItem);
    end;
    FMenuItemStart[i].Visible := (Count>0) and (FMenuItemStart[i].MenuIndex>0);
    FMenuItemFinish[i].Visible := (FMenuItemFinish[i].MenuIndex<FParent[i].Count-1);
  end;
end;

procedure TMRU.Read;
var
  i: Integer;
  s: string;
begin
  if Registry.OpenKey(HKEY_CURRENT_USER, FRegistryKey) then begin
    FMRUFileNames.Clear;
    for i := 0 to MRUSize-1 do begin
      s := Registry.ReadString(IntToStr(i+1), '');
      if s<>'' then begin
        FMRUFileNames.Add(s);
      end;
    end;
    UpdateMenu;
    Registry.CloseKey;
  end;
end;

procedure TMRU.Write;
var
  i: Integer;
  ValueName: string;
begin
  if Registry.OpenKey(HKEY_CURRENT_USER, FRegistryKey, KEY_ALL_ACCESS, True) then begin
    Registry.WriteInteger('Size', MRUSize);
    for i := 0 to MRUSize-1 do begin
      ValueName := IntToStr(i+1);
      if i<Count then begin
        Registry.WriteString(ValueName, FMRUFileNames.Strings[i]);
      end else begin
        if Registry.ValueExists(ValueName) then begin
          Registry.DeleteValue(ValueName);
        end;
      end;
    end;
    Registry.CloseKey;
  end;
end;

function TMRU.GetCount: Integer;
begin
  Result := Min(FMRUFileNames.Count, MRUSize);
end;

function TMRU.GetItem(Index: Integer): string;
begin
  Result := FMRUFileNames[Index];
end;

procedure TMRU.SetAction(Value: TAction);
begin
  if Value<>FAction then begin
    FAction := Value;
    UpdateMenu;
  end;
end;

procedure TMRU.Add(const FileName: string);
var
  i, Index: Integer;
begin
  Index := -1;
  for i := 0 to FMRUFileNames.Count-1 do begin
    if FileNamesEqual(FileName, FMRUFileNames[i]) then begin
      Index := i;
      break;
    end;
  end;

  if Index<>-1 then begin
    FMRUFileNames.Move(Index, 0);
  end else begin
    FMRUFileNames.Insert(0, FileName);
    if FMRUFileNames.Count>MRUSize then begin
      FMRUFileNames.Delete(FMRUFileNames.Count-1);
    end;
  end;

  UpdateMenu;
  Write;
end;

procedure TMRU.Delete(ItemNum: Integer);
begin
  FMRUFileNames.Delete(ItemNum);
  UpdateMenu;
end;

initialization
  Registry := TRegistry.Create;
  if not Registry.KeyExists(AppRegistryKey) then begin
    Registry.CreateKey(AppRegistryKey);
  end;

finalization
  FreeAndNil(Registry);

A: You'll have a separate TAction for each menu item anyway so that they can have distinct Caption values. But you don't have to have separate OnExecute event handlers. The event handler will receive a reference to the action in its Sender parameter. Use the sender's Tag property to refer to a list where your file names are kept. (Don't use the Caption property to discover which file to open; that restricts you from doing nice things like adding accelerators or abbreviating unwieldy paths.)
That's what the documentation assumes you'd do, too. FindItemByAction returns the first item that the given action is attached to. If you attach a single action to all your MRU menu items, then you won't be able to use that function to tell you which menu was selected. On the other hand, the menu item wouldn't hold any more information than the associated action would, so I see no reason to look for the menu item anyway. Just use the information from the action directly.


text:
Q: Android - Layout scrolling with a ListView? My app has a profile page. In that page, I have profile and header photos. And have a ListView at below.
My ListView scrolls correctly but not RelativeLayout which contains profile and header photos.
I can't wrap the whole xml with ScrollView because I have ListView at there. It's not reasonable solution.
I want to make the whole page scrollable. I want photos behave like they are items in ListView.
How can I do that?
Thanks in advance.
Note: Of course I looked for it but couldn't find any significant solution. Neither Google nor Stackoverflow could help.

A: Put the profile and header photos in a relative layout.  Change the ListView to a LinearLayout and wrap it all in a ScrollView. Does this work?

A: overwrite ListView or GridView
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int expandSpec = MeasureSpec.makeMeasureSpec(
               Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    super.onMeasure(widthMeasureSpec, expandSpec);
}

that you can write ListView in ScrollView
try it

A: Technically you can add listview in a scroll view, and your profile and listview both will scroll but it is neither recommended nor it will show same behavior on all devices.
I think, what you can do is use Expandable listView having 1 parent (which will contain profile+pic) and many children. Here your each listview item will become 1 child. Make child View of expandable listview always visible. Enjoy.

A: You can include you headers and profile photos too in your ListView. Basically, you can have a listview with multiple rows with different completely different layouts. Override the methods getViewTypeCount() and getItemViewType(int position in your Adapter. This should start you off in the right direction.


text:
Q: How to upload gallery or captured image to server in android I am facing a problem while uploading an image to amazon s3 server in Android.
I have created a bucket and I need to post the image to that bucket every time. When I try to post the image to that bucket for the first time it can post from next time on words its showing a messages like:

The bucket you are attempting to access must be addressed using the
  specified endpoint. Please send all future requests to this endpoint.

Can I upload images in a single bucket and I tried to
s3Client.createBucket(Constants.getPictureBucket());

// Content type is determined by file extension.
PutObjectRequest por = new PutObjectRequest(Constants.getPictureBucket(), Constants.PICTURE_NAME, new java.io.File(filePath));
s3Client.putObject(por);

Can anyone help me?

A: I assume that you know how to take image from gallery.There are several steps through which you can upload a image in the server.Follow the below steps,
1.Get the Image from the gallery.
2.Convert the image to Bitmap and compress it to your desired format.
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);

3.Convert the Bitmap to byte[] .
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);

4.and then send it using Http Post request.
The link which I am referring is this.
This is the link which serves your exact need http://blog.3dmick.com/2012/06/android-app-for-uploading-images-on-server/

A: Check out these:

*

*Uploading files to HTTP server using POST on Android.

*Android: Upload image or file using http POST multi-part
Please note that data.getData() won't work on Samsung devices. Use a pre-inserted URI instead .


text:
Q: Is there a way to split the variable in different columns Need help to split the variable in different columns.
The variable has 3 inputs separated by the symbol pipe '|'
The size of the input varies.
Using query : split(x, '|') [0] as abc, split(x, '|') [1] as bcd,

Input field x = 234324234|4873264962

Required output:
    column 1: abc 234324234
    column 2: bcd 4873264962

A: InputField x: 234324234|4873264962
select split(x, '\\|') [0] as col1, split(x, '\\|') [1] as col2, split(x, '\\|') [2] as col3 from table.
col1               col2                  col3
234324234         4873264962               NULL


text:
Q: WebSphere 7: GSSCredential expired, must login again I'm recieving this strange error when I'm trying to send a WS request (below). I'm using WebSphere App Server 7.0.0.23. Since I am not familiar with such low level WebSphere funcationaliry, any help regarding this issue would be appreciated. Thanx!
Caused by: javax.xml.ws.WebServiceException: java.io.IOException: Unable to deserialize the Subjects in this Context, cause: org.ietf.jgss.GSSException, major code: 8, minor code: 0
major string: Credential expired
minor string: GSSCredential expired, must login again.
at org.apache.axis2.jaxws.ExceptionFactory.createWebServiceException(ExceptionFactory.java:175)
at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:70)
at org.apache.axis2.jaxws.ExceptionFactory.makeWebServiceException(ExceptionFactory.java:128)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.execute(AxisInvocationController.java:586)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.doInvoke(AxisInvocationController.java:130)
at org.apache.axis2.jaxws.core.controller.impl.InvocationControllerImpl.invoke(InvocationControllerImpl.java:93)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invokeSEIMethod(JAXWSProxyHandler.java:364)
at org.apache.axis2.jaxws.client.proxy.JAXWSProxyHandler.invoke(JAXWSProxyHandler.java:185)
... 72 more
 Caused by: java.io.IOException: Unable to deserialize the Subjects in this Context, cause: org.ietf.jgss.GSSException, major code: 8, minor code: 0
major string: Credential expired
minor string: GSSCredential expired, must login again.
at com.ibm.ws.security.context.ContextImpl.readObject(ContextImpl.java:1116)
at sun.reflect.GeneratedMethodAccessor413.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:600)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1030)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1855)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1759)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1335)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:354)
at com.ibm.ws.websvcs.utils.SecurityContextMigrator$6.run(SecurityContextMigrator.java:389)
at java.security.AccessController.doPrivileged(AccessController.java:251)
at com.ibm.ws.websvcs.utils.SecurityContextMigrator.migrateThreadToContext(SecurityContextMigrator.java:386)
at org.apache.axis2.util.ThreadContextMigratorUtil.performMigrationToContext(ThreadContextMigratorUtil.java:163)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.preExecute(AxisInvocationController.java:608)
at org.apache.axis2.jaxws.core.controller.impl.AxisInvocationController.execute(AxisInvocationController.java:570)
... 78 more
Caused by: com.ibm.websphere.security.WSSecurityException: org.ietf.jgss.GSSException, major code: 8, minor code: 0
major string: Credential expired
minor string: GSSCredential expired, must login again.
at com.ibm.ws.security.context.ContextImpl.doLogin(ContextImpl.java:781)
at com.ibm.ws.security.context.ContextImpl.deserializeSubjects(ContextImpl.java:1144)
at com.ibm.ws.security.context.ContextImpl.readObject(ContextImpl.java:1110)
... 92 more

A: The current credential has expired or your keytab has been discontinued. Export a new keytab for your server.


text:
Q: Copy from TableView/TreeTableView with overridden cell factory I was looking for a universal way (i.e., that can be applied to an arbitrary TableView or TreeTableView) to copy data "as you see it" from a TableView/TreeTableView. I found a couple of posts about how to copy contents from a TableView (here and here), but the important part "as you see it" is the issue with all of them.
All solutions I saw are relying on getting the data associated with each cell (pretty easy to do), and calling .toString() on it. The problem is that when you store one type (let's say a Long) as actual data in a column, and then define a custom cell factory to display it as a String (it's beyond the scope why you would do that, I just want a method that works with such table views):
TableColumn<MyData, Long> timeColumn;
<...>
        timeColumn.setCellFactory(param -> new TableCell<MyData, Long>() {
                @Override
                protected void updateItem(Long item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        super.setText(null);
                    } else {
                        super.setText(LocalDate.from(Instant.ofEpochMilli(item)).format(DateTimeFormatter.ISO_DATE));
                    }
                }
            }
    );

Those methods based on converting the underlying data (which is Long here) to String will obviously not work, because they will copy a number and not a date (which is what the user sees in the table).
Possible (envisioned) solutions:

*

*If I could get my hand on the TableCell object associated with each table cell, I could do TableCell.getText(), and we are done. Unfortunately, TableView does not allow this (have I missed a way to do it?)

*I can easily get the CellFactory associated with the column, and therefore create a new TableCell (identical to that one existing in the table view):
TableCell<T, ?> cell = column.getCellFactory().call(column);
Then the problem is there's no way (again, did I miss it?) to force a TableCell to call the updateItem method! I tried to use commitEdit(T newValue), but it's pretty messy: there are checks inside, so you need to make the whole stuff (column, row, table) Editable, and call startEdit first.
2a. So the only solution that works for me, uses the Reflection to call the protected updateItem, which feels kind of dirty hacking:
// For TableView:
T selectedItem = <...>;
// OR for TreeTableView:
TreeItem<T> selectedItem = <...>;

TableCell<T, Object> cell = (TableCell<T, Object>) column.getCellFactory().call(column);

try {
    Method update = cell.getClass().getDeclaredMethod("updateItem", Object.class, boolean.class);
    update.setAccessible(true);
    Object data = column.getCellData(selectedItem);
    update.invoke(cell, data, data == null);
} catch (Exception ex) {
    logger.warn("Failed to update item: ", ex);
}
if (cell.getText() != null) {
    return cell.getText().replaceAll(fieldSeparator, "");
} else {
    return "";
}

I would appreciate any comment on it, namely if this can be achieved with less blood. Or may be indicate some problems with my solution which I missed.
Here's the full code in case someone wants to use it (in spite of its ugliness :)
package com.mycompany.util;

import com.google.common.collect.Lists;
import javafx.beans.property.ObjectProperty;
import javafx.scene.control.*;
import javafx.scene.input.Clipboard;
import javafx.scene.input.DataFormat;
import javafx.scene.input.KeyCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TableViewCopyable {

    private static final Logger logger = LoggerFactory.getLogger(TableViewCopyable.class.getName());

    protected final String defaultFieldSep;
    protected final String defaultLineSep;

    protected TableViewCopyable(String defaultFieldSep, String defaultLineSep) {
        this.defaultFieldSep = defaultFieldSep;
        this.defaultLineSep = defaultLineSep;
    }

    protected static final <T> void copyToClipboard(List<T> rows, Function<List<T>, String> extractor) {
        logger.info("Copied " + rows.size() + " item(s) to clipboard");
        Clipboard.getSystemClipboard().setContent(Collections.singletonMap(DataFormat.PLAIN_TEXT, extractor.apply(rows)));
    }

    public static TableViewCopyable with(String fieldSep, String lineSep) {
        return new TableViewCopyable(fieldSep, lineSep);
    }

    public static TableViewCopyable toCsv() {
        // When using System.lineSeparator() as line separator, there appears to be an extra line break :-/
        return with(",", "\n");
    }

    public final <T> void makeCopyable(TableView<T> table, Function<List<T>, String> extractor) {

        table.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.C) && event.isControlDown() || event.isControlDown() && event.getCode().equals(KeyCode.INSERT)) {
                // "Smart" copying: if single selection, copy all by default. Otherwise copy selected by default
                boolean selectedOnly = table.getSelectionModel().getSelectionMode().equals(SelectionMode.MULTIPLE);
                copyToClipboard(getItemsToCopy(table, selectedOnly), extractor);
            }
        });

        MenuItem copy = new MenuItem("Copy selected");
        copy.setOnAction(event -> copyToClipboard(table.getSelectionModel().getSelectedItems(), extractor));
        MenuItem copyAll = new MenuItem("Copy all");
        copyAll.setOnAction(event -> copyToClipboard(table.getItems(), extractor));

        addToContextMenu(table.contextMenuProperty(), copy, copyAll);
    }

    public final <T> void makeCopyable(TreeTableView<T> table, Function<List<TreeItem<T>>, String> extractor) {

        table.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.C) && event.isControlDown() || event.isControlDown() && event.getCode().equals(KeyCode.INSERT)) {
                // "Smart" copying: if single selection, copy all by default. Otherwise copy selected by default
                boolean selectedOnly = table.getSelectionModel().getSelectionMode().equals(SelectionMode.MULTIPLE);
                copyToClipboard(getItemsToCopy(table, selectedOnly), extractor);
            }
        });

        MenuItem copy = new MenuItem("Copy selected");
        copy.setOnAction(event -> copyToClipboard(getItemsToCopy(table, true), extractor));

        MenuItem copyAll = new MenuItem("Copy all (expanded only)");
        copyAll.setOnAction(event -> copyToClipboard(getItemsToCopy(table, false), extractor));

        addToContextMenu(table.contextMenuProperty(), copy, copyAll);
    }

    protected <T> List<TreeItem<T>> getItemsToCopy(TreeTableView<T> table, boolean selectedOnly) {
        if (selectedOnly) {
            // If multiple selection is allowed, copy only selected by default:
            return table.getSelectionModel().getSelectedItems();
        } else {
            // Otherwise, copy everything
            List<TreeItem<T>> list = Lists.newArrayList();
            for (int i = 0; i < table.getExpandedItemCount(); i++) {
                list.add(table.getTreeItem(i));
            }
            return list;
        }
    }

    protected <T> List<T> getItemsToCopy(TableView<T> table, boolean selectedOnly) {
        if (selectedOnly) {
            // If multiple selection is allowed, copy only selected by default:
            return table.getSelectionModel().getSelectedItems();
        } else {
            return table.getItems();
        }
    }

    protected void addToContextMenu(ObjectProperty<ContextMenu> menu, MenuItem... items) {
        if (menu.get() == null) {
            menu.set(new ContextMenu(items));
        } else {
            for (MenuItem item : items) {
                menu.get().getItems().add(item);
            }
        }
    }

    public final <T> void makeCopyable(TableView<T> table, String fieldSeparator) {
        makeCopyable(table, csvVisibleColumns(table, fieldSeparator));
    }

    public final <T> void makeCopyable(TreeTableView<T> table, String fieldSeparator) {
        makeCopyable(table, csvVisibleColumns(table, fieldSeparator));
    }

    public final <T> void makeCopyable(TableView<T> table) {
        makeCopyable(table, csvVisibleColumns(table, defaultFieldSep));
    }

    public final <T> void makeCopyable(TreeTableView<T> table) {
        makeCopyable(table, defaultFieldSep);
    }

    protected <T> String extractDataFromCell(IndexedCell<T> cell, Object data, String fieldSeparator) {
        try {
            Method update = cell.getClass().getDeclaredMethod("updateItem", Object.class, boolean.class);
            update.setAccessible(true);
            update.invoke(cell, data, data == null);
        } catch (Exception ex) {
            logger.warn("Failed to updated item: ", ex);
        }
        if (cell.getText() != null) {
            return cell.getText().replaceAll(fieldSeparator, "");
        } else {
            return "";
        }
    }

    public final <T> Function<List<T>, String> csvVisibleColumns(TableView<T> table, String fieldSeparator) {
        return (List<T> items) -> {
            StringBuilder builder = new StringBuilder();
            // Write table header
            builder.append(table.getVisibleLeafColumns().stream().map(TableColumn::getText).collect(Collectors.joining(fieldSeparator))).append(defaultLineSep);
            items.forEach(item -> builder.append(
                    table.getVisibleLeafColumns()
                            .stream()
                            .map(col -> extractDataFromCell(((TableColumn<T, Object>) col).getCellFactory().call((TableColumn<T, Object>) col), col.getCellData(item), fieldSeparator))
                            .collect(Collectors.joining(defaultFieldSep))
            ).append(defaultLineSep));
            return builder.toString();
        };
    }

    public final <T> Function<List<TreeItem<T>>, String> csvVisibleColumns(TreeTableView<T> table, String fieldSeparator) {
        return (List<TreeItem<T>> items) -> {
            StringBuilder builder = new StringBuilder();
            // Write table header
            builder.append(table.getVisibleLeafColumns().stream().map(TreeTableColumn::getText).collect(Collectors.joining(fieldSeparator))).append(defaultLineSep);
            items.forEach(item -> builder.append(
                    table.getVisibleLeafColumns()
                            .stream()
                            .map(col -> extractDataFromCell(((TreeTableColumn<T, Object>) col).getCellFactory().call((TreeTableColumn<T, Object>) col), col.getCellData(item), fieldSeparator))
                            .collect(Collectors.joining(defaultFieldSep))
            ).append(defaultLineSep));
            return builder.toString();
        };
    }
}

Then the usage is pretty simple:
    TableViewCopyable.toCsv().makeCopyable(someTreeTableView);
    TableViewCopyable.toCsv().makeCopyable(someTableView);

Thanks!


text:
Q: What's the principal difference between MS AppCenter and Azure DevOps (former VSTS)? I am "a bit" confused in understanding of what of those two services are capable for and what are the core differences between of them.
In general, I understand what they provide, and separately I used them both earlier (VSTS as issue tracker, mostly), and AppCenter for the sources to be built and deployed.
However:
1. They both have building and (apparently) publishing capabilities.
In DevOps has the option of setting up the Pipeline:

Same way as AppCenter has mostly the same:

2. They both also have Tests sections with (seems like) similar functionality.
3. They both provide ability of deploying the build into Play/App Stores.
AppCenter - with "Stores" section, and DevOps with this plugin (at least).
They both also have some specific features (like AppCenter has PushNotifications functionality and Azure DevOps has issue tracking), however, for the apps distribution they look pretty alike.
So, which of them should be used for what particular tasks? Or this is just one the modern "marketing" feature of Microsoft, when there is mostly no difference, but those are just two similar thing wrapped with different-colored envelope?

A: In short, App Center is for mobile app deployment & monitoring whereas DevOps is for any-platform development & deployment. App Center focuses on deploying and monitoring mobile apps, while DevOps focuses on the entire development lifecycle of all types of projects along with deployment.
So I think one needs both for an entire project perspective: DevOps to develop and deploy, and App Center to deploy and/or monitor.
If we are comfortable with multiple tools like github/bitbucket for git, jira or trello for management, then we only need to have App Center. Otherwise everything can be under one roof with DevOps.
Anyhow, I prefer App Center for my projects as I can have all the features of bitbucket and jira, along with an easier test & deployment set up and monitoring.
I can't say they should merge everything under DevOps, as there are users like me who prefers to use only the deployment and/or monitoring (of mobile apps) with Microsoft and enjoy other products for the rest. Hence, with the current set up, they are addressing two different sets of customers.


text:
Q: How to programatically turn on/off a Data Annotation Validation Attribute So, I am using ASP.NET MVC 3 and Entity Framework 4.1 (code-first).
I have a class like this:
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    [Range(18, 99)]
    public int Age { get; set; }
}

The range validation is fired correctly. But, for example, in some situations I would like to change the range for the Age attribute. Or even turn it off. How could I do it without changing my Model class? Is this possible to made programatically?

A: You can use the IValidatableObject interface and define custom validation rules.
See my answer at:
Using Data Annotations to make a field required while searching for another in a form mvc 3
Its usually just a matter of implementing the interface and determine when to enforce your rules.

A: I just realised the solution for this case.
Eg. A user can have an authorization to create a 14 years old person.
Before save the Model, we can invoke DataContext.GetValidationErrors() and infer if the only error validation is that we want to disable, and then set
DataContext.Configuration.ValidateOnSaveEnabled = false;
So, this way we are able to save the model.

A: Yes, it is possible to inject validators programmatically.  Altering existing validators presents separate issues, as some attributes are read-only, so you may have to delete and replace your existing validator.
You can add a class to work on the validators by following my answer to this question.


text:
Q: How to interleave vector of strings with a string I have the following vectors example:
v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")

Note that the length of each vector can be varied.
What I want to do is to interleave each vector with a string:
linker <- "xxx"

Resulting in this:
c("AA", "xxx", "BB")
c("AA","xxx",  "BB", "xxx", "CCC")

How can I achieve that?

A: You could use an rbind trick here:
v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")
linker <- "xxx"

head(c(rbind(v2, linker)), -1)

[1] "AA"  "xxx" "BB"  "xxx" "CCC"

A: We can try strsplit + paste0 like below
> strsplit(paste0(v2, collapse = sprintf(" %s ", linker)), " ")[[1]]
[1] "AA"  "xxx" "BB"  "xxx" "CCC"

A: Here you have a possible answer:
v1 <- c("AA", "BB")

v2 <- c("AA", "BB", "CCC")

linker <- "xxx"

interleave <- function(v,l){

  result <- c()

  for(i in 1:length(v)){

    if(i!=1){

      result <- c(result,l,v[i])

    }else{

      result <- c(result,v[i])

    }

  }

  return(result)

}

interleave(v1,linker)

interleave(v2,linker)

Results:
> interleave(v1,linker)
[1] "AA"  "xxx" "BB"
>
> interleave(v2,linker)
[1] "AA"  "xxx" "BB"  "xxx" "CCC"

A: We can use append, and then head to remove the trailing linker:
append_linker <- function(vector, linker){
lapply(vector, \(x) append(x, linker)) |>
        unlist() |>
        head(-1)
}

append_linker(v1, linker)

[1] "AA"  "xxx" "BB"

append_linker(v2, linker)

[1] "AA"  "xxx" "BB"  "xxx" "CCC"

A: A creative application of mapply and c:
v1 <- c("AA", "BB")
v2 <- c("AA", "BB", "CCC")
linker <- 'xxx'

c(mapply(c, linker, v1))[-1]

[1] "AA"  "xxx" "BB"

c(mapply(c, linker, v2))[-1]

[1] "AA"  "xxx" "BB"  "xxx" "CCC"


text:
Q: ASP.net C# SQL Azure Encryption I have a ASP.net C# Cloud application and I need to encrypt my SQL Azure Tables. I have researched about this and I found out that SQL Azure doesn't support encryption and that you have to do it in the application layer.
Now I have no problem encrypting my stored procedure parameters and decrypting them again when i read out, however this means I cannot perform a proper search on my cells anymore.
I have no idea how to deal with this except reading the whole thing in memory and filtering it there, but that just feels dirty and I don't wanna lose performance once I start reading a lot of cells.
Do you guys have any idea how to cope with this??
Thanks a lot

A: The only realistic way to have encryption-at-rest in SQL Server in Azure is to provision an IaaS VM with full SQL Server installed, as described here. Then you can configure whatever full-blown SQL features you want, including encryption, full-text indexing and all the other stuff that's not available in Windows Azure SQL Database.
But as @spender says, is encryption really necessary in this instance? The encryption-at-rest feature is to protect sensitive data in the event of the physical disk being compromised, and that's not really going to happen in a massive-scale cloud hosting scenario.
Update: full-text search and TDE are now supported in SQL Azure http://azure.microsoft.com/blog/2015/04/30/full-text-search-is-now-available-for-preview-in-azure-sql-database/
http://www.sqlindepth.com/full-text-search-in-sql-azure/
http://blogs.msdn.com/b/sqlsecurity/archive/2015/04/29/announcing-transparent-data-encryption-for-azure-sql-database.aspx

A: In case anyone else stumbles on this question, note that Azure SQL Database now supports Transparent Data Encryption (TDE, aka "encryption-at-rest").
See: https://msdn.microsoft.com/en-us/library/dn948096.aspx

A: The problem is that this is all very sensitive data. The only way we have done it now is to actually manually encrypt every entry that gets into the database. The only issue with this is that searching this data now because very hard to deal with.
We actually implemented an extra table that contains the first 4 encrypted letters which we then use for our searches. I know it's very farfetched but this was the only way to do it


text:
Q: Randomized Quick Sort and Partition Probability? We know about Quick Sort and Randomized Version and Partition. I ran into a Fact when I read my notes.
Let $0 < a < 0.5$ be some constant. We have an $n$-element array as input. Randomized quicksort chooses one element from array uniformly at random as a pivot and partitions. With probability $1-2a$ the smallest section be greater than $an$.
How this probability is calculated?

A: You are looking for the probability that the smaller of the two sections contains more than fraction $a$ of the array.
If the pivot element is selected uniformly at random from the array, then one section will contain fraction $X$ of the array, and the other will contain fraction $1-X$, where $X$ has uniform distribution over the interval $[0,1]$. So the desired probability is
$$P(\min(X,1-X)>a)$$
which has probability $1-2a$ because
$$\min(X,1-X)>a\ \Longleftrightarrow\ a<X<1-a\;.$$


text:
Q: Changing the case of a single word in a string using Apple Script So I have the Apple Script:
-- Uses the satimage osax
-- Get it at http://www.satimage.fr/software/en/downloads/downloads_companion_osaxen.html

tell application "Music"
    try
        set the_tracks to the selection
        repeat with a_track in the_tracks
            set the_old_name to name of a_track as string
            set the_new_name to titlecase the_old_name
            set the name of a_track to the_new_name
            log the_old_name
            log the_new_name
        end repeat
    on error
        set the_tracks to the selection
        repeat with a_track in the_tracks
            set the_old_name to name of a_track as string
            set the_new_name to titlecase the_old_name
            set the name of a_track to the_new_name
            log the_old_name
            log the_new_name
        end repeat
    end try
end tell

And I want to be able to change the capitalization of a single element in a string/title. Specifically changing Roman numerals to all caps, in this example finding "Iv." and changing it to "IV.":
from:
Concerto Grosso No. 8 in G Minor, Op. 6, "Christmas Concerto": Iv. Vivace
to: Concerto Grosso No. 8 in G Minor, Op. 6, "Christmas Concerto": IV. Vivace
Any help would be greatly appreciated. Thanks!

A: This handler replaces all roman characters from I to IX followed by a period with their uppercase equivalent. It uses the powerful API's from the Foundation framework
use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

on uppercaseRomanCharacters(theText)
    set cocoaString to current application's NSString's stringWithString:theText
    set romanRange to cocoaString's rangeOfString:"(I{1,3}|IX|IV|VI{0,3})\\." options:1025
    if romanRange's location < cocoaString's |length|() then
        set substring to cocoaString's substringWithRange:romanRange
        return (cocoaString's stringByReplacingCharactersInRange:romanRange withString:(substring's uppercaseString())) as text
    end if
    return theText
end uppercaseRomanCharacters

set theString to "Concerto Grosso No. 8 in G Minor, Op. 6, \"Christmas Concerto\": iv. Vivace"
set newName to uppercaseRomanCharacters(theString)

You can use it in your loop
repeat with a_track in the_tracks
    set the_old_name to name of a_track -- as string is redundant
    set the_new_name to my uppercaseRomanCharacters(the_old_name)
    set the name of a_track to the_new_name
    log the_old_name
    log the_new_name
end repeat

The handler must be located somewhere on the top level of the script.
Note: 1025 is the integer value for the options NSCaseInsensitiveSearch | NSRegularExpressionSearch


text:
Q: not seeing query results echo <?php
include 'connect.php';
$query = "SELECT * FROM (
SELECT CONCAT(customer_name, ' ', address, ' ', street, ' ', phone_1, ' ', phone_2, ' ', phone_3, ' ', phone_4) as `mysearch`
FROM customers) base
WHERE `mysearch` LIKE '%102%'";

$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo "customer name: " . $row['customer_name'];
}
?>

The query is working, but I am missing something for being able to echo the results. It returns the results when ran in phpmyadmin. There are 2 entries in the database that should be returned.
My actual output is as follows:

customer name: customer name:

indicating that it found the 2 entries, but I can't get them to echo. customer_name is a match to a field name in the database.

A: If you want to have customer_name in your result, you must select it as separated column in your subquery:
SELECT
    *
    FROM (
        SELECT
            customer_name,
            CONCAT(customer_name, ' ', address, ' ', street, ' ', phone_1, ' ', phone_2, ' ', phone_3, ' ', phone_4) as `mysearch`
        FROM
            customers
    ) base
WHERE
    `mysearch` LIKE '%102%'


text:
Q: One Heroku worker process for both delayed_job and sidekiq? Currently our Heroku app has two dynos: web and worker. The worker dyno is set up to run bundle exec rake jobs:work, which starts up delayed_job. I have some new Sidekiq jobs that I also need to run. (I plan to convert our delayed_job jobs to Sidekiq soon, but haven't yet.) My question is: do I need to add and pay for a third Heroku dyno ("sidekiqworker"?), or is there a way for me to specify that my existing worker dyno run both delayed_job and Sidekiq?

A: You will need to pay for a third heroku dyno unfortunately. I've experimented with naming both processes as "Workers" but only one would be registered while the other one wouldn't be. When adding a new process name, heroku updates and will set that new process name to 0 dynos.
Refer to this for more details multiple worker/web processes on a single heroku app


text:
Q: Does dual boot linux need two swap partitions? My harddrive is partitioned as follows. I used GParted to gather this info.

/dev/sda1 ---- ext4 ---- Ubuntu

/dev/sda2 ---- extended
---> /dev/sda5 ---- ext4 ---- Kali
---> /dev/sda6 ---- linux-swap

I am assuming that both sda5 and sda6 are both a part of sda2 and it appears to me that the linux-swap is only available to Kali and not Ubuntu. Am I correct in assuming this?
If so, should I create an additional linux-swap for ubuntu under sda1?

A: No, you don't need separate swap partitions.
You should be able to modify your /etc/fstab file in the Ubuntu system to point to the same location as the swap file in the Kali system.  Then both linuxes will use the same partition.