text:
Q: React - Problems with function parameters for assigning values I have a sidebar where it is possible to change the background of the sidebar as a background, I store pictures in the object, everything worked well for me until I decided to add a second property "color" inside the object, that is, in addition to changing the background, the color of the text also changes. it looks like this

I think that the essence is clear, but as I mentioned earlier, the problems started when I decided to add a second property, that is, the color of the text
The problem is that the color property does not work for me, that is, it works, but in this case the sidebar background does not work
My object looks very simple
import Bg from "../../SideBar/Background/mac.jpg"
import Pink from "../../SideBar/Background/pink.jpg"
import Anapa from "../../SideBar/Background/anapa.jpg"

const SideBarBackgrounds = [
    {
        SideBarWallpaper: Bg,
        color: "red",
    },
    {
        SideBarWallpaper: Pink,
        color: "green",
    },
    {
        SideBarWallpaper: Anapa,
        color: "yellow",
    },
].map((item) => {
        return {
            SideBarWallpaper: item.SideBarWallpaper,
            color: item.color,
        }
    }
)

export default SideBarBackgrounds;
That is, I import the picture and apply it as the value for the SideBarWallpaper properties then create a second property named color and apply the string as the color
Then I use local storage to save the user changes.
export const CounterContext = createContext([]);

export default function ThemeDoc(props) {

    const [SideBarBackground, SetSideBarBackground] = useState(JSON.parse(localStorage.getItem("BgKey")));

    useEffect(() => {
        localStorage.setItem("BgKey", JSON.stringify(SideBarBackground));
    })

    const ChangeSideBarWallpaper = (SideBarWallpaper) => {
        localStorage.setItem('BgKey', JSON.stringify(SideBarWallpaper));
        SetSideBarBackground(SideBarWallpaper);
    }

    return (

            <CounterContext.Provider value={{
                SideBarWallpaperValue: [SideBarBackground, SetSideBarBackground],
            }}>
                <SideBar ChangeSideBarWallpaper={ChangeSideBarWallpaper} SideBarPageContent={SideBarPageContent} {...props} />
            </CounterContext.Provider>

    );
}

As you can see, I use React Context since I have a lot of themes and I import them in many files, in this case I deleted everything personal and left only the code that belongs to the background of the sidebar
Then I have a component called SideBarWallpaperContainer where I import my object, create a loop using a map, process each property from the object and finally import the SideBarWallpaperContainer component inside the SideBarModal component
export default function SideBarWallpaperContainer(props) {

    const SideBarWallpaperList = SideBarBackgrounds.map((theme, index) => {
        return (
             props.ChangeSideBarWallpaper(theme.SideBarWallpaper)} alt={"Select Theme"}/>
        );
    })
    return (
        <>
            {SideBarWallpaperList}
        </>
    );
}

SideBarModal.jsx
const DraggableDialog = (props) => {
   ...
   return(
      <SideBarWallpaperContainer {...props} />
      ...
  );
}

Through props, I get the ChangeSideBarWallpaper method to change the background and color
And the color for the sidebar text I get using useContext it looks like this
SideBarMenu.jsx
export default function SideBarMenu(props) {

    const {SideBarWallpaperValue} = React.useContext(CounterContext);

    const [SideBarWallpaperTheme,] = SideBarWallpaperValue;
    const SideBarWallpaperStyle = SideBarWallpaperTheme;

return(

        <Link
           style={{ color: SideBarWallpaperStyle && SideBarWallpaperStyle.color,}}>{item.name}
        </Link>

);

}

Now when you roughly understand how all the logic works, I want to explain the problem. The problem is that either the sidebar color or the background does not work for me, please pay attention to the method
props.ChangeSideBarWallpaper (theme.SideBarWallpaper)}

When I use theme.SideBarWallpaper as a parameter inside the ChangeSideBarWallpaper method, only the background works for me and not the color, and this is of course logical, then I tried to apply 2 parameters, the color and the background, it looked like this
onClick={() => props.ChangeSideBarWallpaper(theme.SideBarWallpaper, theme.color)}

But in this case, only the background also worked and the only solution that remained for me to transfer the entire value, it looked like this
onClick={() => props.ChangeSideBarWallpaper(theme)}

And then I was surprised now only the sidebar color works for me but the background does not work, You can look at the picture (sorry if I'm so long and boring to explain :) I just want you to understand the problem as clearly as possible)

I decided to check if I get a picture and yes I get

Now that you understand the problem, I will be interested in hearing your advice, thank you for paying attention to my long question.

A: Before I demonstrate the solution, I would like to say that the problem lies with me, I, as always, introduced myself impatiently and inattentively: (it turns out that I forgot that in the SideBar component I get the SideBarBackground value in short, the code looked like this
    const {someValue} = useContext(SideBarContext);
    const {SideBarValue, SideBarWallpaperValue} = React.useContext(CounterContext);

    const [SideBarTheme] = SideBarValue;
    const [SideBarBackground] = SideBarWallpaperValue;

<div style={{backgroundImage: `url(${SideBarBackground})`}}>
...

Then I got the SideBarWallpaper value
<div style={{backgroundImage: `url(${SideBarBackground.SideBarWallpaper})`}}>
...


text:
Q: How to check table columns in dbml before executing query in Linq I am having one window application which we will run on different systems to update database.
Suppose we have 10 systems. Out of 10 systems 2 systems are using latest application with latest DBML. In latest DBML I have added columns in tables. For these systems everything working good.
Problem :
When I try to run it on old systems where I am using old database. When I run application it throws an error

columns not found

Reason behind this is DBML is updated but database is not updated.
How can I handle this situation? I cannot update the database due to some restrictions.

A: I think that in your case you should version your code. The dbml that you are using should reflect the schema of the database and in your case it doesn't happens.
So I suggest you two version of your application each one with dbml updated with the database.

*

*So your application version 1.1 will contain older dbml

*Version 1.2 is the actual version with updated dbml

update
So my answer is No you can't do something like this because the dbml (that doesn't reflect the database) thinks that columns all exist.
So you can try checking this columns with a standard SqlCommand and do a query directly to the database.

A: To solve this problem I am using the following steps :
1.Added one more DBML in project in other namespace than older DBML.Here i drop table with old schema.
2.Get columns of table as follow :
 class CheckVersion
{
    public static bool isOldSystem;
    public static void CheckColumnsInMasterInventory()
    {
        string[] Columns = { "Col1", "Col2", "Col3", "Col4" };//New Columns Which are not present in Old table.
        List<string> ColumnList = new List<string>();
        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
        {
            using (var schemaCommand = new SqlCommand("SELECT * FROM dbo.Table1", con))
            {
                con.Open();
                using (var reader = schemaCommand.ExecuteReader())
                {
                    DataTable dt = new DataTable();
                    dt.Load(reader);
                    foreach (DataColumn column in dt.Columns)
                    {
                        ColumnList.Add(column.ColumnName);
                    }
                }
            }
        }
        var columnCount = ColumnList.Where(item => Columns.Contains(item)).Count();
        if (columnCount == 4)
            isOldSystem = false;
        else
            isOldSystem = true;
    }
}

3.On the Basis of
isOldSystem

value i am executing linq as follow :
  DataLoaderDataContext objDC = new DataLoaderDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        DataLoaderOldDataContext objOldDC = new DataLoaderOldDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

            if (!CheckVersion.isOldSystem)
            {
                //objDC
            }
            else
            {
               //objOldDC
            }

Now i am able to handle Old as well as New Database.

A: It might be an option to create updateable views. I do know you can add views to the DBML.
http://msdn.microsoft.com/en-us/library/ms187956.aspx
In theory, this could work. But I have to admit I never tried this in real life.
How to do it, is answered overhere at SO:
LINQ to SQL : How to Insert record into a view?

redpajama_set_name: RedPajamaStackExchange


text:
Q: get data from related tables in postgresql assuming these 3 tables
create table item(
    item_id integer NOT NULL primary key,
    name varchar(50) NOT NULL,
    description varchar(150) NOT NULL,
    in_stock integer NOT NULL
)

create table customer(
    customer_id VARCHAR(9) NOT NULL primary key,
    name VARCHAR(50) NOT NULL,
    lastname VARCHAR(50) NOT NULL,
    phone VARCHAR(15) NOT NULL,
    join_date DATE NOT NULL
)

create table purchase(
    purchase_id integer references item,
    customer_id varchar(9) references customer,
    purchase_date TIMESTAMP NOT NULL,
    amount INTEGER NOT NULL,
    PRIMARY KEY(purchase_id, customer_id, purchase_date)
)

*

*how could I get each unique name and the total amount of items purchased?

*how could I get each purchase name and the buyer's name and lastname?

*how could I get each item and how many of it were sold?

A: The two topics you are looking to learn are how to use GROUP BY and how to JOIN tables. Here's an example (more or less) that answers your first question and uses both tools:
select
  C.customer_id as customer_id,
  max(C.name) as customer_name,
  sum(amount) as total_amount
from customer C
left join purchase P on C.customer_id = P.customer_id
group by C.customer_id


text:
Q: how can we use will_paginate in ruby on rails 3.0.3 is their will_paginate will support to ruby on rails 3.0.3?

A: Yes. In beta - https://github.com/mislav/will_paginate/tree/rails3.

A: Yes, Its still in beta and we have used will paginate successfully in a production rails project.The bug that i have seen so far is the count of items at times is wrong. You can work around it by firing your own count query and populate it.


text:
Q: Getting the ImageView image location I am using the ImageView to display a image with a image stored in SD card. Like this-
    ImageView grp_icon=(ImageView)gridView.findViewById(R.id.grid_item_image);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            String path="/sdcard/Letsmeet/letsmeet_media/group_images/"+gridImage[position];
            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
            grp_icon.setImageBitmap(bitmap);

And I am trying to get the image location to display the same image in another activity by sending the location in Intent. But it gives a different location Why?
The code where I get the ImageView image location is
String groupName=((TextView) v.findViewById(R.id.grid_item_label)).getText().toString();
                ImageView grp_image=(ImageView)v.findViewById(R.id.grid_item_image);
                Bitmap b=((BitmapDrawable)grp_image.getDrawable()).getBitmap();
                Uri image=getImageUri(getActivity().getApplicationContext(), b);
                String path=image.toString();
                Intent toMangeGroup=new Intent(getActivity(),ManageGroup.class);
                Bundle bundle=new Bundle();
                bundle.putString("grp_name", groupName);
                bundle.putString("grp_image", path);
                toMangeGroup.putExtras(bundle);
                startActivity(toMangeGroup);

Here I am getting the path as "content://media/external/images/media/42424" but the actual path of the image is "/sdcard/Letsmeet/letsmeet_media/group_images/1395247992445"

A: System.out.println("this is path where stored.."
                + Environment.getExternalStorageDirectory()
                        .getAbsolutePath());

A: Try this for getting file path on sdcard:
String filePath = Environment.getExternalStorageDirectory().toString() + File.separator + "Letsmeet/letsmeet_media/group_images/" + gridImage[position];

A: use this code:may help you..
Bitmap mybit=BitmapFactory.decodeFile(file1.getAbsolutePath());
image.setImageBitmap(mybit);

used to store your image in file format and get the image from that path.

A: Look at this Get filename and path from uri from mediastore. The answer provided by Nikolay Nikiforchuk is the way to go. And that does not only work with the mediafile but will also work good with all the files stored on SDCard
just replace this line
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

with this one
int column_index = cursor.getColumnIndexOrThrow("_data");

That would work fine.


text:
Q: Importing TFHpple on Swift I'm relatively new to programming and I have spent hours on trying to understand how to import TFHpple library (or any Objective C library) into my Swift code. I have read the documentations but I still don't really understand it can anyone point me in the right direction?

A: *

*Add the Objective-C files to your project

*Xcode will ask if you want a Bridging Header, say YES

*Add #import "TFHpple.h" to your bridging header

*Add libxml2 to Build Phases > Link binary with library

*Add $(SDKROOT)/usr/include/libxml2 in Header Search Paths

*Call your methods in Swift


text:
Q: Is there a way to reference the broadcast ip of a micro segmented network from another in Python on a single router? I thought this should be super simple, but considering that I haven't been able to find much online, it might be weirder than I thought, or I'm barking up the wrong tree entirely.
I'm looking to find a way to discover broadcast packets from a micro segmented network from the context of the hidden main network. I have devices broadcasting from 192.168.1.0 on port 9999, and I would like to use the Python socket library in order to discover these and connect to them.
At the moment, this is working fine from the context of everything being on the same subnet and using 255.255.255.255 to locate, like so:
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.settimeout(timeout)
    sock.sendto(req, ('255.255.255.255', 9999))

Once I make the request from a device on 192.168.0.0 to 192.168.1.0, I don't see anything. My attempt thus far has been using the broadcast address of the subnet I'm looking to discover from, like so:
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.settimeout(timeout)
    sock.sendto(req, ('192.168.1.255', 9999))

If anyone can redirect me to a better solution, preferably using the socket lib but at this point I'm open to anything, it would be very much appreciated. Thanks


text:
Q: How can I dynamically generate content of a Blockly dropdown menu? I am writing an application using python and flask.
In the webinterface, the user is able to make small customized programs using blockly.
Some of the already existing blocks have a dropdown menu.
All that works fine.
But now I want to have a block with a dropdown menu where the options are certain files on a usb stick the python backend found by walking through the usb stick directory.
I would like to fill the dropdown menu with these files now. I cannot, however, know them in advance and that is why they have to be dynamically generated - but by python, not by javascript or that like.
I already found this here: https://developers.google.com/blockly/guides/create-custom-blocks/dropdown-menus (at "Dynamic menu" at the end), but that does not help in my case, since I want the information to come from the python backend and not from javascript.
Does anyone know a way to do this?
Thank you a lot in advance!

A: This is a pretty old question, so I'm not sure if the OP still needs an answer, but I'm answering on the assumption that this is a situation where the OP is using an asynchronous JavaScript call to the backend and can't just return the results because of that.
We have a not dissimilar situation in our application (albeit using a nodejs backend) where we're populating dropdowns based on options retrieved from Google Cloud Datastore. We have a React App, so our solution was to have a Flux store attached to the window which our asynchronous call populates upon completing, and then have the dropdown generation code access that store. Obviously, a full Flux store may not be appropriate for all situations, but my general advice here would be to pass in an option generator function and have it read from a store or other variable on the window, and then have your call to the backend run on page load (or when otherwise appropriate) and populate the store on the window. If your app inits before the call is done, you can have it set up to show that it's loading options based on a flag on the store.
As a very simplified case, you might have:
// on page load
window.store = {done: false};
myBackendCall()
.then(function(results){
    window.store = {
        results: results,
        done: true
    };
})
.catch(function(error){
    console.error(error);
    window.store = {results: [], done: true};
});

Then in your selector, you might go with something like:
function generateOptions(){
    if(!window.store.done) {
        return [['Loading...', 'loading']];
    } else {
        return [['Select a file', '']].concat(window.store.results);
    }
}
this.appendDummyInput()
    .appendField(new Blockly.FieldDropdown(generateOptions), fieldName);

Obviously, this is a gross simplification, but I think it's enough to show the technique. We actually made our own custom Blockly fields for this for other reasons, but this should still work with a vanilla Blockly dropdown. Swap out Promise chaining for callbacks if that's how your setup is. You could also make the call inside the block and set a variable on the block itself (this.store or whatever), but that would result in multiple calls being made for multiple instances of the block, so that may not be appropriate for you.


text:
Q: How to break a geometry into blocks? I am certain there is already some algorithm that does what I need, but I am not sure what phrase to Google, or what is the algorithm category.
Here is my problem: I have a polyhedron made up by several contacting blocks (hyperslabs), i. e. the edges are axis aligned and the angles between edges are 90°. There may be holes inside the polyhedron.
I want to break up this concave polyhedron in as little convex rectangular axis-aligned whole blocks are possible (if the original polyhedron is convex and has no holes, then it is already such a block, and therefore, the solution). To illustrate, some 2-D images I made (but I need the solution for 3-D, and preferably, N-D):
I have this geometry:

One possible breakup into blocks is this:

But the one I want is this (with as few blocks as possible):

I have the impression that an exact algorithm may be too expensive (is this problem NP-hard?), so an approximate algorithm is suitable.
One detail that maybe make the problem easier, so that there could be a more appropriated/specialized algorithm for it is that all edges have sizes multiple of some fixed value (you may think all edges sizes are integer numbers, or that the geometry is made up by uniform tiny squares, or voxels).
Background: this is the structured grid discretization of a PDE domain.
What algorithm can solve this problem? What class of algorithms should I
search for?

A: Update: Before you upvote that answer, I want to point out that my answer is slightly off-topic. The original poster have a question about the decomposition of a polyhedron with faces that are axis-aligned. Given such kind of polyhedron, the question is to decompose it into convex parts. And the question is in 3D, possibly nD. My answer is about the decomposition of a general polyhedron. So when I give an answer with a given implementation, that answer applies to the special case of polyhedron axis-aligned, but it might be that there exists a better implementation for axis-aligned polyhedron. And when my answer says that a problem for generic polyhedron is NP-complete, it might be that there exists a polynomial solution for the special case of axis-aligned polyhedron. I do not know.
Now here is my (slightly off-topic) answer, below the horizontal rule...

The CGAL C++ library has an algorithm that, given a 2D polygon, can compute the optimal convex decomposition of that polygon. The method is mentioned in the part 2D Polygon Partitioning of the manual. The method is named CGAL::optimal_convex_partition_2. I quote the manual:

This function provides an implementation of Greene's dynamic programming algorithm for optimal partitioning [2]. This algorithm requires O(n4) time and O(n3) space in the worst case.

In the bibliography of that CGAL chapter, the article [2] is:

[2] Daniel H. Greene. The decomposition of polygons into convex parts. In Franco P. Preparata, editor, Computational Geometry, volume 1 of Adv. Comput. Res., pages 235–259. JAI Press, Greenwich, Conn., 1983.

It seems to be exactly what you are looking for.
Note that the same chapter of the CGAL manual also mention an approximation, hence not optimal, that run in O(n): CGAL::approx_convex_partition_2.
Edit, about the 3D case:
In 3D, CGAL has another chapter about Convex Decomposition of Polyhedra. The second paragraph of the chapter says "this problem is known to be NP-hard [1]". The reference [1] is:

[1] Bernard Chazelle. Convex partitions of polyhedra: a lower bound and worst-case optimal algorithm. SIAM J. Comput., 13:488–507, 1984.

CGAL has a method CGAL::convex_decomposition_3 that computes a non-optimal decomposition.

A: I have the feeling your problem is NP-hard. I suggest a first step might be to break the figure into sub-rectangles along all hyperplanes. So in your example there would be three hyperplanes (lines) and four resulting rectangles. Then the problem becomes one of recombining rectangles into larger rectangles to minimize the final number of rectangles. Maybe 0-1 integer programming?

A: I think dynamic programming might be your friend.
The first step I see is to divide the polyhedron into a trivial collection of blocks such that every possible face is available (i.e. slice and dice it into the smallest pieces possible).  This should be trivial because everything is an axis aligned box, so k-tree like solutions should be sufficient.
This seems reasonable because I can look at its cost.  The cost of doing this is that I "forget" the original configuration of hyperslabs, choosing to replace it with a new set of hyperslabs.  The only way this could lead me astray is if the original configuration had something to offer for the solution.  Given that you want an "optimal" solution for all configurations, we have to assume that the original structure isn't very helpful.  I don't know if it can be proven that this original information is useless, but I'm going to make that assumption in this answer.
The problem has now been reduced to a graph problem similar to a constrained spanning forest problem.  I think the most natural way to view the problem is to think of it as a graph coloring problem (as long as you can avoid confusing it with the more famous graph coloring problem of trying to color a map without two states of the same color sharing a border).  I have a graph of nodes (small blocks), each of which I wish to assign a color (which will eventually be the "hyperslab" which covers that block).  I have the constraint that I must assign colors in hyperslab shapes.
Now a key observation is that not all possibilities must be considered. Take the final colored graph we want to see.  We can partition this graph in any way we please by breaking any hyperslab which crosses the partition into two pieces.  However, not every partition is meaningful.  The only partitions that make sense are axis aligned cuts, which always break a hyperslab into two hyperslabs (as opposed to any more complicated shape which could occur if the cut was not axis aligned).
Now this cut is the reverse of the problem we're really trying to solve.  That cutting is actually the thing we did in the first step.  While we want to find the optimal merging algorithm, undoing those cuts.  However, this shows a key feature we will use in dynamic programming: the only features that matter for merging are on the exposed surface of a cut.  Once we find the optimal way of forming the central region, it generally doesn't play a part in the algorithm.
So let's start by building a collection of hyperslab-spaces, which can define not just a plain hyperslab, but any configuration of hyperslabs such as those with holes.  Each hyperslab-space records:

*

*The number of leaf hyperslabs contained within it (this is the number we are eventually going to try to minimize)

*The internal configuration of hyperslabs.

*A map of the surface of the hyperslab-space, which can be used for merging.

We then define a "merge" rule to turn two or more adjacent hyperslab-spaces into one:

*

*Hyperslab-spaces may only be combined into new hyperslab-spaces (so you need to combine enough pieces to create a new hyperslab, not some more exotic shape)

*Merges are done simply by comparing the surfaces.  If there are features with matching dimensionalities, they are merged (because it is trivial to show that, if the features match, it is always better to merge hyperslabs than not to)

Now this is enough to solve the problem with brute force.  The solution will be NP-complete for certain.  However, we can add an additional rule which will drop this cost dramatically: "One hyperslab-space is deemed 'better' than another if they cover the same space, and have exactly the same features on their surface.  In this case, the one with fewer hyperslabs inside it is the better choice."
Now the idea here is that, early on in the algorithm, you will have to keep track of all sorts of combinations, just in case they are the most useful.  However, as the merging algorithm makes things bigger and bigger, it will become less likely that internal details will be exposed on the surface of the hyperslab-space.  Consider
+===+===+===+---+---+---+---+
|   :   : A | X :   :   :   :
+---+---+---+---+---+---+---+
|   :   : B | Y :   :   :   :
+---+---+---+---+---+---+---+
|   :   :   |   :   :   :   :
+===+===+===+   +---+---+---+

Take a look at the left side box, which I have taken the liberty of marking in stronger lines.  When it comes to merging boxes with the rest of the world, the AB:XY surface is all that matters.  As such, there are only a handful of merge patterns which can occur at this surface

*

*No merges possible

*A:X allows merging, but B:Y does not

*B:Y allows merging, but A:X does not

*Both A:X and B:Y allow merging (two independent merges)

*We can merge a larger square, AB:XY

There are many ways to cover the 3x3 square (at least a few dozen).  However, we only need to remember the best way to achieve each of those merge processes.  Thus once we reach this point in the dynamic programming, we can forget about all of the other combinations that can occur, and only focus on the best way to achieve each set of surface features.
In fact, this sets up the problem for an easy greedy algorithm which explores whichever merges provide the best promise for decreasing the number of hyperslabs, always remembering the best way to achieve a given set of surface features.  When the algorithm is done merging, whatever that final hyperslab-space contains is the optimal layout.
I don't know if it is provable, but my gut instinct thinks that this will be an O(n^d) algorithm where d is the number of dimensions.  I think the worst case solution for this would be a collection of hyperslabs which, when put together, forms one big hyperslab.  In this case, I believe the algorithm will eventually work its way into the reverse of a k-tree algorithm.  Again, no proof is given... it's just my gut instinct.

A: You can try a constrained delaunay triangulation. It gives very few triangles.

A: Are you able to determine the equations for each line?
If so, maybe you can get the intersection (points) between those lines. Then if you take one axis, and start to look for a value which has more than two points (sharing this value) then you should "draw" a line. (At the beginning of the sweep there will be zero points, then two (your first pair) and when you find more than two points, you will be able to determine which points are of the first polygon and which are of the second one.
Eg, if you have those lines:
verticals (red):
x = 0, x = 2, x = 5
horizontals (yellow):
y = 0, y = 2, y = 3, y = 5

and you start to sweep through of X axis, you will get p1 and p2, (and we know to which line-equation they belong ) then you will get p3,p4,p5 and p6 !! So here you can check which of those points share the same line of p1 and p2. In this case p4 and p5. So your first new polygon is p1,p2,p4,p5.
Now we save the 'new' pair of points (p3, p6) and continue with the sweep until the next points. Here we have p7,p8,p9 and p10, looking for the points which share the line of the previous points (p3 and p6) and we get p7 and p10. Those are the points of your second polygon.
When we repeat the exercise for the Y axis, we will get two points (p3,p7) and then just three (p1,p2,p8) ! On this case we should use the farest point (p8) in the same line of the new discovered point.
As we are using lines equations and points 2 or more dimensions, the procedure should be very similar
ps, sorry for my english :S
I hope this helps :)


text:
Q: Eclipse: required '@Nonnull Type' prevents JUnit test My methods so far
I have a method with such a signature:
public static MyObject mapToOther(final MyInputType domain) {
  Objects.requireNonNull(domain, () -> "message if domain is null");
  // code …
  return new MyObject;
}

Also, in package-info.java, I have set:
@CheckReturnValue
@ParametersAreNonnullByDefault
package my.package.mappers;

import javax.annotation.CheckReturnValue;

I then created a JUnit test to check if a NullPointerException is being thrown if null is given as parameter.
@Test(expected = NullPointerException.class)
public void testNpe_null() {
  MyClass.mapToOther(null);
}

The problem
The test is just fine as I want to test for an NPE. But instead eclipse is complaining:
Null type mismatch: required '@Nonnull MyInputType' but the provided value is null

Well, the message is absolutely correct. But for this test it is a false positive because I am intentionally handing over null as a parameter value.
What I tried so far
Can I Eclispe make not report intentional null to nonnull methods? I know I can disable it completely using this dialog:
Window -> Preferences ->  Java -> Compiler -> Errors/Warnings -> Section 'Null Analysis'

But there is no option to exclude methods in src/test/java or having a @SuppressWarnings annotation configured.
Now my Java problem view is flooded with errors, most of which are in test classes. Is eclipse really that stupid? I'm using Oxygen.
Side note
Special Kudos to the answer with maven integration. ;-)
Also, as a side note: Spotbugs is complaining that I am not checking the return value in my junit test…

A: Either the parameter must not be null which means that the behavior of the method is undefined for null and does not have to be tested, or it can be null and the parameter is annotated with @Nullable.
However, with a null constant it is possible (although I would not recommend this hack):
private static final Object NULL = null;

@Test(expected = NullPointerException.class)
@SuppressWarnings("null")
public void testNpe_null() {
  MyClass.mapToOther((MyInputType) NULL);
}

Note, this only works if the constant NULL is not in a @ParametersAreNonnullByDefault package.


text:
Q: Convert a Windows-created ZIP to Linux (internal paths issue) I have a .zip created on a Windows machine (outside of my control). The zip file contains paths that I need to preserve when I unzip.
However, when I unzip, all files end up like:
unzip_dir/\window\path\separator\myfile.ext
I've tried both, with and without -j option.
My issue is that I need that path information under \window\path\separator\. I need that file structure to be created when I unzip.
I can mv the file and flip the \ to / easily enough in a script, but then there are errors that the destination path directories do not exist. My workaround for now is to mkdir -p the paths (after converting \ to /) and then cp the files to those paths.
But there are a lot of files, and these redundant mkdir -p statements for every file really slows things down.
Is there any more elegant way to convert a zip file with Windows paths to Linux paths?

A: I think something went wrong with the creation of the zip file, because when I create a zip file on Windows is has (portable) forward slashes:
zip.exe -r pip pip
updating: pip/ (244 bytes security) (stored 0%)
  adding: pip/pip.log (164 bytes security) (deflated 66%)

But now that you have the files with file names that contain "paths" with backslashes, you can run the following program in unzip_dir:
#! /usr/bin/env python

# already created directories, walk works topdown, so a child dir
# never creates a directory if there is a parent dir with a file.
made_dirs = set()

for root, dir_names, file_names in os.walk('.'):
    for file_name in file_names:
        if '\\' not in file_name:
            continue
        alt_file_name = file_name.replace('\\', '/')
        if alt_file_name.startswith('/'):
            alt_file_name = alt_file_name[1:]  # cut of starting dir separator
        alt_dir_name, alt_base_name = alt_file_name.rsplit('/', 1)
        print 'alt_dir', alt_dir_name
        full_dir_name = os.path.join(root, alt_dir_name)
        if full_dir_name not in made_dirs:
            os.makedirs(full_dir_name)  # only create if not done yet
            made_dirs.add(full_dir_name)
        os.rename(os.path.join(root, file_name),
                  os.path.join(root, alt_file_name))

This handles files in any directory under the directory from where the program is started. Given the problem that you describe, the unzip_dir probably doesn't have any subdirectories to start with, and the program could just walk over the files in the current directory only.

A: This is just an update of @anton's answer which includes fixes by @madmuffin (FileExistsError: [Errno 17] File exists and missing os module import), a fix for python 3 (SyntaxError: Missing parentheses in call to 'print') and a fix for the missing errno module import (NameError: name 'errno' is not defined).
#! /usr/bin/env python

import os
import errno

# already created directories, walk works topdown, so a child dir
# never creates a directory if there is a parent dir with a file.
made_dirs = set()

for root, dir_names, file_names in os.walk('.'):
    for file_name in file_names:
        if '\\' not in file_name:
            continue
        alt_file_name = file_name.replace('\\', '/')
        if alt_file_name.startswith('/'):
            alt_file_name = alt_file_name[1:]  # cut of starting dir separator
        alt_dir_name, alt_base_name = alt_file_name.rsplit('/', 1)
        print('alt_dir', alt_dir_name)
        full_dir_name = os.path.join(root, alt_dir_name)
        if full_dir_name not in made_dirs:
            try:
                os.makedirs(full_dir_name)
            except OSError as exc:
                if exc.errno == errno.EEXIST and os.path.isdir(full_dir_name):
                    # the pass already exists and is a folder, let's just ignore it
                    pass
                else:
                    raise
            made_dirs.add(full_dir_name)
        os.rename(os.path.join(root, file_name),
                  os.path.join(root, alt_file_name))

A: Had to make a few changes to @xn.'s answer for Mac. This worked for me:

*

*brew install gawk

*7z rn windows.zip $(7z l windows.zip | grep '\\' | gawk '{ print $6, gensub(/\\/, "/", "g", $6); }' | paste -s -)

A: Use 7z rn to rename the files within the archive so that they have a forward slash.  Then when you extract the archive, directories will be created.
To rename the files, list the paths of the files within the archive containing slashes, and generate a list of replacement strings that change the backslash to a slash using awk, for example.
7z rn windows.zip $(7z l windows.zip | grep '\\' | awk '{ print $6, gensub(/\\/, "/", "g", $6); }' | paste -s)

A: or, after unzipping use bash to fix the filenames:
for i in *; do new=${i//\\/\/}; newd=$(dirname "$new"); mkdir -p "$newd"; mv "$i" "$new"; done

A: I had the same problem yesterday:
I had downloaded a Windows driver containing paths with a backslash ("") as path separator. For installing Windows on my Linux machine I needed to unzip this file to a usb file using Linux, but Linux refused to do so due to invalid paths. The above solutions didn't work for me (I can't really tell why).
This is how I solved it.
Requirements:

*

*Python 3 (apt-get install python3)

Steps:

*

*Copy this code into an empty file in the zip's directory:

#!/usr/bin/python

import zipfile
import sys

def main(argv):
   if len(argv)!=1:
      filename=raw_input("Which file do you want to extract? Input here:\n")
   else:
      filename=argv[0]
   zipObj=zipfile.ZipFile(filename, 'r')
   for info in zipObj.infolist():
      info.filename=info.filename.replace('\\', '/')
      zipObj.extract(info)

if __name__ == "__main__":
   main(sys.argv[1:])

*Make the file executable.

*Run the file. Either specify a file on the command line or input the zip's filename. It will be extracted to the same folder, but path separators will be repaired.

A: I realize this script is probably similar to what OP used, but I thought I'd add it here for others who might need a bash solution instead of python.
I had the same problem with big zip file that I unzipped on a linux box. Everything dumped into one directory with backslashes in the file names. The script below

*

*loops through all of those files

*Separates the directory path from the file name

*Flips backslashes into forward slashes

*tests to see if the directory path exists, and creates it if it doesn't

*moves the file into the correct directory

The first argument is the directory where the files exist. If you name this script "correct-paths.sh" you can call it with
$ ./correct-paths.sh dir-with-backslash-files

Here's the content of the bash script
#!/bin/bash

if [[ ! -d "$1" ]]
then
    echo "The argument must be a directory where the files live."
    echo "'$1' is not a directory'"
    exit 0
fi

cd $1

for fullpath in *
do
    filename=$(echo $fullpath | awk -F'\\' '{ print $NF }')
    dirpath=$(echo ${fullpath%\\*} | sed 's/\\/\//g')
    if [[ ! -d "$dirpath" ]]
    then
        mkdir -p "$dirpath"
    fi

    mv "$fullpath" "$dirpath/$filename"
done


text:
Q: Finding the Jacobson Radical of a subring of a matrix ring and a quotient of a polynomial ring Find the Jacobson Radical of:
$B_1 = \left\{\begin{bmatrix}
a & 0 & 0 \\
b & c & d \\
0 & 0 & e \\
\end{bmatrix}\,\,\middle|\,\,a,b,c,d,e\in k\right\}
⊆ M_3(k)$
$B_2 = \Bbbk[x]/(x^3 − 2x^2 − 4x + 8)$
I know the jacobson radical is the intersection of left ideals but i don't know how to find these.
For B1 I think I may be able to make use of a, c, e being in the positions of the identity matrix. and for B2 I could factorise the polynomial, but beyond this I am unsure

A: For B1:

I think I may be able to make use of a, c, e being in the positions of the identity matrix.

I have no idea what that is supposed to mean.
But you can use exactly the same approach mentioned in this similar question and this similar question and this similar question.
If $k$ is supposed to be a field, the radical will wind up being $\left\{\begin{bmatrix}0&0&0\\b&0&d\\0&0&0\end{bmatrix}\,\,\middle|\,\,b,d\in k\right\}$
for B2

for B2 I could factorise the polynomial, but beyond this I am unsure

Yeah, you should do that. $k[x]$ is a principal ideal domain, so its maximal ideals are easily understood.
The only question is how it factors over $k$. Fortunately for you, it has three "integer" roots. Unfortunately, that's still not enough information to get a single answer.
You'll have to ask whoever gave you the problem if $k$ is supposed to have characteristic $0$ or what. It could have two distinct maximal ideals, or just one maximal ideal.
Still, after you factor it, you can easily see the maximal ideals that contain the polynomial, and then easily compute their intersection.
These are all the hints I can give without knowing what specifically you are stuck with.  You might consider editing that information into your question to improve its quality.


text:
Q: subfolder and html page name is the same and nor working I have a webpage, which has got a html page called "blog.html" and a subfolder which is called "blog" and have some other html page inside. I just removed .html with htaccess.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

Now, when somebody click on the "blog" menu, the following happened:
You don't have permission to access /blog/.html on this server.
I wonder how can i fix this, i would like to have a page with working urls like this:
mydomain.com
mydomain.com/blog
mydomain.com/blog/first_post

A: Change your rule to this:
DirectorySlash Off
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/$1 -d
RewriteRule ^(.*?[^/])$ %{REQUEST_URI}/ [L,R=302]

RewriteCond %{DOCUMENT_ROOT}/$1\.html -f [NC]
RewriteRule ^(.+?)/?$ $1.html [L]

And test it in a different browser.


text:
Q: My TFS build definition setup cannot get past Get Sources error 'directory already exists' My TFS 2018 build fails at GET SOURCES with this error:

*

*tf vc get /version:192 /recursive /overwrite
C:\Users\Administrator\agent_work\2\s /loginType:OAuth /login:.,
/noprompt C:\Users\Administrator\agent_work\2: Warning s - Unable to
get because a directory already exists. Exit code 1 returned from
process: file name 'tf', arguments 'vc get /version:192 /recursive
/overwrite C:\Users\Administrator\agent_work\2\s /loginType:OAuth
/login:., /noprompt'.

My steps
I have a fresh installation of TFS 2018.
I created an agent pool (default)
I created the agent
The VSTS service is running
I created a simple Visual Studio 2017 C# winforms project
I added the solution to TFS
I mapped the workspace
In Get sources...
I set CLEAN to true ... and it is set up for Clean Sources. My server path is directly to the solution file within the repository.
But the above error keeps happening.
Any ideas? Help!

A: I had this problem and it turned out it was because I'd specified the solution file in the "server path" box rather than the source directory.
Initially I had the server path set to $/Modelling/ConsoleApp1/ConsoleApp1.sln and got the error above, then I changed it to $/Modelling/ConsoleApp1 and the problem went away.

A: I ended up deleting the Agent folder structure, deleted the agent as well. And in TFS deleted the build definition.  I opted to start from scratch, and after reconstructing the new AGENT and creating the new Repository with Build Definitions, it worked.  The error stopped.

A: Another fix is if your "Server Path" is a single file, then the "Local Path" should be that file's name with the extension instead of blank. $/MyPath/MySolution.sln -> MySolution.sln


text: Q: Generally what are the ports that need to be open and remain on a windows server? Normally under windows open and public ports there are nearly 50 to 60 ports. Most of these range between 1 - 1023. Can all those ports keep as it is or should I close them except RDP.


text:
Q: How to choose server for production release of my Django application? My company is at the very end of development process of some (awesome:)) web application. This app will be available as a online service for (hopefully) some significant number of users. This is our biggest django release so far and as we are preparing to release some question about deployment have to be answered.
Q1: how to determine required server parameters for predicted X number of users/Y hits per minute or other factor?
Q2: what hosting solution (shared/vps/dedicated) is worth considering?
Q3: what optimizations can be done at a first place?
I know that this is very subjective and dependent of size of a site, code quality and other factors but I'm very interested in your experiences with django (and not only django) deployment. Any hints, links, advices are kindly welcome. Thanks in advance.

A: What hosting solution you want to have depends also on how much you want to take of your server yourself (from upgrades etc to backup...), and you should decide if you want to have the responsibility or leave it to someone else.
I think you can only really determine the necessary requirements and bottlenecks in your applications through testing with the estimated load! Try to simulate as many requests.... as you expect - think about caching (where memcached is the best option you have)! If you try to cache things one great tool is the django debug toolbar (http://github.com/robhudson/django-debug-toolbar) which can show you also much about how many database hits you have (dont take the times it shows for that for granted, but analyse them and keep an eye on the number of hits) and eg. how many templates are rendered....
If your system grows, you can first of all think about serving your static media files from another location! Coming to the web server I have made great experiences using lighttpd instead of the fat apache, but I guess you have to evaluate that for yourself!
Also take in consideration what database backend to use, in shared envionments there's in most cases a bigger load on the mysql than on the postgres servers, but also evaluate what works best for you!

A: You can get some guesses here, but to get a halfway reasonable performance estimate you have to measure the performance of your application yourself. You should then be able to roughly extrapolate the performance on different hardware.
Most of the time the bottleneck is the database, you should get enough RAM to keep it in memory if possible.
"Web application" can encompass so many different things, we can really do no more than guess here.
As for optimization, if it fits to your needs implement some caching (e.g. with memchached), that can give you huge speed improvements.


text:
Q: Jenkins user gets changed based on job name,WHY? I have installed Jenkins on Linux RHEL7 and i did below changes to run all my Jenkins job with a root user rather than Jenkins user.
The changes I made:

*

*Inside file /etc/sysconfig/jenkins:
JENKINS_USER="root" (default it used to be "jenkins")

*Changed the ownership of files using below commands:
sudo chown -R root:root /var/lib/jenkins
sudo chown -R root:root /var/cache/jenkins
sudo chown -R root:root /var/log/jenkins
Now when I am creating a job named "snjiii", it runs correctly i.e., using root user:
Console Output
Started by user FSQA ADMIN
Running as SYSTEM
Building on master in workspace /var/lib/jenkins/workspace/snjiii
[snjiii] $ /bin/sh -xe /tmp/jenkins8170584152885597665.sh
+ whoami
root
Finished: SUCCESS

But when I am creating a different job named as "snjiii_newjob_l1_rhl7", it's running as jenkins user:
Console Output
Started by user FSQA ADMIN
Running as SYSTEM
Building remotely on Slave_1_14 (Redhat_linux) in workspace /var/lib/jenkins/workspace/snjiii_newjob_l1_rhl7
[snjiii_newjob_l1_rhl7] $ /bin/sh -xe /tmp/jenkins2597327522922634209.sh
+ whoami
jenkins
Finished: SUCCESS

I need to create job and run it using root user irrespective of naming convention. How to do it???

A: Even though I was running the job on my master, I created a master-slave configuration for the same wherein I created a node with master credentials and used it as my slave i.e. I restricted my project to run on the slave machine which is my master itself and henceforth it uses ssh credentials to communicate, it resolves my issue.


text:
Q: c# Calling method using P/Invoke causing AccessViolation Exception I interfacing with a device using P/Invoke. But I've come stuck at calling the following method:
BOOL __stdcall voGetFirmwareVersion(IN OUT LPTSTR lpVersion,  IN OUT DWORD *dwSize);

In my wrapper I have called the method like so:
[DllImport(DLL_LOCATION, CharSet = CharSet.Ansi)]
private static extern Boolean voGetFirmwareVersion(string s, uint d);

I have attempted to change the inputs to Out/Ref and tried adding the [In,Out] attributes but I am constantly getting a AccessViolation Exception.  Can anyone point me in the right direction? I've been at this for a couple of hours now and google hasn't been able to put me straight

A: *

*dwSize is passed by address, so it should be a ref parameter.

*BOOL return type must be marshaled if any nonzero value may come as a true value

*I am not sure if you really want to use Ansi charset. Try Auto or Unicode.

*LPStr and StdCall are not a must, they are the default settings.

So try this:
[DllImport(DLL_LOCATION, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool voGetFirmwareVersion([MarshalAs(UnmanagedType.LPTStr)] string s, ref uint d);


text:
Q: Rhomobile search question I try to make rhomobile search in Fixed DB.
But it returns ALL entries in DB instead of the ones with given QID
    <%=@questions.id%>
<%   @antworts = Antwort.find(:conditions=>{'qid'=>@questions.id})%>
   <% @antworts.each do |antwort| %>

         <%= antwort.antwort %>

   <% end %>

Any idea why?

A: You need to pass :first or :all in the first argument:
Antwort.find(:all, :conditions=>{'qid'=>@questions.id})

Or change the method to find_all:
Antwort.find_all(:conditions=>{'qid'=>@questions.id})


text:
Q: Pressure $p$ in the Bernoulli equation I know the Bernoulli equation that states that the energy along a streamline is constant:
$$ \frac{v^{2}}{2}+gh+\frac{p}{\rho}=C $$
However I can't seem to figure out what exactly $p$ is in this equation. In every book I look and also on Wikipedia it only says "$p$ is the (static) pressure". I always considered $p$ to be the internal pressure of the liquid, i.e. the pressure exerted by the fluid on its surroundings (that includes covering fluid). But this raises a problem that I wasn't sure of how to solve.

Lets assume that the flow in the picture is an incompressible flow, like water. When the water flows from the wide to the narrow part of the tube, the speed $v$ increases, lowering the pressure $p$ (as $gh$ and $\rho$ remain constant). As this is an incompressible fluid, the volume cannot change. But if the pressure is lowered and the volume does not change, doesn't that mean that the temperature is lowered too? This just seems weird to me.
What goes wrong in this thought process?

A: Bernouilli is all about conservation of energy. The drop in pressure is necessary so that work can be done on the incompressible fluid - because when it flows faster, it has more kinetic energy and that had to come from somewhere.
There is no change in temperature. This is not an ideal gas - you said yourself it is an incompressible fluid. So $PV=nRT$ does not apply.

A: If we think of the forces $(F=PA)$ acting on the fluid as it flows along the pressure gradient the problem becomes clearer.
An incompressible fluid flowing from a region of higher pressure to a region of lower pressure feels a net force in the direction of the pressure gradient. This net force causes the fluid to accelerate (bulk motion).
Thus there is an increase in kinetic energy. On the assumption that the water is incompressible there will not be a change in temperature.


text:
Q: Stuck in developing an interactive USSD app Halo great people?
I am using the below code to get, dismiss and toast a USSD response message, However, I would like to interact with the ussd response containing menus or options,
e.g, reply with one in the USSD's edit text and click the send button.
How can I go about this. if you have some reference code, examples, or you can point me in the right direction I'll be very grateful.
Any help is appreciated in advance.
Thanks, Keep safe.
class USSDService : AccessibilityService() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onAccessibilityEvent(event: AccessibilityEvent?) {
    val ussdResponse = event!!.text.toString().replace("[", "").replace("]", "")
    if( TextUtils.isEmpty(ussdResponse) ) return;
    if (event.className == "android.app.AlertDialog") {
        performGlobalAction(GLOBAL_ACTION_BACK)
        val intent = Intent("com.times.ussd.action.REFRESH")
        intent.putExtra("message", ussdResponse)

        val nodeInfo = event.source
        val list: List<AccessibilityNodeInfo> = nodeInfo.findAccessibilityNodeInfosByText("Send")
        for (node in list) {

            if (ussdResponse.contains("Select User")){
                /** I would like to perform the setting of text and replying back here... */
            }
        }

        Toast.makeText(this, ussdResponse, Toast.LENGTH_LONG).show()
        //
    }
}

override fun onInterrupt() {
    TODO("Not yet implemented")
}

override fun onServiceConnected() {
    super.onServiceConnected()
    val info = AccessibilityServiceInfo()
    info.flags = AccessibilityServiceInfo.DEFAULT
    info.packageNames = arrayOf("com.android.phone")
    info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
    serviceInfo = info
}

}
/** I found the Following code; */
val inputNode = source.findFocus(AccessibilityNodeInfo.FOCUS_INPUT)
val arguments = Bundle()

arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "2")
inputNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments)
for (node in list) {
      node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
}

Supposed to reply with 6 but returns a null.
There's an exception the input is null.
Anyone seeing where or what I am doin wrong!

A: I noticed that this is NOT supported for Android below API 5, but runs fine in API 6 and above.


text:
Q: Reshape Pandas Dataframe with multiple column groups I currently have a wide dataframe that looks like this:
Index ID1 ID2 Foc_A Foc_B Foc_C Sat_A Sat_B Sat_C
   0   r  1   10    15    17    100   105   107
   1   r  2   20    25    27    110   115   117
   2   s  1   30    35    37    120   125   127
   3   s  2   40    45    47    130   135   137

Each entry has multiple identifier columns (ID1 and ID2). I then have two separate categories of measurements (Foc and Sat) each of which contains multiple identifiers (A, B, C)(the category identifiers are shared between categories). I'm eventually needing to plot it in a facet_grid with x and y as each category of measurement and separated by category identifier, so I'm trying to reshape it so that it looks like this:
Index ID1 ID2 Ch  Foc  Sat
   0   r  1   A   10   100
   1   r  1   B   15    105
   2   r  1   C   17    107
   3   r  2   A   20    110
   4   r  2   B   25    115
   5   r  2   C   27    117
   6   s  1   A   30    120
   7   s  1   B   35    125
   8   s  1   C   37    127

I've been trying .melt, .pivot, and .stack but not understanding what I'm doing well enough to make headway.

A: You are thinking in the right way. You can do:
# melt the dataframe
d1 = df.set_index(['Index', 'ID1', 'ID2']).stack().reset_index()

# create separate column
d1[['flag', 'Ch']] = d1['level_3'].str.split('_', expand=True)
d1 = d1.drop('level_3', 1)
d1 = d1.rename(columns = {0: 'Foc'})

# expand the dataframe to wide
d2 = pd.pivot_table(d1, index=['Index', 'ID1', 'ID2', 'Ch'], columns=['flag']).reset_index()

# fix column names
d2.columns = ['Index', 'ID1', 'ID2', 'Ch', 'Foc', 'Sat']

print(d2.head())

   Index ID1  ID2 Ch  Foc  Sat
0      0   r    1  A   10  100
1      0   r    1  B   15  105
2      0   r    1  C   17  107
3      1   r    2  A   20  110
4      1   r    2  B   25  115

A: I'd set ID columns to the index, split and expand the columns on the '_' character, then stack the dataframe:
from io import StringIO
import pandas

datafile = StringIO("""\
Index ID1 ID2 Foc_A Foc_B Foc_C Sat_A Sat_B Sat_C
   0   r  1   10    15    17    100   105   107
   1   r  2   20    25    27    110   115   117
   2   s  1   30    35    37    120   125   127
   3   s  2   40    45    47    130   135   137
""")

(
    pandas.read_csv(datafile, sep='\s+')
        .set_index(['ID1', 'ID2'])
        .drop(columns='Index')
        .pipe(lambda df:
             df.set_axis(
                 df.columns.str.split('_', expand=True),
                 axis="columns"
            )
        )
        .rename_axis([None, 'Ch'], axis='columns')
        .stack(level='Ch')
        .reset_index()
)

And that give me:
   ID1  ID2 Ch  Foc  Sat
0    r    1  A   10  100
1    r    1  B   15  105
2    r    1  C   17  107
3    r    2  A   20  110
4    r    2  B   25  115
5    r    2  C   27  117
6    s    1  A   30  120
7    s    1  B   35  125
8    s    1  C   37  127
9    s    2  A   40  130
10   s    2  B   45  135
11   s    2  C   47  137

A: Let us do wide_to_long
df = pd.wide_to_long(df,['Foc','Sat'],i=['ID1','ID2'],j='Ch',sep='_',suffix='\w+').reset_index()
Out[168]:
   ID1  ID2 Ch  Foc  Sat
0    r    1  A   10  100
1    r    1  B   15  105
2    r    1  C   17  107
3    r    2  A   20  110
4    r    2  B   25  115
5    r    2  C   27  117
6    s    1  A   30  120
7    s    1  B   35  125
8    s    1  C   37  127
9    s    2  A   40  130
10   s    2  B   45  135
11   s    2  C   47  137

A: you could also achieve this with .melt, .groupby and np.where:
df = pd.melt(df, id_vars=['ID1','ID2','Foc_A', 'Foc_B', 'Foc_C'], var_name='Ch', value_name='Sat') \
    .groupby(['ID1','ID2','Ch']).agg({'Foc_A':'max','Foc_B':'max', 'Foc_C':'max','Sat':'max'}).reset_index()
df['Foc'] = np.where((df['Ch'] == 'Sat_A'), df['Foc_A'], '')
df['Foc'] = np.where((df['Ch'] == 'Sat_B'), df['Foc_B'], df['Foc'])
df['Foc'] = np.where((df['Ch'] == 'Sat_C'), df['Foc_C'], df['Foc'])
df['Ch'] = df['Ch'].str.replace('Sat_', '')
df = df.drop(['Foc_A', 'Foc_B', 'Foc_C'], axis=1)
df

output:
    ID1 ID2 Ch      Sat Foc
0   r   1   A       100 10
1   r   1   B       105 15
2   r   1   C       107 17
3   r   2   A       110 20
4   r   2   B       115 25
5   r   2   C       117 27
6   s   1   A       120 30
7   s   1   B       125 35
8   s   1   C       127 37
9   s   2   A       130 40
10  s   2   B       135 45
11  s   2   C       137 47

A: Creating a multi_index then using stack
df = df.set_index(['ID1','ID2'])

df.columns = df.columns.str.split('_',expand=True)

df1 = df.stack(1).reset_index().rename(columns={'level_2' : 'Ch'})

   ID1  ID2 Ch  Foc  Sat
0    r    1  A   10  100
1    r    1  B   15  105
2    r    1  C   17  107
3    r    2  A   20  110
4    r    2  B   25  115
5    r    2  C   27  117
6    s    1  A   30  120
7    s    1  B   35  125
8    s    1  C   37  127
9    s    2  A   40  130
10   s    2  B   45  135
11   s    2  C   47  137


text:
Q: how to create image gallery with horizontal scroll How can I make an image gallery with horizontal scroll in android studio in which images can be displayed one image at the screen and with buttons on the right and the left for moving to other images

A: You can use ViewPager instead of HorizontalScrollView,
Please follow this tutorial

A: You may also use horizontal recycleview. Here's the code:
fragment/activity layout:
<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

       ...

    <android.support.v7.widget.RecyclerView
        android:id="@+id/horizontal_recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:horizontalSpacing="10dp"
        android:isScrollContainer="false"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp"
        />
            ...

</LinearLayout>

item:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
    android:id="@+id/horizontal_item_view_image"
    android:layout_marginRight="10dp"
    android:layout_width="109dp"
    android:layout_height="109dp" />

</LinearLayout>

adapter:
public class HorizontalPhotosAdapter extends RecyclerView.Adapter<HorizontalPhotosAdapter.MyViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Bitmap> bitmapList;

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private ImageView riv;

        public MyViewHolder(View view) {
            super(view);

            riv = (ImageView) view.findViewById(R.id.horizontal_item_view_image);

        }
    }

    public HorizontalPhotosAdapter(Context context, ArrayList<Bitmap> bitmapList, String[] imageUrls) {
        this.context = context;
        this.bitmapList = bitmapList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.horizontal_item_view, parent, false);

        if (itemView.getLayoutParams ().width == RecyclerView.LayoutParams.MATCH_PARENT)
            itemView.getLayoutParams ().width = RecyclerView.LayoutParams.WRAP_CONTENT;

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        holder.riv.setImageBitmap(bitmapList.get(position));

    }

    @Override
    public int getItemCount() {
        return bitmapList.size();
    }
}

implementation in fragment/activity:
            horizontalAdapter=new HorizontalPhotosAdapter(getContext(), bitmapList);
            horizontal_recycler_view.setAdapter(horizontalAdapter);
            horizontalAdapter.notifyDataSetChanged();

            LinearLayoutManager horizontalLayoutManagaer = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
            horizontal_recycler_view.setLayoutManager(horizontalLayoutManagaer);
            horizontal_recycler_view.setAdapter(horizontalAdapter);


text:
Q: NetCoreApp System.codedom I'm creating a new .NET Core application and would like to use System.CodeDom (and .Compiler) as reference. I require the classes: CSharpCodeProvider, CodeMemberProperty, ... However i'm not finding a package via nuget where these types are available. Anybody who knows in which package I can find this for .NET core?

A: I found this one CoreCompat.System.CodeDOM which is resolving some of my issues. This is still in beta, so if there is an RTM available this can be added here.

A: CodeDOM is not currently available on .Net Core and it seems it's not planned to be included anytime soon.
Your best choice is to use Roslyn libraries instead.


text:
Q: How can black holes possibly drive accelerating expansion of the universe? (Potentially too broad, but all my questions are related to the paper in question.)
Recently there was an article published in Astrophysical Journal Letters that claims black holes "contribute cosmologically as vacuum energy". The article was covered in the popular media, e.g. here and here.
I'm trying to understand this result. As far as I can tell from the paper, what is actually argued is that black holes gain mass at a rate proportional to $a^k$, where $a$ is the scale factor of cosmology and $k$ is some constant. The paper claims that $k \sim 3$. Since in cosmology all matter dilutes as $a^{-3}$ as the universe expands, if black holes gain mass at $a^3$, then the two factors cancel out and there is an approximately constant energy density that looks like dark energy. This is in section 3.1 of the paper:

Equation (1) implies that a population of $k \sim 3$ BHs will gain mass proportional to $a^3$. Within an RW [Robertson-Walker] cosmology, however, all objects dilute in number density proportional to $a^{−3}$. When accretion becomes subdominant to growth by cosmological coupling, this population of BHs will contribute in aggregate as a nearly cosmologically constant energy density. From conservation of stress-energy, this is only possible if the BHs also contribute cosmological pressure equal to the negative of their energy density, making $k \sim 3$ BHs a cosmological dark energy species.

However, I don't see why this constant energy density would mimic dark energy. Dark energy drives expansion of the universe, while black holes would presumably act as (gravitationally attractive) matter. Why wouldn't lots of very massive black holes slow down expansion?
Furthermore:

*

*Given that black holes of all sizes can at most be 26.8% of the universe's energy content, how can they possibly account for all of dark energy, which has 68.3% of the universe's energy content?

*If there are black holes of several million solar masses in the galaxy outskirts (necessary to account for dark matter), why wouldn't that be immediately noticeable, e.g. by capturing stars into orbit?

A: There is a nice rebuttal to the hype written up on Ask Ethan.

This is what I call a swing. The alternative explanation....is that this method is 100% unsound. It's possible that $k = 0$, that there is no coupling, and that what's actually happening is that these black holes are growing by purely astrophysical processes: the infall and accretion of matter over time, as well as from mergers and acts of galactic cannibalism.

That said, it is worth looking into further, it is just highly unlikely that there turns out to be a connection with the interior of black holes and cosmic expansion.
Not least because when black holes cross the cosmic event horizon, they take their entropy (and dark energy in this idea) with them...(noting there is also a currently-minority view that questions expansion, and thus the existence of a cosmic event horizon).


text:
Q: Skype can't connect via built-in 4G mobile broadband modem When I'm using my laptops built-in mobile broadband modem, skype cannot connect.
Additional symptom: After signing out of skype, I cannot sign in again.
(Sign in works fine on wifi)
Everything else (internet connection from browser, dropbox, etc.) connects without problems.
Details:

*

*Ubuntu 14.04

*Thinkpad T440

*Modem: Sierra Wireless EM7345 4G LTE

When using wifi, skype connects fine.
When using the same sim-card, inserted into a mobile wifi box like huawei E5776, skype can also connect without problems. (This is via wifi to the huawei box, and via gsm from there).
This indicates:
a) that it is not my ISP blocking anything. (also, according to their technical support they are not blocking).
b) that the problem is related to the use of the modem connection from ubuntu. It could be a problem with the modem (firmware?), or with ubuntu/modemmanager/networkmanager.
I suspect this has something to do with ubuntu and/or skype treating the wireless broadband connection differently from a wifi connection. Perhaps it has something to do with dialout, with 'metered connection', etc.
I checked the permissions on the modem device, only root had access to the device. The device did not have the dialout group, as described in this bug: https://bugs.launchpad.net/ubuntu/+source/udev/+bug/1032865
I added the device to the dialout group as described in the bug. After the fix:
crw-rw----  1 root dialout   180,   0 Aug 26 11:09 cdc-wdm0
I also added my own user (the user running skype) to the dialout group, as described here: Changing permissions on serial port
BUT this did not solve the problem.
Any hints?

A: I found a blog that say that the stock drivers on your modem (Sierra Wireless EM7345 4G LTE) has some bugs in it, please read this link.
Also, did you try connecting Skype using a HTTP Proxy? Check the following link and give it a try...

A: I also use the Sierra Wireless, the only time I had this issue was when bandwidth was poor over 4G and it was actually more like 2G. Have you run a speed test when this happens? Also try disabling all other adapters then connect via 4G Network.

A: A workaround for getting acces to using skype when on my mobile broadband connection:
Use the skype web client, https://web.skype.com/. Unfortunately video / voice calls do not work (yet) on linux - only text based chat.

A: With the latest kernel update Linux X1 3.16.0-55-generic #74~14.04.1-Ubuntu Skype is now working on 3G. Lenovo X1 Carbon 3rd gen.

A: change below settings in 4G modom
tools -> Options -> select connection type NDIS
and click OK, now click connect.
now skype will work
this is working in AIRTEL 4G dongle


text:
Q: Как получить изображение с веб-камеры? Как мне в bash получить изображение с веб-камеры ноутбука? Мне нужно написать скрипт, который получал бы изображение с веб-камеры и залиал его на ФТП с определённым именем.
A: fswebcam -r 640x480 --jpeg 85  -F 3 -S 2 test.jpg  &&  lftp -u user,password  -e  'put ./test.jpg; bye' host.with.ftp.comНемножко поясню. Утилита понятно, скачал из репов поставил, вопросов нет. Параметры -F и -S я ставил потому что у меня странная камера и нормально инициализируется только на 3 фрэйме, поэтому я ловлю 3 (-F), а первые два пропускаю (-S), может вам и не надо их ставить, далее имя файла. Ну а дальше ftp там все тривиально.


text:
Q: How to re-render Formik values after updated it - React Native? I have a screen for update previously data "name, email, age, etc". at the first time I call a function that gets data from server name as getProfileData()
after user write the new data I send a POST request for that "update Profile"
and it's a success, but after that, I want to re-render this form with new data, So i call the getProfileData() function to get new data but it's not working to re-render Input Values!
it's just still with previous data
I also try with componentDidUpdate() but sadly not re-render :)
So how can i solve it?
Code
getProfileData = async () => {
    let USER_TOKEN =
      '....';
    let AuthStr = `Bearer ${USER_TOKEN}`;
    let response = await API.get('/profile', {
      headers: {Authorization: AuthStr},
    });
    let {
      data: {data},
    } = response;
    let password = '';
    let password_confirmation = '';
    let {name, email, avatar, age, gender, country_id} = data;
    let initialValues = [];
    initialValues.push({
      name,
      password,
      password_confirmation,
      email,
      avatar,
      age,
      gender,
      country_id,
    });
    this.setState({initialValues: initialValues, loading: false}, () =>
      reactotron.log(this.state.initialValues[0]),
    );
  };

  updateProfile = async value => {
    let USER_TOKEN =
      '....';
    let AuthStr = `Bearer ${USER_TOKEN}`;
    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    let response = await API.post('/update_profile', value, {
      headers: headers,
    });
    let {
      data: {data},
    } = response;
    alert(data);
    this.getProfileData(); // called
  };

 componentDidMount() {
    this.getCountryList();
    this.getProfileData();
  }
  componentDidUpdate(prevProps, prevState) {
    if (prevState.initialValues !== this.state.initialValues) {
      console.log('componentDidUpdate', this.state.initialValues);
      this.setState({initialValues: this.state.initialValues});
    }
  }

UI
<Formik
                  validationSchema={formSchema}
                  initialValues={this.state.initialValues[0]}
                  onSubmit={(values, actions) => {
                    this.updateProfile(values);
                    reactotron.log(values), actions.resetForm();
                  }}>
                  {({
                    handleChange,
                    handleBlur,
                    touched,
                    errors,
                    handleSubmit,
                    values,
                    setFieldValue,
                  }) => (
                    <View>
                      <Item style={styles.item} floatingLabel>
                        <Label style={styles.formLabel}>name</Label>
                        <Input
                          style={styles.value}
                          rounded
                          onChangeText={handleChange('name')}
                          onBlur={handleBlur('name')}
                          value={values.name}
                        />
                      </Item>
                      <Text style={styles.errorText}>
                        {touched.name && errors.name}
                      </Text>
                 </View>
             )}
 </Formik>

A: You can use enablereinitialize prop on formik.
<Formik
  enableReinitialize
  ...
/>

By default it is false, but if its true, what will happen is if you initialValues change, it will rerender.
So you can store your initialValues in state.
for example
state = {
  initialValues: { name: '', ...}
}

and when you update the profile data just update that state.
setState({initialValues: newInitialValues })

https://jaredpalmer.com/formik/docs/api/formik#enablereinitialize-boolean


text:
Q: How to estimate bug fixes? How can you actually determine the size of fixing something which is broken in an unknown way?  I tell people in my classes I only know two sizes for defect fixes: 1) Trivial because I already know what's broken and how to fix it, or 2) Infinite because I have no idea what's broken or how to fix it!  If those are the only two sizes available to us how can we possibly estimate them?
I got that from a blog by Bob Hartman but that's exactly my questions. Sometimes seemingly trivial bugs are hugely complicated and sometimes big issues get fixed by changing one tiny character somewhere. Then how can we ever know how long it will take without actually trying to fix it while estimating? And if I am going to fix it while estimating.. why am I estimating?

A: You cannot determine the size, but you can estimate it. An estimate gives some information to your manager, and therefore it delivers some value. This is better than no value, therefore you should take the trouble to make an estimation even if it won't be exact.
Why is this so? Because a business runs on repetition. Sure, telling your manager that making a fix has a 50% chance of taking less than a day is not hard information. But your manager has more than one report, an there is more than one day in a project. If your estimates are good, in the long run half of these issues will take less than a day, and this is a valuable thing to know when budgeting, planning, etc.
And how do you estimate? Well, you compare to the closest previous situations, and you guess. That's pretty much all there's to it. Obviously it takes some expertise to judge which situations are similar, and you'll sometimes get it wrong. That is not the point. The point is that no matter how inscrutable a problem seems to you, you, as the developer, have a better chance of making this judgement call than your higher-ups, therefore you are the logical person to make that call.
This is no different from an MBA hiring a programmer to program for him because he's better at programming: you get paid to perform a valuable service - in this case, reducing planning uncertainty for the project you're working on. It doesn't matter that you can't reduce it to zero - in business you have to think in marginal values, not absolute ones.

A: You estimate your patience with the problem.
Sometimes you have no idea what is causing the problem.  No idea what it will take to fix it.  How can you possibly predict how long it will take?
You predict how long before you'd give up and work on something else.  Now you only need to understand the problem, not the solution.
If you don't yet understand the problem, the classic answer to this question is: "I'll get back to you."


text:
Q: Weird adware source code in every website I've got a weird script popping up on every website I go on. What makes it even weirder is that it does absolutely nothing. I didn't notice anything until I saw this kind of stuff:

I've tried making it bigger and visible but the iframe is transparent. There is nothing there. How can I get rid of this? I am not running any suspicious extensions and I've run Chrome Suspicious Software Remover, or whatever it's called. I've run multiple scans with my Antivirus AND MalwareBytes. Still nothing.
Is this dangerous? What does it do? How do I get rid of it? Thanks in advance.
This issue exists in both IE and Chrome
EDIT: It is gone! It was a program called "SuperFish Inc Visual Discovery" installed. I have deleted it and uninstalled it completely and now my browsers are best-deals-products free!


text:
Q: Why might paramiko connect more slowly than openssh client? I'm using paramiko to run some commands over ssh.  I notice that paramiko takes 2-3 seconds to open a connection, while the command line ssh client is almost instant.
Using some prints, I've found that the sticking point is Transport.auth_publickey (it is using a discovered ~/.ssh/id_dsa).  That's the same authentication method that command line ssh is using, so why might paramiko be running more slowly?
The code I'm using to connect is pretty simply:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('myhostname', **{'username': 'root'})

A: This is most likely because the modular exponentiation operations needed both for the Diffie-Hellman key-exchange and the RSA public key authentication are orders of magnitude slower in a Python bytecode interpreter (as in pure Python Paramiko) compared to heavily optimized compiled native binary that OpenSSH uses.


text:
Q: How do I position a subview within a principal view? I created a class in my project and this class is a subclass of another class; I want place this subview in the principal view, I reduced x and y to make it smaller, but it always appears at the top left, how can I set it in other position?

A: Would be easier to answer if you posted some code. Most likely, you need to modify the frame property of your view. frame is a rectangle (CGRect) that determines the position and size of your view in the coordinate system of its superview. The bounds property is similar but expresses origin and size in the coord system of itself (e.g. origin is 0,0).
For other layout tips, look at the autoresizingMask and contentMode properties of views. In fact, read up on views in general. The Apple docs are good and lots of stuff here about them.


text:
Q: How can adjust images overlay size relative to img size I want to set a overlay on my images and when I hover the image an overlay appears on the image and is the same size as image. When I resize the window the overlay should resize automatically.
I have tried some JS code but does not work. It's always set width/height to 0px.
Please let me know how I can fix this.

var portImg = document.getElementById("portimg");
var overlay = document.getElementsByClassName("overlay");
var overlayh = overlay.style.height = portImg.clientHeight;
var overlayw = overlay.style.width = portImg.clientWidth;
/*
tried this 1 too

clientHeight + "px";
clientWidth + "px";
*/
.col-sm-6 {
  position: relative;
}

.img-container {
  width=100%
}

.img-container img {
  width=100%
}

.overlay {
  position: absolute;
  margin-top: 20px;
  text-align: center;
}

.overlay:hover {
  transform: rotate(0deg);
  opacity: .95;
}

A: You can set an overlay with CSS alone using either your own element or a pseudo element. Use absolute positioning on the overlay with relative positioning on the parent, and the overlay will scale automatically with the parent.

.img-container {
  position: relative;
}

.img-container img {
  display: block;
  width: 100%;
}

.overlay {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  text-align: center;
  opacity: 0;
  transition: opacity .25s;
  background: black;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1em;
}

.img-container:hover .overlay {
  opacity: .5;
}

overlay

If you still want to have the overlay's width and height be controlled via javascript, I would create a function that matches the heights and call that on page load as well as on the window's resize event.

.img-container {
  position: relative;
}

.img-container img {
  display: block;
  width: 100%;
}

.overlay {
  position: absolute;
  top: 0; left: 0;
  /* right: 0; bottom: 0; */
  text-align: center;
  opacity: 0;
  transition: opacity .25s;
  background: black;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1em;
}

.img-container:hover .overlay {
  opacity: .5;
}

overlay


text:
Q: FFMPEG remove codec x264 to final films I am processing my movie in ffmpeg (file merging, stabilization). The resulting metadata file gets an x264 codec. What prevents it from being reprocessed?
I decided to remove the codec using the Internet.
script:
    ffmpeg -i input.mp4 -c copy -map 0 -metadata creation_time="2017-09-18 13:30:04" output.mp4
ffmpeg -i output.mp4 -vcodec copy -acodec copy -vbsf h264_changesps=removesei -map_metadata -1 out.mp4
pause

Unfortunately it does not work:

Unknown bitstream filter h264_changesps

What am I doing wrong?


text:
Q: Integer solutions of $\sum_{j=1}^m\frac{n-m}{j}+\sum_{j=m+1}^n\frac{n}{j}=k$ This is in reference to an answer I gave to this question. I am curious to know if my intuition is correct. Given $n,m\in\mathbb{N}$, with $n>m$, is it possible for $\exp(2\pi in\sum\limits_{j=1}^n\frac{1}{j})=\exp(2\pi im\sum\limits_{j=1}^m\frac{1}{j})$ to hold, other than the solution where $n=2$ and $m=1$? This can be written equivalently as: are there any other solutions $n,m\in\mathbb{N}$, $k\in\mathbb{Z}$ with $n>m$ other than $n=2$, $m=1$ to the equation: $$\sum_{j=1}^m\frac{n-m}{j}+\sum_{j=m+1}^n\frac{n}{j}=k$$
I suspect that the answer is 'no,' and there may be a proof involving residues modulo $j$, though I would be interested in seeing any proof.


text:
Q: Window in Window Dynamic Content I am a little new to WPF.
I want to use one window for all my content, the content will vary dramatically and the Window.Resources content will need to vary also.

<Window x:Class="NS01.WPF01"
        xmlns:b="clr-namespace:NS01"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
     xmlns:local="clr-namespace:FluidKit.Showcase.ElementFlow"
     xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"

        Loaded="Window_Loaded"
        Title="NS01"
     WindowStartupLocation="CenterScreen"
        Width="1280"
        Height="720"
        WindowStyle="ThreeDBorderWindow">

    <Window.Resources>
      ...
    </Window.Resources>

    <Grid>
        ...
    </Grid>

  </Window>

As an example, I would like to use some third party content like FluidKit's ElementFlow.
There are many good examples of how to dynamically Load UserControls, but nothing on Window in Window. The best I have found is: Changing content dynamically in wpf window
I would like to have multiple *.xaml Files in my project and load content dynamically into the Current Window.
EDIT:
I like WPF Frame, but I can not load and unload Window.Resources:

<Window x:Class="NS01.WPF01"
        xmlns:b="clr-namespace:NS01"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
     xmlns:local="clr-namespace:FluidKit.Showcase.ElementFlow"
     xmlns:Controls="clr-namespace:FluidKit.Controls;assembly=FluidKit"

        Loaded="Window_Loaded"
        Title="NS01"
     WindowStartupLocation="CenterScreen"
        Width="1280"
        Height="720"
        WindowStyle="ThreeDBorderWindow">

    <Window.Resources>
      ...
    </Window.Resources>

    <Frame Name="ContentHolder" />

  </Window>

ContentHolder.Source = new Uri("/XAML/Repository/Page1.xaml", UriKind.Relative);

Just so you know, I have explored:
SolidColorBrush SolidColorBrushRed = new SolidColorBrush(Colors.Red);
this.Resources.Add("RedBrushResource", SolidColorBrushRed);

Is what I am wanting to do possible? Can I load all the required content from a single xaml File?
Thanks.
EDIT:
This is one method, but not really what I was wanting:

<Page x:Class="NS01.XAML.Repository.Page1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:local="clr-namespace:NS01.XAML.Repository"
  mc:Ignorable="d"
  d:DesignHeight="300" d:DesignWidth="300"
  Title="Page1">

<Grid>

    <TextBlock Text="Welcome" FontSize="18" Foreground="{DynamicResource ResourceKey=textForeColorResource}" Margin="80,32,66,219"/>

</Grid>

</Page>

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:NS01.XAML.Resources">

<SolidColorBrush x:Key="textForeColorResource" Color="Blue"/>

</ResourceDictionary>

ContentHolder.Source = new Uri("/XAML/Repository/Page1.xaml", UriKind.Relative);

ResourceDictionary RD = new ResourceDictionary()
{
Source = new Uri("/NS01;component/XAML/Resources/Page1.xaml", UriKind.RelativeOrAbsolute)
};

Application.Current.Resources.MergedDictionaries.Add(RD);

Application.Current.Resources.MergedDictionaries.Remove(RD);

foreach (var R in MWindow.Resources)
{
MessageBox.Show(R.ToString());
}


text:
Q: ENVI EX reviews? Does anyone have a review of ENVI EX?  I am wondering how well the Feature Extraction and Image Classification workflows function.

A: based on my experience, envi ex is good if you don't have much time and need the data "quickly", if you're using good resolution rasters. in low-res rasters, the regular version, imho, is much better, because you have a better control of the procedure.
if you try the various extraction methods with the same raster in envi and envi ex, the results you obtain in regular envi are more accurate than the one's from envi ex.
edit: in the first line, i meant "envi ex", not "envi"...

A: In my experience, ENVI EX provides a rather simplistic method for performing feature extraction using object-based image analysis. I investigated using ENVI EX for a project involving image segmentation and classification, and decided that there was not enough configurability for my needs.
Instead, I find the eCognition provides a far more configurable (albeit far more expensive) piece of software which will allow you to segment with various parameters, and then perform very complex image classifications involving user-defined metrics and fuzzy parameters.

A: In my experience, ENVI Ex is good in sence if you donot have sofisticaed software like eCognition. But it have very less parameter to for user control. Segmentation results are satisfactory but classification are not good.


text:
Q: Google Maps custom panorama conflict with google streetview panoramas I have a custom panorama which shows outside of a building (street view). When I do:
panorama.setPano(myPano);
panorama.setPosition(myLatLng);

it starts showing my panorama but after a second stops and shows google's own street view. I found out setPosition method is triggering google street view. Without it, my pano is shown perfectly.
Is there any way to turn off or disable google data or StreetViewService or whatever is conflicting with my custom panorama?
thanks!

A: There's a note about it here: https://developers.google.com/maps/documentation/javascript/streetview#CustomPanoramaMethod

do not directly set a position on the StreetViewPanorama when you wish to display custom panoramas, as such a position will instruct the Street View service to request the default Street View imagery close to that location. Instead, set this position within the custom StreetViewPanoramaData's location.latLng field.

So just set pano object like you did before:

panorama.setPano(myPano);

and that's it, Streetview will use the position you specified in the pano object.


text:
Q: Casting object to type without generics public class ErrorCode
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }
    public Type ExceptionT { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        throw Activator.CreateInstance(ExceptionT, pMsg);
    }
}

So, as you can see i am trying to create an instance of the given type. I cannot use Generics. because i have a dictionary that creates a pool of error codes.
Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode
    (
        "element click intercepted",
        400,
        typeof(ElementClickInterceptedException)
    )
);

The above code doesn't work since the type being created is of type object and does not derive from system.exception
The above code won't work with generics since the dictionary needs to understand what is being built. I am not sure what to do here. my dictionary has about 50 different exceptions. Thoughts?

A: You need to cast the instance created to Exception
public class ErrorCode
{
  public int HttpStatus { get; private set; }
  public string JsonErrorCode { get; private set; }
  public Type ExceptionT { get; private set; }

  public ErrorCode(string pJsonErrorCode, int pHttpStatus, Type pExceptionType)
  {
    this.HttpStatus = pHttpStatus;
    this.JsonErrorCode = pJsonErrorCode;
    this.ExceptionT = pExceptionType;
  }

  public void ThrowException(string pMsg)
  {
    throw (Exception)Activator.CreateInstance(ExceptionT, pMsg);
  }
}

You can replace Exception by ElementClickInterceptedException or anything needed.
Test
var error = new ErrorCode("test", 1, typeof(ArgumentException));
try
{
  error.ThrowException("error");
}
catch ( Exception ex )
{
  Console.WriteLine(ex.Message);
}

Fiddle Snippet
Output
error

A:
I cannot use Generics. because i have a dictionary that creates a pool of error codes.

Yes, you really can, and it is the right solution. You just need to declare a base interface for your lookup dictionary.
public interface IErrorCode
{
    int HttpStatus { get; }
    string JsonErrorCode { get; }
    void ThrowException(string pMsg);
}

public class ErrorCode<T> : IErrorCode where T : Exception
{
    public int HttpStatus { get; private set; }
    public string JsonErrorCode { get; private set; }

    public ErrorCode(string pJsonErrorCode, int pHttpStatus)
    {
        this.HttpStatus = pHttpStatus;
        this.JsonErrorCode = pJsonErrorCode;
    }

    public void ThrowException(string pMsg)
    {
        var exception = (T)Activator.CreateInstance
        (
            typeof(T),
            new object[] { pMsg }
        );
        throw exception;
    }
}

//Declare the dictionary with the interface, not the concrete type
Protocol.ErrorCodes = new Dictionary<ErrorCodeType,IErrorCode>();

Protocol.ErrorCodes.Add
(
    ErrorCodeType.ElementClickIntercepted,
    new ErrorCode<ElementClickInterceptedException>
    (
        "element click intercepted",
        400
    )
);

If you need to work with any element in the list, you can use the interface-- you should not have to cast anything.
To get the HTTP status:
var status = Protocol.ErrorCodes[key].HttpStatus;

To get the Json error code:
var errorCode = Protocol.ErrorCodes[key].JsonErrorCode;

In general your code should not be depending on concrete instances but on interfaces (per the "D" in SOLID).