text:
Q: PostGIS geometry intersection test results different for Point and Linestring Can anyone please tell me what I'm doing wrong, and how do I avoid the problem? I'll attempt to clarify what I'm doing as things go along.
The geom column is a multipolygon column, all values are SRID=4326.
archive=> select st_intersects( GeomFromewkt('SRID=4326;LINESTRING(-16.899216666666668 12.610816666666667,-16.899216666666668 12.610816666666667)')
, z.geom) as intersects
from zone z
where z.zone_id=2;
 intersects
------------
 f
(1 row)

archive=> select   st_intersects( GeomFromewkt('SRID=4326;POINT(-16.899216666666668 12.610816666666667)')
, z.geom) as intersects
from zone z
where z.zone_id=2;
 intersects
------------
 t
(1 row)

This is the text representation of the geom:
MULTIPOLYGON(((-18.7273147400488 12.8862644964914,-18.7334078119781 12.3609663554343,-16.5597662148828 12.3796303212717,-16.6302631480867 13.1209501528692,-18.7273147400488 12.8862644964914)))

How can the linestring not intersect with the geometry, yet a single point does? Is this some sort of rounding error, or a problem because the linestring has a length of zero? If the length is the problem, how do I avoid this problem?

A: Yup, it looks like that is the behaviour from JTS and GEOS. The problem is that your LINESTRING is invalid. If you have PostGIS 2.0, you can use ST_MakeValid(geometry) to fix the LINESTRING to a POINT.
This query verifies your bug, and uses ST_MakeValid as a workaround.
WITH data AS (SELECT 'POLYGON((150 280, 99 215, 190 210, 150 280))'::geometry AS poly,
                     'POINT(170 240)'::geometry AS pt)

SELECT ST_Intersects(poly, pt) AS intersects_poly_pt,
       ST_Intersects(poly, ST_MakeLine(pt, pt)) AS intersects_poly_line,
       ST_IsValid(ST_MakeLine(pt, pt)) AS isvalid_line,
       ST_AsText(ST_MakeValid(ST_MakeLine(pt, pt))) AS valid_geom,
       ST_Intersects(poly, ST_MakeValid(ST_MakeLine(pt, pt))) AS intersects_poly_valid_geom
FROM data;

with results (using psql's \x option):
NOTICE:  Too few points in geometry component at or near point 170 240
-[ RECORD 1 ]--------------+---------------
intersects_poly_pt         | t
intersects_poly_line       | f
isvalid_line               | f
valid_geom                 | POINT(170 240)
intersects_poly_valid_geom | t

If you are using a previous version of PostGIS (pre 2.0), then you can cast from an invalid LINESTRING to a box2d, then back to a GEOMETRY. For a two-vertex LINESTRING with same coordinates, this turns into a POINT. Here is the PostGIS 1.5 version of the above:
WITH data AS (SELECT 'POLYGON((150 280, 99 215, 190 210, 150 280))'::geometry AS poly,
                     'LINESTRING(170 240, 170 240)'::geometry AS line)

SELECT ST_Intersects(poly, line) AS intersects_bad_line,
       ST_IsValid(line) AS isvalid_line,
       ST_AsText(CASE WHEN NOT ST_IsValid(line) THEN line::box2d::geometry
                      ELSE line END) as valid_geom,
       ST_Intersects(poly, CASE WHEN NOT ST_IsValid(line) THEN line::box2d::geometry
                                ELSE line END) AS intersects_poly_valid_geom
FROM data;

with results:
NOTICE:  Too few points in geometry component at or near point 170 240
NOTICE:  Too few points in geometry component at or near point 170 240
NOTICE:  Too few points in geometry component at or near point 170 240
-[ RECORD 1 ]--------------+---------------
intersects_bad_line        | f
isvalid_line               | f
valid_geom                 | POINT(170 240)
intersects_poly_valid_geom | t


text:
Q: Extract from zip file to a list I'm trying to extract a set of photos from a zip file using python
and then saving those pictures to an image list to do some work on each.
I tried a lot, but nothing was useful to me.

A: Try this:
import zipfile

path = 'path_to_zip.zip'
input_zip = zipfile.ZipFile(path)
l = [input_zip.read(name) for name in input_zip.namelist()]

To Display one of the images you can do:
import io

import matplotlib.pyplot as plt
from PIL import Image

image = Image.open(io.BytesIO(l[0]))
plt.imshow(image)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get instance of component on active route in Angular2's router? I know that ActivatedRouteSnapshot.component in Angular2 contains the reference/class to the activated route if I call Router.routerState.snapshot but how to get for the component class the current (or minimal: one created) instance for it?
Injector.get(..) does not return instances of components and creating a new instance of a component does also not help (me).

A: You can use
<router-outlet
  (activate)='onActivate($event)'
  (deactivate)='onDeactivate($event)'></router-outlet>

where $event is the component instance and for example assign it to a service to make it available globally.
See also https://angular.io/api/router/RouterOutlet
You can also create a custom <router-outlet> component that does that automatically.

A: You should be able to get it with the ActivateRoute.
For example, if you have the Injector service:
const activatedRoute: ActivateRoute = this.injector.get(ActivatedRoute);

then
component reference: this.injector.get(activatedRoute.component);

However, this only works if the injector instance you use has reference to that component itself.
In my example, this can be used to find the ViewComponent from a child of that view.
|- ViewComponent
  |- ChildComponent
    |- ChildComponent
      ... injector here -> using the code above, gets the ViewComponent' instance
  |- ChildComponent

This may not work in your instance, however, hopefully this may help someone.


text:
Q: why i should not use object manager directly in magento2? Magento 2 uses dependency injection means when ever client required any services we have to pass in constructor.
So magento take care like automatically create objects recursively..
but there is a statement like we should not use object manager.
I'm very confusing on this part.
Can you some one explain ?

A: There are several reasons. The code will work, but it is best practice to not reference the ObjectManager class directly.

*

*Because we say so! ;-)  (better expressed as consistent code is good code)

*The code could by used with a different dependency injection framework in the future

*Testing is easier - you pass in mock arguments for the required class, without having to provide a mock ObjectManager

*It keeps dependencies clearer - it is obvious what the code depends on via constructor list, rather than having dependencies hidden in the middle of the code

*It encourages programmers to think about concepts like encapsulation and modularization better - if the constructor gets big, maybe it is a sign the code needs refactoring

I would also suggest reading up on dependency injection. There are lots of tutorials around on the concept. Here are a few I found pretty quickly, with Martin Fowler's description being definitely worth a read.

*

*Martin Fowler: http://www.martinfowler.com/articles/injection.html

*Wikipedia: https://en.wikipedia.org/wiki/Dependency_injection

*Java Creed: http://www.javacreed.com/why-should-we-use-dependency-injection/
At the end of the day just remember dependency injection is not a new concept - Magento is following best practices learnt over more than 10 years by the community at large.


text:
Q: How to share my own facebook application to my friends I developed a simple FB messenger bot app, the app was reviewed and approved by Facebook, it is live and working as expected, replying to messages from my Page users.
Now, I want to share my app to my friends, so they can use it to their Pages. However, I can't find a way to share it, I can't find the link for my App. Any hint on how to share my App will be greatly appreciated.


text:
Q: templated method with std::vector overload not taking hold I know this question has been asked numerous times, but referring to the answer to this question:
How can I specialize a template member function for std::vector<T>
if I try a simple example of this using GCC9 it simply does not work, and I cant understand why not.  Am I missing something here?
#include <vector>
#include <stdio.h>

template<typename T>
std::vector<T> foo( const std::vector<T> & )
{
    printf( "vector!\n" );
    return std::vector<T>();
}

template<typename T>
T foo( const T & )
{
    printf( "non vector!\n" );
    return T();
}

int main()
{
    foo<int>( *( int * ) nullptr);
    foo<std::vector<int>>( *( std::vector<int> * ) nullptr);
}

Outputs:
non vector!
non vector!

A: Try changing:
foo<std::vector<int>>( *( std::vector<int> * ) nullptr);

to
foo<int>( *( std::vector<int> * ) nullptr);

Your top template expects a typename T and the method takes a vector of T.


text:
Q: Assigning values via a Lambda Expressions? I am aware of the following quote:

The reason is that a lambda expression can either be converted to a delegate type or an expression tree - but it has to know which delegate type. Just knowing the signature isn't enough.

Trouble is I am still stuck on how to resolve my problem.
Can someone tell if the below is at all possible?
bool isStaff = () => { return selectedPerson.PersonType == "Staff"; };

Error:

Cannot convert lambda expression to type 'bool' because it is not a delegate type

I understand the error, but I really want to know how to fix this issue as I have rebounded off this error many times and simply not learnt to how properly use lamda expressions as far as value assignment is concerned.
Thanks for the quick replies fellas:
IMO, it would be awesome of the below was possible:
bool isStaff = (selectedPerson, bool) => { return selectedPerson.PersonType == "Staff"; };

Lol, I don't think that works but is beautiful in line code, to me that looks awesome and what I expect. The answers below seem to suggest otherwise lol!

A: bool isStaff = selectedPerson.PersonType == "Staff";

or
Func<Person, bool> isStaffDelegate = selectedPerson =>
                                         selectedPerson.PersonType == "Staff";
bool isStaff = isStaffDelegate(selectedPerson);

A: The problem is that the lambda returns a bool when it is evaluated, but it is not a bool itself.
You can do the following:
Func<bool> func = () => { return selectedPerson.PersonType == "Staff"; };
bool isStaff = func();

This assigns the lambda to a variable, which can then be used to invoke the lambda, and return the desired bool value.

A: As the compiler says, you need to assign to a delegate or expression tree type. So for example:
Func<bool> isStaff = () => selectedPerson.PersonType == "Staff";

Now you haven't explained what you're really trying to do, or what selectedPerson is. The above will capture the selectedPerson variable - but you may actually want a Func<Person, bool> instead, as per the_ajp's answer.


text:
Q: Pacemaker ocf:heartbeat:IPaddr on different subnets I'm trying to add a Pacemaker virtual IP address; with it, the gateway, and the two VMs it serves on different subnets. I've only done this before with all IPs on the same subnet, and I need some help.
I have two VMs on 200.xx.xxx.9 and 200.xx.xxx.10 with the below in /etc/network/interfaces
auto eth0
iface eth0 inet static
    address 200.xx.xxx.9
    gateway 200.xx.xxx.9
    netmask 255.255.255.255

    post-up route add yy.yyy.yyy.1 dev eth0
    post-up route add default gw yy.yyy.yyy.1

and
auto eth0
iface eth0 inet static
    address 200.xx.xxx.10
    gateway 200.xx.xxx.10
    netmask 255.255.255.255

    post-up route add yy.yyy.yyy.1 dev eth0
    post-up route add default gw yy.yyy.yyy.1

They're both showing up in Pacemaker, and seemingly communicating OK. The bindnetaddr parameters in the two /etc/corosync/corosync.conf files are:
bindnetaddr: address 200.xx.xxx.9

and
bindnetaddr: address 200.xx.xxx.10

respectively.
If everything was on the same subnet, I'd expect to add the virtual IP with something like:
sudo crm configure primitive eth0_virtual ocf:heartbeat:IPaddr params ip="200.zzz.z.162" nic="eth0" cidr_netmask="24" broadcast="200.zzz.z.255" op monitor interval="10s" timeout="20s"

and while this shows up as resource in crm_mon, it isn't allowing me to access one of the VMs via the virtual IP. Clearly there's more to it, but what?
Edit: After a suggestion on the ClusterLabs mailing list that this may be an underlying networking issue, here's where I'm at:
I'm hosting ESXi with online.net, who provide additional 'failover' IPs that can be assigned to my hosted VMs.
I have three; 200.xx.xxx.9 and 200.xx.xxx.10 which I'm using for the two Ubuntu VMs listed, and the third, 200.zzz.z.162, which I'm trying to use as an ocf_heartbeat_IPaddr resource agent. Critically, online.net require that you match assign each IP a MAC address that matches an interface on a VM. I did this for the first two IPs (using different MAC
addresses) but not for the third. When I tried using one of the existing MAC addresses with the third IP, I immediately got connectivity with:
So now, I have all three IPs and both VM interfaces sharing the same MAC address. This strikes me as a really bad idea, but, it actually seems to be working, without creating any packet errors or problems with connectivity or the HA cluster... at least none that I've spotted so far, other than martian traffic being logged. This is the ocf:heartbeat:IPaddr setting I'm using:
sudo crm configure primitive eth0_virtual ocf:heartbeat:IPaddr params ip="200.zzz.z.162" nic="eth0" cidr_netmask="32" broadcast="200.zzz.z.162" op monitor interval="10s" timeout="20s"


text:
Q: Is there a name for the partial order of metrics defined by induced topology subset. If we have two metrices on a space then these will induce a topology and since the subset relation defines a partial order on the power set then so does the relation $d_1 \succeq d_2$ if $\operatorname{Ind}(d_1) \supseteq \operatorname{Ind}(d_2)$ (where $\operatorname{Ind}(d)$ is the topology induced by $d$).
Has this relation $\succeq$ a name? (Note that $d_1\succeq d_2 \succeq d_1$ is the same as $d_1$ and $d_2$ are equivalent)

A: On the topology level it's just the standard refinement partial order on topologies (its standard complete lattice structure). So it's just the pulled back pre-order of this partial order via the "induce"-function, as it were. The pre-order comes from the fact that the metrisable topologies can have many different inducing metrics; I see no need for a name, I don't think it has been studied much. You could just call a metric finer, if it induces a finer topology, I suppose.


text:
Q: Unable to access BIOS after updating Vista to Windows 8 My laptop has two drive bays, and I want to have a dual boot system.
I have installed a clone of my Windows 8 (it works) and want to 'upgrade' it to 64-bit instead of x86 with the x64 disc that I bought and got posted out. I want to boot off the DVD I have.
However, on this Toshiba Satellite Vista laptop F2 used to provide access to the BIOS, but now it never works and goes straight to Windows 8. (There is a related question here that was closed.)
I have tried all the usual alternatives but just get a long beep when I press any key (F12, Del etc.) So, my question is, how do I access the BIOS, now that Windows 8 has hijacked it without telling me beforehand?

A: This was somewhat planned by Microsoft. Try going to PC Settings > General > Advanced Startup and select "Restart now" to get into the UEFI BIOS where you can tell Windows/the BIOS to boot from a different device.
More info here: http://blogs.msdn.com/b/b8/archive/2012/05/22/designing-for-pcs-that-boot-faster-than-ever-before.aspx


text:
Q: Check if user has custom post published redirection on WordPress I am trying to run a check when a user visits a certain page to see if the current user has a published or draft posts of a custom post type. If they do, then I'm trying to redirect them. I've found some posts, but no luck in putting it all together to fit my needs. I can understand the template redirect function a bit easier, so I've tried to go that route. I'm not sure if that's the best way to do it.
I've tried to work with these snippets:
https://wordpress.stackexchange.com/questions/187973/how-to-check-that-if-current-user-id-has-posts-or-not
https://wordpress.stackexchange.com/questions/139818/check-if-current-user-has-post-in-post-type-and-is-author-role
add_action( 'template_redirect', 'redirect_to_specific_page_resume' );

    function redirect_to_specific_page_resume() {
    global $post;

    $current_user = $post->post_author;

    if(!empty($current_user)){
    $user_post_count = (int) count_user_posts( $current_user );

       if ( is_page('479') && $user_post_count == 1 ) {

            wp_redirect( "/myaccount/manage-resumes", 301 );

            exit;

      }
   }
   }

If current user goes to PAGE ONE and is a published or draft author of a custom post type, then redirect to PAGE TWO. If current user goes to PAGE ONE and is NOT a published author of a custom post type, do nothing, load PAGE ONE as normal.
Thank you.

A: Solution provided by butlerblog

function redirect_to_specific_page_resume() {

    /*
     * Only bother to check if the user is logged in
     * AND we're on page ID 479. Otherwise, there's no
     * reason to run the remaining logic.
     */
    if ( is_user_logged_in() && is_page( 479 ) ) {

        // Get the current logged in user's ID
        $current_user_id = get_current_user_id();

        // Count the user's posts for 'resume' CPT
        $user_post_count = (int) count_user_posts( $current_user_id, 'resume' );

        // If the user has a 'resume' CPT published
        if ( $user_post_count > 1 ) {

            // Get the URL to redirect the user to.
            $url = get_permalink( 480 );

            // Redirect the user.
            wp_redirect( $url );
            exit();

        }
    }
}


text:
Q: exported array becomes a pending promise? I have this code that gets all players in a specific lobby. The console.log() before the return works as expected:
  const getPlayersByLobby = async (lobbyId) => {
    const playersRef = firebase.firestore().collection("GameLobbies").doc(lobbyId).collection("players");
    const playerNames = [];
    const players = await playersRef.get();
    players.forEach((groupSnapshot) => {
       playerNames.push(groupSnapshot.data().name)
    });
    console.log(playerNames) // ["player1Name", "player2Name"];
    return playerNames
  }

Now when rendering the component I do a console.log(getPlayersByLobby(lobby.id)) to see what I get. I see I have a pending promise instead of my array.
Can anyone help my why this is? And how to get my array back?
  return(

Current game lobbies:

      {gameLobbies.map((lobby) => { //gameLobbies comes from a useState() hook that does work
        return (

naam: {lobby.name}

Code: {lobby.gameId}

Spelers in deze lobby:

            {console.log(getPlayersByLobby(lobby.id))}

        )
      })}

  );

A: This is something I struggled with when I came across promises.
With promises it is important to remember that async/await is just a syntactic sugar and it is doesn't make the code synchronous as one might think. It lets you write your code in a way in which it looks synchronous.
Any async function by default returns a Promise and the only way to get the returned value (which comes AFTER the promise has resolved) is to await it everywhere you call that async function.
It does not matter that you already awaited it within the function, that doesn't mean that the function will wait for the promise to get the value/resolve the value before it returns.
The function simply returns the Promise right away with pending status and once the data is there the Promise is updated with the data. In this case by not adding await you are saying "I don't want to wait for the data, just give me the promise" and now you can pass this promise around but you will have to await it if you want the value anywhere you pass it.
Since in your example in the component {console.log(getPlayersByLobby(lobby.id))} there is no await before you call getPlayersByLobby it will simply return a pending Promise without awaiting it
Another way to think about it is using .then(()=> {}).catch((error) => {}) syntax. If there were no async/await keywords or Promises you would have to chain all thens inside of each other.
Using async/await you STILL have to chain the promise but it just looks more readable/synchronous
Hope that makes sense.

A: try to store players in the state when you get them from the database, also its better to use useEffect when you retrieve data from your database
const [players, setPlayers] = useState([])
const [lobbyId, setLobbyId] = useState([initalId])

 useEffect(async () => {
    const playersRef =
  firebase.firestore().collection("GameLobbies").doc(lobbyId).collection("players");
    const playerNames = [];
    const players = await playersRef.get();
    players.forEach((groupSnapshot) => {
       playerNames.push(groupSnapshot.data().name)
    });
    console.log(playerNames) // ["player1Name", "player2Name"];
    //return playerNames
    setPlayers(playerNames)
  }, [lobbyId]) // it called again whenever you changed your looby id

now it should work

   // now you have access to them
   {console.log(players)}

A: First, as you are only using the name field stored in your document, consider switching out groupSnapshot.data().name for groupSnapshot.get("name") for efficiency.
As this function is stateless, you should place this function outside of your component's render function:
const getPlayersByLobby = async (lobbyId) => {
    const playersRef = firebase.firestore()
        .collection("GameLobbies")
        .doc(lobbyId)
        .collection("players");
    const playerNames = [];
    const players = await playersRef.get();
    players.forEach((groupSnapshot) => {
        playerNames.push(groupSnapshot.get("name"))
    });
    console.log(playerNames) // ["player1Name", "player2Name"];
    return playerNames
}

Same with this "render lobby" function:
const renderLobby = (lobby, playerList = undefined) {
  let players;

  if (playerList === undefined) {
    players = (
Loading player list...
);
  } else if (playerList === null) {
    players = (
Failed to get player list
);
  } else if (playerList.length === 0) {
    players = (
Player list empty
);
  } else {
    players = (
{
      playerList.map((p) => (

          {p.name}

      ))
    }
);
  }

  return (

naam: {lobby.name}

Code: {lobby.gameId}

Spelers in deze lobby:

      { players }

  );
}

Next, in your component, you make use of useEffect() to fetch data from the database. Here, I've used a state object that is a map of lobby IDs to lists of players. On each render, a call is sent off to the database to fetch the current player list.
Because Promises (in this case, database calls) can take longer than render cycles to finish, we need to make sure to not call any setState functions after the component has been unmounted. This is done using the disposed boolean value to discard the results of the Promises if the useEffect's unsubscribe function has been called.
const [gameLobbies, setGameLobbies] = useState(/* init value */);
const [playersByLobby, setPlayersByLobby] = useState({});
useEffect(() => {
    let disposed = false;

    const newPlayersByLobby = {};

    Promise.all(gameLobbies.map((lobby) =>
      getPlayersByLobby(lobby.id)
        .then((playerList) => newPlayersByLobby[lobbyId] = playerList)
        .catch((err) => {
          console.error(`Failed to get Lobby #${lobbyId}'s player list: `, err);
          newPlayersByLobby[lobbyId] = null;
        })
    ))
      .then(() => {
        if (disposed) return; // component disposed/gameLobbies was changed
        setPlayersByLobby(newPlayersByLobby);
      })

    return () => disposed = true;
}, [gameLobbies]); // rerun when gameLobbies updates

return (

Current game lobbies:

    {
      gameLobbies.map(
        (lobby) => renderLobby(lobby, playersByLobby[lobby.id])
      )
    }

);

Note: Consider implementing a <Lobby> component along with a <PlayerList> component. By doing this, you allow yourself the ability to make full use of the Firestore's Realtime updates.

A: Try doing it like this
{
  getPlayeesByLobby(lobby.id).then(val => {
    console.log(val);
  }
}

This should give an error in React so what's next
Make an iife or more specifically useEffect in React
so make a useState and after getting data from backend setPlayers to that array. And then map the array and render
 in the
.
This is what you need to do


text:
Q: Cannot set setstate in reactJS Can anybody explain what im doing wrong here, my setState console is returning undefined where the first console is returning right values
return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
            snapshot.forEach(function(childSnapshot){
                // var childKey= childSnapshot.key;
                var childData= childSnapshot.val();
                var childEmail = childData.email;
                var childfirstName = childData.firstName;
                var childlastName = childData.lastName;
                var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
                 console.log(childTrainers);
            })
            this.setState({
                Trainers: snapshot.val().childTrainers
            })
            console.log(this.state.Trainers)
        })

A: Okay ive done, and the correct answer is
return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
            snapshot.forEach((childSnapshot) => {
                // this.setState({
                //     childEmail = childSnapshot.val().email
                // })
                // var childKey= childSnapshot.key;
                var childData= childSnapshot.val();
                var childEmail = childData.email;
                var childfirstName = childData.firstName;
                var childlastName = childData.lastName;
                var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
                 //console.log(childTrainers);
                 this.setState({
                     Trainers: [childTrainers]
                 }, console.log(this.state.Trainers))
            })
        })

All values are retrieving


text:
Q: Ruby: what is the difference between using open() and NET::HTTP module to fetch web content? A separate SO post offers different methods for fetching web content in Ruby, but doesn't fully explain why one is preferable to the other.
What is the difference between using open() and the NET::HTTP module, as demonstrated below, to fetch web content? Why is NET::HTTP considered the "better" approach?
**open() 1:**
require 'open-uri'
file = open('http://hiscore.runescape.com/index_lite.ws?player=zezima')
contents = file.read

**open() 2:**
require 'open-uri'
source = open('http://www.google.com', &:read)

**NET::HTTP 1:**
require 'uri'
require 'net/http'
url = "http://hiscore.runescape.com/index_lite.ws?player=zezima"
r = Net::HTTP.get_response(URI.parse(url).host, URI.parse(url).path)

A: Rule of thumb: Use OpenURI whenever you can.
The reason is that OpenURI is just a wrapper around Net::HTTP, therefore it will require less code to be written. So if all you do is performing simple GET requests, go for it.
On the other hand, prefer Net::HTTP if you want some lower-level functionality that you OpenURI does not give you. It is not a better approach, but it provides more flexibility in terms of configuration.
As the official documentation states:

If you are only performing a few GET requests you should try OpenURI.


text:
Q: How to create a link without showing the url? Could someone please share how to create a link and not letting the users know the url of the link?
For example in the following website, when you hover over the practice groups the mouse shows that its a hyperlink but the url doesn't get dsplayed.
verbling.com/community
I am developing a similar page. Kindly share how to create a link and not letting the users know the url of the link.

A: you can add a click function and set the location throgh javascript like:-
$( document ).ready(function() {
    $( "#target" ).click(function() {
      location.href = 'http://address.com';
    });
});

for this thing to work you have to include jquery, either from your server or from CDN like

A: Following this simple example with jquery
Click Here

$(function(){
    $('.do_action').click(function(e) {
        e.preventDefault();

        // Open link on same page
        document.location.href = 'http://example.com';

       // Open link in tab or other window
       // window.open();
    });
});

For new tab window.open()


text:
Q: Efficiently programming array elements to add up to a sum in python I'm looking to implement in python a simple algorithm which takes as input an array and a sum, and finds a number X where if all elements in the array > X are converted to X, all the elements in the array should add up to the sum.
How do I do this efficiently?
Here is my code:
result = []
for _ in range(int(raw_input())):
     input_array = map(int,raw_input().split())
     sum_target = raw_input()
     for e in input_array:
        test_array = input_array
        test_array[test_array > e] = e // supposed to replace all elements > e with e, but what's wrong here?
        if sum(test_array) == sum_target:
            result.append(e)

print result

A: Using the Numpy library (import numpy), you could replace the line
 input_array = map(int,raw_input().split())

with
 input_array = numpy.array(raw_input().split()).astype(int)

Then
    test_array[test_array > e] = e

just works. Then, you could also do test_array.sum().
(That is, if you want to alter the array in-place, else you could replace
    test_array = input_array

with
    test_array = np.array(input_array)


text:
Q: Primefaces refreshing dataTable on modal dialog commandButton click I have dataTable for editing users.
I have commandLink in each row for opening modal dialog with selected user data for editing.
On that dialog I have commandButton for saving user.
I have a problem refreshing dataTable and displaying new edited values for user.
<p:commandButton value="Save" action="#{usersBean.updateUser()}" onclick="PF('editUserDlg').hide();" update=":adminForm:adminTabView:usersDataTable" styleClass="ui-priority-primary" style="float: right;" />

I followed BalusC answer on subject finding out id of component and have no errors in server log.
When I click on Save button I call backing bean method:
public void updateUser() {
    int userId = selectedUserView.getId();
    User user = adminSessionBean.getMe(userId);
    try {
        updateUser(user);
        LOG.info("User seccessfully updated.");
    } catch (Exception exc) {
        String message = "Error updating user: " + exc.getMessage();
        LOG.error(message);
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
    }
}

and edited user is saved correctly (I've checked in database). Problem is that I don't see new edited user values in dataTable after modal dialog is closed.
When I refresh page I see new values for user.
When I add call @PostConstruct init() method after updateUser(user); I see the changed values in dataTable, but I am not sure if this is the correct approach.

A: Thanks Kukeltje,
I'll go with calling init() after updateUser() method.

A: I wouldn't call the init method, this method should only be called after the bean is constructed as the annotation states.
Try calling a remoteCommand instead of closing your dialog directly which refreshes the dataTable. After that you could close the dialog from that command. Something like this.
<p:remoteCommand name="updateContent" update="table"
oncomplete="PF('dialog').hide();" />

Didn't tried this solution directly, but I think that should work. I used this approach for a similar problem.
EDIT: As Kukeltje states, you also have to refresh your dataModel so that the dataTable receives the new data. You could add an actionListener to the remoteCommand to do that.


text:
Q: Transfer login from https to http I would like to secure logins by redirecting users to https://secure.domain.com/login then on a successful login, redirect them back to a plain http website bringing the session with them. Is this secure? Should I just buy a multi-domain plan so it secures sub domains and the parent domain? I'm puzzled.
TL;DR - Is transferring a login session from HTTPS to HTTP secure?

A:
Is transferring a login session from HTTPS to HTTP secure?

No.
You have two dataflows. One is the {username, password} to the server used for authentication. The second is the token or cookie returned to the client (and the client sending it to the server on subsequent requests).
The first dataflow is protected by HTTPS, and its OK (some hand waiving).
The subsequent dataflows utilize HTTP, so anyone who is in position can read and subsequently use the token or cookie.
Its also bad to mix and match HTTP/HTTPS due to downgrade attacks (or makes matters worse). See for example, Why is TLS susceptible to protocol downgrade attacks?.


text:
Q: What is a good online development IDE? I want a good development IDE for a node.js developer. I also want one that can be downloaded on a local machine.

A: You could go for c9.io that's an online IDE, It works pretty well for any language , and you don't even need to install any software locally. Everything in cloud.
For Offline IDE , I would recommend Sublime, It is used by most of the great developers worldwide.
In sublime you have a great potential for shortcuts and you will be working really fast once you have control over it.
All the best :)


text:
Q: `window.onload` faild to run after asigning `window.__proto__ = prelude` , but why? I by prelude mean this object: http://gkz.github.com/prelude-ls/
Seems not good idea to bind prelude to window.__proto__, though.
I'm curious and confused about why this happend, and my code in Chrome:
window.__proto__ = prelude;
window.onload = function(){
  console.log('loaded');
}

A: __proto__ is a non-standard reference to the prototype of the window object (https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/proto).
In your first line you are overwriting the entire prototype of window. This means that everything else previously written to the prototype object gets list, including native functions that could be responsible for invoking window.onload.
You should typically never overwrite the prototype object, but instead extend it or simply add new properties directly to objects like window.


text:
Q: Which program can open a .DJVU file? I received a folder with a bunch of PDF files and one DJVU file.  The PDF's open in PDF Complete but the DJVU does not.  How do I open this type of file?
I'm using Windows 7 64-bit and Internet Explorer 8.

A: I would suggest SumatraPDF.
It opens PDF, XPS, DjVu, CHM, CBZ, CBR and is small and really fast.

A: Viewers can be found here.  It's just another (not as widely used) format for compression in documents.

A: You should visit a website suggesting software for various file types like this one:
File Extension DJVU
Here are some examples of Windows software from the site:

*

*WinDjView

*DjVuLibre DjView

*ACD Systems Canvas 14

*ACD Systems ACDSee 15

*Lizardtech DjVu Solo

*Web browser with LizardTech DjVu Browser plugin

A: IrfanView , The "swiss army knife" for viewing graphic files on Windows, can display DJVU files.
With the plugin pack it is also easily possible to save the document as a PDF file:
File -> Save as... -> PDF


text:
Q: Variable not being set outside function? This is really doing my head in regarding async i cant get this to work as the summonerData array is not set, i know its probably regarding async but i dont know how to validate it.
var summonerName = req.params.playerName;
var summonerData = [];
var summonerIds = [];
var summonerGames = [];
redis.exists(summonerName, function(err, reply) {
    if (reply === 1) {
      console.log('Data Found for Summoner in Redis!: ' + summonerName);
      redis.hgetall(summonerName, function(err, object) {
        summonerData.push(object);
      });
    } else {
      console.log('Data not Found for Summoner: ' + summonerName);
      lolapi.Summoner.getByName(summonerName, function(error, summoner) {
        if (summoner) {
          console.log('Summoner was retrieved by API! and Saved to Redis!');
          redis.hmset(summonerName, summoner[summonerName]);
          summonerData.push(summoner[summonerName]);
        }
      });
    }
});
console.log(summonerData);

A: When you do something asynchronously, it means the function is called at some point in the future. Your call to redis.exists means at some point in the future, the function you provide will be called. The line after it, console.log(summonerData), is run before the callback function.
Move console.log(summonerData) into the function for it to work as you intend.

A: You should use promises
var getSummonerData = function (summonerName) {
    return new Promise(function (resolve, reject) {
        var summonerData = [];
        var summonerIds = [];
        var summonerGames = [];
        redis.exists(summonerName, function (err, reply) {

            if (err) {
                return reject(err);
            }

            if (reply === 1) {
                console.log('Data Found for Summoner in Redis!: ' + summonerName);
                redis.hgetall(summonerName, function (err, object) {
                    if (err) {
                        return reject(err);
                    }
                    summonerData.push(object);
                    resolve(summonerData);
                });
            } else {
                console.log('Data not Found for Summoner: ' + summonerName);
                lolapi.Summoner.getByName(summonerName, function (error, summoner) {
                    if (error) {
                        return reject(error);
                    }
                    if (summoner) {
                        console.log('Summoner was retrieved by API! and Saved to Redis!');
                        redis.hmset(summonerName, summoner[summonerName]);
                        summonerData.push(summoner[summonerName]);
                    }
                    resolve(summonerData);
                });
            }
        });
    });
};

getSummonerData(req.params.playerName)
        .then(function (summonerData) {
                res.render(..., summonerData);
        });

More: https://spring.io/understanding/javascript-promises


text:
Q: How to UPDATE from columns in an attached database in sqlite3? After 4 hours of googling and more hours of experiments pretty much my last hope is that someone can tell me what is going on when I try the following:
    sqlite3 test1.sqlite
    attach database 'test2.sqlite' as newDB;

This works - no error messages and ".databases" shows "newDB" as #2. "newDB" and "main" have exactly the same structure: same tables, same columns, same names for everything. Simple stuff like
    select * from main.ztip;

or
    select * from newDB.ztip;

works. ("ztip" being, obviously, a valid table name in both DBs.) But when I try to do what I need to do (omitting the WHERE clause for simplicity)
    update main.ztip set zisfavorite=newDB.ztip.zisfavorite;

BOOM! The column "newDB.ztip.zisfavorite" isn't found. Same goes for
    update main.ztip set zisfavorite=newDB.zisfavorite;

which I tried out of desperation. (Column names are unique.)
Anybody know whether what I want do is possible and how to make to work?
Thanks in advance,
Tom

A: It's not quite clear what you're trying to update here.
You can use UPDATE my_table SET col_a=col_b when col_a and col_b are columns in the same table: this will update set value of col_b into col_b for each row. col_b isn't just a column name, but it's associated with a specific value in this case.
However, in update main.ztip set zisfavorite=newDB.ztip.zisfavorite, newDB.ztip.zisfavorite represents an entire column. There is no reason to know which row and value you're willing to use.
Perhaps you should use something like:
UPDATE main.ztip z1 SET zisfavorite=(SELECT z2.zisfavorite FROM newDB.ztip z2 WHERE z2.id=z1.id)

The details of the where clause will depend on the actual structure of your tables, of course. Make sure it returns only one value.


text:
Q: Image format conversion opencv I am doing a project and it needs to convert the image format. Firstly, I need to change the image from cv::Mat format to Image<byte> format which is a kind of black-white frame. The following code shows how to change from cv::Mat to Image<byte>.
void conversionNB(Mat frame, Image<byte> &imBW)
{
    Mat clone = frame.clone();
    Mat_<Vec3b>& frame_p = (Mat_<Vec3b>&)clone;
    for(int i = 0; i < 480; i++)
    {
        for(int j = 0; j < 640; j++)
        {
            imBW[i][j] = (frame_p(i,j)[0] + frame_p(i,j)[1] + frame_p(i,j)[2])/3;
        }
    }
}

Then, after processing of the images, I need to change the images back to cv::Mat format to show them. Does someone know how to change from Image<byte> to cv::Mat according to the code?
P.S. Image<byte> is an 8-bit data type from cvd library.
namespace CVD
{
   typedef unsigned char byte;
}

A: *

*To change from Image<byte> to cv::Mat
Mat image(rows,cols,CV_8UC1,(unsigned char*)imBW.data());
for a gray scale image.

*your code might runs slow. we can create cvd image and opencv mat directly from unsigned char* data.
void conversionNB(Mat& frame, Image &imBW){
    Mat cvd_image(frame.rows,frame.cols,CV_8UC1,(unsigned char*)imBW.data());
    cvtColor(frame, frame, CV_BGR2GRAY);
    frame.copyTo(cvd_image);
}
void conversionRGB(Mat& frame, Image > &imRGB){
    Mat cvd_image(frame.rows,frame.cols,CV_8UC3,(unsigned char*)imRGB.data());
    cvtColor(frame, frame, CV_BGR2RGB);
    frame.copyTo(cvd_image);
}


text:
Q: How to Release the Port Being Used Visual studio Several i came to the Issue ,In Development Environment when i use to Run the Project .Error Says
Port '4131' is already being used by another application .Note that it can be any port '4131' is just for the ref.
I Generally use to switch to another port .But this is not the Solution ,what i believe .Because it happens now a days frequently .
I want to know how to release the Port already being Used ,Forcefully .As i know this port is Unnecessary Reserved .

A: These issues generally comes due to following reason which i faced :

*

*Port is used by other process and reserved .

*Port is Not released by the last same process.
I Recommend following Approaches :

*

*Changing the Port is the best idea .

*Restart your system ,this will release the port in use .
Today i do face same ,after doing multiple R&D find these solution ,Feel like sharing the same.


text:
Q: Extract pixel values using pixel condition in R I am preparing a dataset to run a SVM classification. So far, I have a raster stack  which includes a layer ([6]) for training
> S1
class       : RasterStack
dimensions  : 3865, 6899, 26664635, 6  (nrow, ncol, ncell, nlayers)
resolution  : 14.83, 14.83  (x, y)
extent      : 361363.5, 463675.7, 5760647, 5817965  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
names       : Coherence_VV_Stack2.1, Coherence_VV_Stack2.2, Coherence_VV_Stack2.3, Coherence_VV_Stack2.4, Coherence_VV_Stack2.5, Class
min values  :                     ?,                     ?,                     ?,                     ?,                     ?,     0
max values  :                     ?,                     ?,                     ?,                     ?,                     ?,     1

Where S1[[6]] is:
> S1[[6]]
class       : RasterLayer
dimensions  : 3865, 6899, 26664635  (nrow, ncol, ncell)
resolution  : 14.83, 14.83  (x, y)
extent      : 361363.5, 463675.7, 5760647, 5817965  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : in memory
names       : Class
values      : 0, 1  (min, max)

and plot(S1[[6]) is:

I want to create a dataframe (to be used later as input for classification) where:

*

*If pixel value in S1[[6]] is 1, extract the pixel values in the other layers of the raster stack and put it in the dataframe

*If pixel value in S1[[6]] is0, do nothing.
Any suggestion on how to proceed? I know the issue can be solved by importing a shapefile and use the extract function but I want to use this approach.

A: Given a 3x4 cell x 6 layer brick where the last layer is a 0/1 indicator:
> S1
class       : RasterBrick
dimensions  : 3, 4, 12, 6  (nrow, ncol, ncell, nlayers)
resolution  : 0.25, 0.3333333  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : in memory
names       :    layer.1,    layer.2,    layer.3,    layer.4,    layer.5,    layer.6
min values  : 0.07979194, 0.01004478, 0.12462376, 0.08388173, 0.03662221, 0.00000000
max values  :  0.8417125,  0.9823274,  0.9087239,  0.9050184,  0.9624438,  1.0000000

Then this one-liner will return a data frame of the values in the first five layers for cells that have a one in the last layer:
> ones = setNames(do.call(cbind.data.frame,
          lapply(1:nlayers(S1),
                 function(i){S1[[i]][S1[[nlayers(S1)]][]==1]})),
                 names(S1))
> ones
     layer.1    layer.2   layer.3    layer.4    layer.5 layer.6
1 0.61572701 0.30333021 0.4982907 0.18118309 0.03662221       1
2 0.84171251 0.98232742 0.1246238 0.40075522 0.68438716       1
3 0.37735819 0.27628720 0.7060747 0.25431005 0.33987833       1
4 0.30291850 0.10383452 0.2485474 0.90501841 0.30548540       1
5 0.57979692 0.01196571 0.4019636 0.36540125 0.96244376       1
6 0.14576374 0.48495665 0.4268066 0.34438584 0.83443135       1
7 0.70245897 0.01004478 0.9087239 0.78135612 0.19428952       1
8 0.79984520 0.24450234 0.1956386 0.08388173 0.07563230       1
9 0.07979194 0.32003334 0.3989493 0.48715195 0.18219895       1

To check, the first column should be the numbers in here:
> as.matrix(S1[[1]])
          [,1]      [,2]      [,3]       [,4]
[1,] 0.6157270 0.8417125 0.3773582 0.30291850
[2,] 0.5797969 0.1457637 0.3296398 0.46653010
[3,] 0.7024590 0.7198337 0.7998452 0.07979194

that have a one in here:
> as.matrix(S1[[6]])
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    0    0
[3,]    1    0    1    1

Building tiny examples is a very useful skill when developing data analysis methods.


text:
Q: Get PGP Fingerprint key in c# I just want to know if there is a c# lib to get the key fingerprint such "B97E 9964 ACAD 1907 970D  37CC 8A9E 3745 558E 41AF".
I currently use BouncyCastle to encryption/decryption and to make signature but it seems that BC has not a function to get it, but in Java do.
I want to precise that I use OpenPGP keys defined as RFC 4880 and not X509 or others.
I try to search on GitHub, this forum but i don't find anything about it.
Thanks for your help

A: I am using the same lib and could not find anything.
The PGP object has a property called Key ID but its just a negative number
Screenshot
Edit:
Nvm i think i found it https://csharp.hotexamples.com/examples/Org.BouncyCastle.Bcpg.OpenPgp/PgpPublicKey/GetFingerprint/php-pgppublickey-getfingerprint-method-examples.html


text:
Q: Which entry-wise $L_{p,q}$ matrix norms satisfy $\|\mathbf{A x} \|_l \le \|\mathbf{A}\|_{p,q} \|\mathbf{x} \|_l$? The following submultiplicative inequality holds when, e.g. $p=q=l=2$.
$$\|\mathbf{A x} \|_l  \le \|\mathbf{A}\|_{p,q} \|\mathbf{x} \|_l.$$
Here, $\mathbf{A}$ is a real square matrix, $\mathbf{x}$ is a real vector and $\|\mathbf{A}\|_{p,q}$ is the "entry-wise" $L_{p,q}$ matrix norm, not the induced norm.
Is there a general expression for $p, q$ and $l$ when the above inequality is true?

A: Here is at least a generalisation of your quoted result.
Let $c^i$ be the $i$th column of $A$, and let $y_i = \|c^i\|_l$, and $x'_i=|x_i|$. Then $\|y\|_k = \|A\|_{l,k}$, $\|x'\|_l=\|x\|_l$,and $Ax = \sum_i c^i x_i$, so
$$ \|Ax\|_l =\left\|\sum_i c^i x_i \right\|_l\le \sum_i |x_i|\|c^i\|_l = \langle x',y\rangle\le \|y\|_k \|x'\|_l = \|A\|_{l,k} \|x\|_l,$$
Where $k$ is the Holder conjugate of $l$, $\frac1l + \frac1k=1$. Also, using Minkowski's inequality like here, you should be able to show that $\|A\|_{p,q} \le \|A\|_{q,p}$ whenever $ q\ge p$. In addition, the $p$ norms are ordered in the sense that
$$ p\ge q \implies \|x\|_p \le \|x\|_q$$
So we have the following. For any $l$, $\|Ax\|_l \le \|A\|_{p,q}\|x\|_l$ for any $p,q$ in the rectangle $$1\le p\le l,   1\le q \le k$$
For $1\le l\le 2$, $k\geq2\ge l$ so by Minkowski we also have all the exponents in the 'mirror' rectangle
$$1\le p\le k,   1\le q \le l$$
I haven't thought about if this is optimal.

I'll leave this less useful calculation below. It proceeds by splitting into rows, which is not quite the definition of the $L^{l,k}$ norm.
Let $r^i$ be the $i$th row of $A$ i.e. $r^i_j = a_{ij}$. Then $(Ax)_i = r^i \cdot x$,
$$ \|Ax\|^l_l = \sum_i |r^i\cdot x|^l \leq \sum_i \|r^i\|^l_{k}\|x\|^l_l,$$
so that
$$\|Ax\|_l \leq \|A^{\top}\|_{{k,l}} \|x\|_l,$$
where again $k$ is the Holder conjugate.


text:
Q: How do I call ACPI control methods from C++ or C# on Windows? I'm getting tired of waiting for HP to fix the switchable graphics driver for my laptop, but I think I can switch GPUs myself by calling ACPI methods. The switching works using vga_switcheroo in Linux, which is open source, so I know what methods I need to call, but not how to call them.
The two methods I need to call are in the SSDT namespace, if that matters, and I also need to pass integer arguments.

A: Some links on similar problems (For example) say that this is possible only from kernel-mode driver under Windows. So to accomplish this I can think only of the following options:

*

*Writing entire videodriver by yourself - I doubt you will go this
way...

*Finding documentation on or reverse-engineering existing videodriver
for your GPU and issuing necessary commands via IOCTLs using
function DeviceIoControl (MSDN). Also not very reliable -
existing driver might not contain necessary functions/IOCTLs - but I
think it will be much easier than the first option.


text:
Q: ActionListeners and JButtons I'm trying write a program where I have 3 different buttons and when you click a button it changes the background of a panel in the frame.  I got my panel set up and everything is in the right place, but I need to have all my actionlisteners for my buttons all in one class.  I tried doing that but all the buttons change colors and not the background. Here's the code I have so far.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Kelle Schmitt
 */
public class BackgroundColorChooserFrame extends JFrame
{
    private static final int WIDTH = 300;
    private static final int HEIGHT = 300;

    private JLabel titleLbl;
    private JButton redBtn;
    private JButton greenBtn;
    private JButton blueBtn;
    private JButton quitBtn;

    public BackgroundColorChooserFrame()
    {
        createButton();
        createLabel();
        createPanel();

        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class ColorListener implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {
            redBtn.setBackground(Color.red);
            greenBtn.setBackground(Color.green);
            blueBtn.setBackground(Color.blue);
        }
    }

    public void createButton()
    {
        redBtn = new JButton("Red");
        greenBtn = new JButton("Green");
        blueBtn = new JButton("Blue");

        ActionListener colorlistener = new ColorListener();
        redBtn.addActionListener(colorlistener);
        greenBtn.addActionListener(colorlistener);
        blueBtn.addActionListener(colorlistener);
    }

    public void createLabel()
    {
        titleLbl = new JLabel("Background Color Chooser");
    }

    //create and add panels
    public void createPanel()
    {
        JPanel mainPnl, titlePnl, colorPnl, controlPnl;

        mainPnl = new JPanel();
        mainPnl.setLayout(new BorderLayout());
        titlePnl = new JPanel();
        colorPnl = new JPanel();
        controlPnl = new JPanel();

        mainPnl.add(titlePnl, BorderLayout.NORTH);
        titlePnl.add(titleLbl);
        mainPnl.add(colorPnl, BorderLayout.CENTER);
        mainPnl.add(controlPnl, BorderLayout.SOUTH);
        controlPnl.add(redBtn);
        controlPnl.add(greenBtn);
        controlPnl.add(blueBtn);

        //add the mainPnl to the parent frame
        add(mainPnl);

    }

}

Please help! Thanks!

A: Maybe something like:
public void actionPerformed(ActionEvent evt)
{
    JButton button = (JButton)evt.getSource();
    Component parent = button.getParent();

    if (button == redBtn)
        parent.setBackground( Color.RED );
    else if (...)
}

Although a much better solution is to create a separate ActionListener for every button so you don't use nested if/else logic:
public class ColorListener implements ActionListener
{
    private Color background;

    public ButtonListener(Color background)
    {
        this.background = background;
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        JButton button = (JButton)evt.getSource();
        Component parent = button.getParent();
        parent.setBackground( background );
    }
}

Then you can create an unlimited number of buttons and colors:
redButton.addActionListener( new ColorListener(Color.RED) );

The key point is in using the getSource() method so you can write generic code.


text:
Q: DynamoDB Enhanced - No result from query I have below two test cases implemented to test DynamoDB enhanced library.
Test case 1: Use Get Item on table "digital_form", with PK = "FORM#ABC123" and SK = "INFO#ABC123". which can return result
    @Test
    public void testGetItemWithPKSK() throws ExecutionException, InterruptedException {
        DynamoDbAsyncTable<DigitalFormDao> digitalformTable = dynamoDbEnhancedAsyncClient
                .table("digital_form", TableSchema.fromBean(DigitalFormDao.class));

        DigitalFormDao form = digitalformTable.getItem(
                Key.builder().partitionValue("FORM#ABC123").sortValue("INFO#ABC123").build()).get();

        System.out.println(form.getSk());
    }

Test case 2: Use Query on same table, with PK= "FORM#ABC123" and SK begin with "INFO". Supposely it will return set of result includes test case 1. However, no result is return.
    @Test
    public void testQueryWithPKandSKBegin(){
        DynamoDbAsyncTable<DigitalFormDao> digitalformTable = dynamoDbEnhancedAsyncClient
                .table("digital_form", TableSchema.fromBean(DigitalFormDao.class));

        PagePublisher<DigitalFormDao> digitalForms = digitalformTable.query(
                r -> r.queryConditional(
                    sortBeginsWith(k -> k.partitionValue("FORM#ABC123").sortValue("INFO"))));

        AtomicInteger atomicInteger = new AtomicInteger();
        atomicInteger.set(0);

        digitalForms.subscribe(page -> {
            DigitalFormDao digitalFormDao = (DigitalFormDao) page.items().get(atomicInteger.get());
            System.out.println(digitalFormDao.getSk());
            atomicInteger.incrementAndGet();
        });
    }

Is there some thing wrong in my Query statement?

A: Does this work?
public static void queryTableSortKeyBetween(DynamoDbEnhancedClient enhancedClient) {

        try {
            DynamoDbTable<Customer> mappedTable =
                    enhancedClient.table("DigitalForm", TableSchema.fromBean(DigitalFormDao.class));

            // Querying the sort key Name between two values
            Key key = Key.builder().partitionValue("FORM#ABC123").sortValue("INFO").build();

            QueryConditional queryConditional = QueryConditional.sortBeginsWith(key);

            PageIterable<DigitalFormDao> forms  =
                    mappedTable.query(r -> r.queryConditional(queryConditional));

            forms.stream()
                     .forEach(p -> p.items().forEach(item -> System.out.println(item.getCustName())));

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("Done");
}


text:
Q: location.href could not load new location? I need to redirect to new location when a button is clicked. I have used location.href=newloactionname.aspx but it doesn't move to new location. My code is:
function OpenUser(userID) {
    location.href = 'UserRegistration.aspx?userID=' + userID;
    alert(location.href)//shows only previous location
}

A: you can try:
window.location = 'UserRegistration.aspx?userID=' + userID;

instead...

A: See first if you have any javasript errors. Maybe your code does not calling OpenUser function.
Also try this:
//link click
window.location.href = "https://stackoverflow.com/";
OR
// HTTP redirect
window.location.replace("https://stackoverflow.com/");
I almost sure that you have an JS error somewhere. Press F12 on your browser.
Put an alert on the function. See if the alert appears.


text:
Q: How to save a YUV_420_888 image? I built my own camera app with the camera2 API. I started with the sample "camera2Raw" and I added YUV_420_888 support instead of JPEG. But now I am wondering how I save the images in the ImageSaver!?
Here is my code of the run method:
@Override
    public void run() {
        boolean success = false;
        int format = mImage.getFormat();
        switch(format) {
            case ImageFormat.RAW_SENSOR:{
                DngCreator dngCreator = new DngCreator(mCharacteristics, mCaptureResult);
                FileOutputStream output = null;
                try {
                    output = new FileOutputStream(mFile);
                    dngCreator.writeImage(output, mImage);
                    success = true;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    mImage.close();
                    closeOutput(output);
                }
                break;
            }
            case ImageFormat.YUV_420_888:{
                ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                FileOutputStream output = null;
                try {
                    output = new FileOutputStream(mFile);
                    output.write(bytes);
                    success = true;
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    mImage.close();
                    closeOutput(output);
                }
                break;
            }
            default:
                Log.e(TAG, "Cannot save image, unexpected image format:" + format);

        }
        // Decrement reference count to allow ImageReader to be closed to free up resources.
        mReader.close();

        // If saving the file succeeded, update MediaStore.
        if (success) {
            MediaScannerConnection.scanFile(mContext, new String[] { mFile.getPath()},
            /*mimeTypes*/ null, new MediaScannerConnection.MediaScannerConnectionClient() {
                @Override
                public void onMediaScannerConnected() {
                    // Do nothing
                }

                @Override
                public void onScanCompleted(String path, Uri uri) {
                    Log.i(TAG, "Scanned " + path + ":");
                    Log.i(TAG, "-> uri=" + uri);
                }
            });
        }
    }

I tried to save the YUV images like a JPEG, but that way I only get one plane and the saved data don't make any sense to me...
What is the correct way to save a YUV image? Convert it to RGB (what is the sense of YUV then?)? Or with YuvImage class?

A: Typically, you don't save a YUV image as a file, and as such there are no built in functions to do so. Moreover, there are no standard image format encodings for such YUV data. YUV is typically an intermediate form of data that is convenient for the camera pipeline and conversion into other formats afterwards.
If you're really intent on this, you can write the buffers for the three channels as unencoded byte data to a file and then open it elsewhere and reconstruct it. Make sure you save the other important information too, though, such as stride data. This is what I do. Here are the relevant lines from a file format switch statement I use, along with comments on the reasoning:
File file = new File(SAVE_DIR, mFilename);
FileOutputStream output = null;
ByteBuffer buffer;
byte[] bytes;
boolean success = false;

switch (mImage.getFormat()){

    (... other image data format cases ...)

    // YUV_420_888 images are saved in a format of our own devising. First write out the
    // information necessary to reconstruct the image, all as ints: width, height, U-,V-plane
    // pixel strides, and U-,V-plane row strides. (Y-plane will have pixel-stride 1 always.)
    // Then directly place the three planes of byte data, uncompressed.
    //
    // Note the YUV_420_888 format does not guarantee the last pixel makes it in these planes,
    // so some cases are necessary at the decoding end, based on the number of bytes present.
    // An alternative would be to also encode, prior to each plane of bytes, how many bytes are
    // in the following plane. Perhaps in the future.
    case ImageFormat.YUV_420_888:
        // "prebuffer" simply contains the meta information about the following planes.
        ByteBuffer prebuffer = ByteBuffer.allocate(16);
        prebuffer.putInt(mImage.getWidth())
        .putInt(mImage.getHeight())
        .putInt(mImage.getPlanes()[1].getPixelStride())
        .putInt(mImage.getPlanes()[1].getRowStride());

        try {
            output = new FileOutputStream(file);
            output.write(prebuffer.array()); // write meta information to file
            // Now write the actual planes.
            for (int i = 0; i<3; i++){
                buffer = mImage.getPlanes()[i].getBuffer();
                bytes = new byte[buffer.remaining()]; // makes byte array large enough to hold image
                buffer.get(bytes); // copies image from buffer to byte array
                output.write(bytes);    // write the byte array to file
            }
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            Log.v(appFragment.APP_TAG,"Closing image to free buffer.");
            mImage.close(); // close this to free up buffer for other images
            if (null != output) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        break;
    }

Because it can be up to the device exactly how the data is interlaced, it can be challenging to extract the Y,U,V channels from this encoded information later. To see a MATLAB implementation of how to read and extract a file like this, see here.

A: If you have the YuvImage object then you can convert it to Jpeg using the compressToJpeg function like so.
ByteArrayOutputStream out = new ByteArrayOutputStream();
YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
yuvImage.compressToJpeg(new Rect(0, 0, width, height), 50, out);
byte[] imageBytes = out.toByteArray();
Bitmap image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
iv.setImageBitmap(image);

You have to set the width and height of the image explicitly though.


text:
Q: If и JSON в С#? Как сделать проверку если не существует элемента в json ?
Есть json от стим веб апи(http://steamcommunity.com/market/priceoverview?appid=730&market_hash_name=...), который я получаю в своем проекте c#, обычно в json есть median_price, но иногда его нет(Например здесь есть - http://steamcommunity.com/market/priceoverview?appid=730&market_hash_name=Negev%20%7C%20Army%20Sheen%20%28Minimal%20Wear%29&format=json , а здесь нет http://steamcommunity.com/market/priceoverview?appid=730&market_hash_name=StatTrak™%20M4A4%20%7C%20Howl%20%28Field-Tested%29&format=json). Я бы хотел сделать проверку на его наличие.

A: Используйте JSON.Net, мой вам совет...
Берем JSON, который может быть и создаем на его основе класс:
public class Root
{
    public bool Success { get; set; }
    [JsonProperty("lowest_price")]
    public string LowestPrice { get; set; }
    public int Volume { get; set; }
    [JsonProperty("median_price")]
    public string MedianPrice { get; set; }
}

Обратите внимание на то, что название каждой переменной должно быть такое же, как и в JSON, но не всегда это красиво в коде и для этого мы указываем JsonProperty с именем, которое находится в JSON - это позволит нам назвать переменную как угодно.
Имея класс под наш JSON - мы можем сделать десериализацию:
var json = JsonConvert.DeserializeObject<Root>(StringData);

StringData - ответ от сервера, в виде String.
Ну и дальше спокойно работайте с данными. К примеру, если прочесть JSON с одним значением Success и вывести все данные на экран:
Console.WriteLine(json.Success);
Console.WriteLine(json.LowestPrice);
Console.WriteLine(json.Volume);
Console.WriteLine(json.MedianPrice);

То в ответ мы получим:

False
0

То есть говоря другими словами, при десериализации JSON - вы получите только те данные, которые есть в файле, остальное будет иметь NULL. И тут вы можете делать нужные вам проверки:
if (json.LowestPrice != null) //как пример...

В общем, в вашем случае не обязательно отслеживать есть ли на сервере это значение, или его нету. Главное правильно десериализовать!


text:
Q: While loop producing weird div behavior I have the following code running in my site. It is done to show items 2 by 2, with a line break every time an even number is gotten.
This is all within a DIV:
while($info = $items->fetch(PDO::FETCH_ASSOC))
{
echo "

";
echo "

".$info[name]."
 - $".$info[price]."
";
$row_count++;
if ($row_count % 2 == 0)
    {
echo "
"; // close the row if we're on an even record
    }

}

The problem is that my resulting CSS is doing something weird. It creates divs for the 1st 2 items and then it creates  tags for the following items, to the point that these come out of the container div where they should be loaded...
Any idea of why this could be happening?

A: Please try this :-
$html = '';
while($info = $items->fetch(PDO::FETCH_ASSOC))
{
    $html.= "

";

    $html.= "

       ".$info['name']."
        -$".$info['price']."
";

   $row_count++;
   if ($row_count % 2 == 0)
    {
      $html.= "
"; // close the row if we're on an even record
    }
}
 echo $html;


text:
Q: 50/50 lifeline in Who Wants To Be a Millionaire program Vb.net I'm currently writing a Who Wants To Be A Millionaire program and I can't seem to figure out a serious error in the code. Specifically the 50/ 50 lifeline. Whenever the correct answer is the first answer in the choices the program crashes. Otherwise if the correct answer is the 2,3 or 4th choice, it works fine.
I really don't know why it does this and my efforts of fixing it has been useless. I'm using an array to hold which choice is the correct choice for each answer.
correctanswer(i)
    Dim remove As Integer
        Dim remove1 As Integer
start:
        remove = CStr(Int(Rnd() * 4))
        If remove + 2 = correctanswer(i) + 1 Then
            GoTo start
        End If
start2:
    remove = CStr(Int(Rnd() * 5))
    If remove1 + 2 = correctanswer(i) + 1 Then
        GoTo Start2
    ElseIf remove1 = remove Then
        GoTo Start2
    End If
    Dim r1 As Button
    r1 = Me.Controls("cmdanswer" & remove + 1)
    r1.Enabled = False
    r1.Text = ""
    Dim r2 As Button
    r2 = Me.Controls("cmdanswer" & remove1 + 1)
    r2.Enabled = False
    r2.Text = ""

A: There's an infinite loop whenever remove1 + 2 = correctanswer(i) + 1.  It goes back to start2, then continues down to the if statement, then to start2, over and over. The value of remove1 and correctanswer(i) never change.


text:
Q: Laravel Route:dispatch create new session with EncryptCookie My code is :
…
$new_request = Request::create($page, 'GET', $request->all(), $request->cookie());
$router = Route::dispatch($new_request);
…

with middlewares
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,

The problem :
A new session is created on every request on Route::dispatch call (if I exit before, no session created, after a new session is created) : new Redis key with redis driver, or new file with file driver.
But everything working correctly, it just spam new sessions keys/files instead of keeping alway the same file.
If I remove the EncryptCookie, it fix the problem, only one file is used, no more file after each request...
How to fix that with EncryptCookies enabled ?

A: Problem fixed, the problem is the source code have :
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
and the request have these middleware too.
Using encrypt/startsession two times seem to do that.
The simple solution is to remove these middleware before the source code with Route:dispatch, but leave it in the Request.


text:
Q: Uncaught TypeError: Failed to construct 'URL': Invalid URL in chrome extension v3 when using messages Here is a minimal extension for chrome in v3:
manifest.json
{
  "manifest_version": 3,
  "name": "Test",
  "version": "1.0",
  "description": "Test extension",
  "icons": {
    "48": "dark.png"
  },
  "background": {
    "service_worker": "button.js"
  },
  "permissions": [
    "activeTab"
  ],
  "action": {
    "default_icon": "dark.png",
    "default_title": "Test"
  }
}

button.js
chrome.action.onClicked.addListener(tab => {
  console.log('clicked')
  chrome.tabs.sendMessage(tab.id, { value: false })
});

The API seems quite clear in the doc. So I don't understand why, when I press the plugin button, I get weird errors:
extensions.js:4187 Uncaught TypeError: Failed to construct 'URL': Invalid URL
    at ExtensionsErrorPageElement.onSelectedErrorChanged_ (extensions.js:4187:2827)
    at Object.runObserverEffect [as fn] (polymer_bundled.min.js:1:37568)
    at runEffectsForProperty (polymer_bundled.min.js:1:37087)
    at runEffects (polymer_bundled.min.js:1:36604)
    at ExtensionsErrorPageElement._propertiesChanged (polymer_bundled.min.js:1:52973)
    at ExtensionsErrorPageElement._flushProperties (polymer_bundled.min.js:1:26564)
    at ExtensionsErrorPageElement._flushProperties (polymer_bundled.min.js:1:51737)
    at ExtensionsErrorPageElement._invalidateProperties (polymer_bundled.min.js:1:51534)
    at ExtensionsErrorPageElement._setProperty (polymer_bundled.min.js:1:51459)
    at ExtensionsErrorPageElement.Object.defineProperty.set (polymer_bundled.min.js:1:24863)
onSelectedErrorChanged_ @ extensions.js:4187
runObserverEffect @ polymer_bundled.min.js:1
runEffectsForProperty @ polymer_bundled.min.js:1
runEffects @ polymer_bundled.min.js:1
_propertiesChanged @ polymer_bundled.min.js:1
_flushProperties @ polymer_bundled.min.js:1
_flushProperties @ polymer_bundled.min.js:1
_invalidateProperties @ polymer_bundled.min.js:1
_setProperty @ polymer_bundled.min.js:1
Object.defineProperty.set @ polymer_bundled.min.js:1

What am I missing?
This is on Chromium Version 100.0.4896.75 (Build officiel) snap (64 bits)

A: I had the same exception but with another reason.
So, i see the possible solution(how to get real error message).
I've set breakpoint on failed line and check the runtimeError message.
Can be usefull for somebody.

A: *

*Please remove node modules or take a clone of the repo in the new folder

*install node (npm install)

*npx cypress open

it works perfectly.


text:
Q: How can I tell what windows theme I'm using? I'm trying to make my application force a theme - this is straightforward as shown here: http://arbel.net/blog/archive/2006/11/03/Forcing-WPF-to-use-a-specific-Windows-theme.aspx
However, I don't know what theme I'm using now.  I'm using the Windows XP default theme, whatever that may be.  That article says

It's important to specify the version
  and the public key token

...where do I get that information?

A: To get the theme name you can call the unmanaged GetCurrentThemeName method:
public string GetThemeName()
{
  StringBuilder themeNameBuffer = new StringBuilder(260);
  var error = GetCurrentThemeName(themeNameBuffer, themeNameBuffer.Capacity, null, 0, null, 0);
  if(error!=0) Marshal.ThrowExceptionForHR(error);
  return themeNameBuffer.ToString();
}

[DllImport("uxtheme.dll", CharSet=CharSet.Auto)]
public static extern int GetCurrentThemeName(StringBuilder pszThemeFileName, int dwMaxNameChars, StringBuilder pszColorBuff, int dwMaxColorChars, StringBuilder pszSizeBuff, int cchMaxSizeChars);

You can find the version and public key token by right-clicking the theme .dll (such as PresentationFramework.Aero) in the GAC (open c:\Windows\Assembly in Exporer), or you can use code to do it.  Just loop through all loaded assemblies using AppDomain.CurrentDomain.LoadedAssemblies and find the one you want:
foreach(Assembly a in AppDomain.CurrentDomain.LoadedAssemblies)
  if(a.Name.StartsWith("PresentationFramework."))
    return a.FullName;

Note that looping through the loaded assemblies will also tell you the current theme name if only one theme has been loaded in the current AppDomain.


text:
Q: SQL Out of range value for column 'CGPA' at row 1 -- 1) Creating the table student
CREATE TABLE student (IDNO VARCHAR(11) NOT NULL PRIMARY KEY,
                      NAME VARCHAR(64) NOT NULL,
                      ROOM INTEGER,
                      HOSTEL CHAR(2),
                      CGPA NUMERIC (2,2) CHECK(CGPA < 10 and CGPA > 0));

-- Inserting the given data  CGPA DECIMAL(2,2) CHECK(CGPA < 10 and CGPA > 0)
INSERT INTO student VALUES('2000A3PS177', 'Raoul', 222, 'AK', 8.8);

INSERT INTO student VALUES('2001A7PS098', 'Kapil', 143, 'RM', 7.9);

INSERT INTO student VALUES('2000A7PS588', 'Sriram', 175, 'RP', 10.0);

INSERT INTO student VALUES('2001A7PS721', 'Nikhil', 112, 'RM', 9.2);

INSERT INTO student VALUES('2001A3PS588', 'Mouli', 121, 'BD', 7.5);

I have above code when i run get the below error:
Preparing...
Importing my_test.sql...
Finished executing script
ERROR 1264 (22003) at line 8: Out of range value for column 'CGPA' at row 1
Operation failed with exitcode 1
I have tried changing the value which i have entered or NUMERIC  to DECIMAL but no luck.
If i make below change it is working.
form
CGPA NUMERIC (2,2) CHECK(CGPA < 10 and CGPA > 0)

to
CGPA float

Can you please help to understand what i am missing here ?

A: Your problem is NUMERIC(2, 2).  This basically supports values from 0.00 to 0.99 -- two digits of precision.
I think you intend NUMERIC(4, 2) or NUMERIC(3, 2) in order to support digits before the decimal point.

A: Also In Addition to ans to understand  the concept below is helpful:
The DDL would look like this:
CREATE TABLE account (
accountNo integer,
balance numeric(8,2)
);
The "balance" column can safely store the number 173226.62.

Numerical, decimal Data Types in SQL
P- 8 (This is total decimal digit)
S- 2


text:
Q: How to suppress OpenCV error message I am writing an OpenCV project using g++ and opencv 2.4.6
I have some code like this:
try
{
    H = findHomography( obj, scene, CV_RANSAC );
}
catch (Exception &e)
{
    if (showOutput)
        cout<< "Error throwed when finding homography"<<endl;
    errorCount++;
    if (errorCount >=10)
    {
        errorCount = 0;
        selected_temp = -99;
        foundBB = false;
        bb_x1 = 0;
        bb_x2 = 0;
        bb_y1 = 0;
        bb_y2 = 0;
    }
    return -1;
}

Error will be thrown when the findHomography failed to find things. The error message includes:
OpenCV Error: Assertion failed (npoints >= 0 && points2.checkVector(2)
== npoints && points1.type() == points2.type()) in findHomography,
file /Users/dji-mini/Downloads/opencv- 2.4.6/modules/calib3d/src/fundam.cpp,
line 1074
OpenCV Error: Assertion failed (count >= 4) in cvFindHomography,
file /Users/dji-mini/Downloads/opencv-2.4.6/modules/calib3d/src/fundam.cpp, line 235

Since I know under what conditions the message would appear, I want to suppress these error messages. But I don't know how to do it.
In old version of OpenCV, there seems to have a "cvSetErrMode", which, according to other articles, is depreciated in OpenCV 2.X.
So what function can I use to suppress OpenCV error messages?

A: cv::error() is called on every occurrence of an assertion failure. The default behavior is to print the assertion statement to std::cerr.
You can use the undocumented cv::redirectError() function to set a custom error-handling callback. This will override the default behavior of cv::error(). You first need to define a custom error-handling function:
int handleError( int status, const char* func_name,
            const char* err_msg, const char* file_name,
            int line, void* userdata )
{
    //Do nothing -- will suppress console output
    return 0;   //Return value is not used
}

And then set the callback before the code which throw:
    cv::redirectError(handleError);

try {
    // Etc...

If at any point you wish to restore the default behavior, you can do so:
cv::redirectError(nullptr);    //Restore default behavior; pass NULL if no C++11


text:
Q: pixel/sandbox simulator optimizations I've been working on this project for a few days now, it's a pixel simulator, and the only element I have right now is sand. I'm in the process of fine tuning the physics for sand as a base for other elements. I've noticed something though, the program starts to slow down significantly after placing sand for a while, and I'm looking for any improvements or things I could do differently in my code to make it run better. Any help is appreciated. Thanks!
Code for the main file:

let alter = true;

particles = []

function setup() {
  let canvas = createCanvas(windowWidth, windowHeight);
  frameRate(120);
}

function sandColor() {
  r = Math.floor(Math.random() * (255 - 230 + 1) + 230)
  g = Math.floor(Math.random() * (230 - 200 + 1) + 230)
  b = Math.floor(Math.random() * (150 - 130 + 1) + 130)
  return color(r, g, b)
}

function drect(c, x, y, l, w) {
  noStroke();
  fill(c);
  rect(x, y, l, w);
}

class Particle {
  constructor(p, c, x, y, s) {
    this.p = p;
    this.c = c;
    this.x = x;
    this.y = y;
    this.s = s;
  }

  draw() {
    drect(this.c, this.x, this.y, this.s, this.s);
  }
}

function check(x, y) {
  found = false;
  let p;
  for (i in particles) {
    if (particles[i].x == x && particles[i].y == y) {
      found = true;
      p = particles[i].p;
    }
  }
  if (found) {
    return [found, p]
  } else {
    return [found];
  }
}

function draw() {

  drect(color(37, 150, 190), 0, 0, windowWidth, windowHeight)

  tw = 4;
  th = 4;

  for (var i in particles) {
    particles[i].draw()
  }

  alter = !(alter)
  if (!alter) {

    for (i in particles) {
      if (particles[i].p == 's') {
        let down = false
        if (!check(particles[i].x, particles[i].y + 4)[0]) {
          particles[i].y += 4;
          down = true;
        }
        if (!down) {
          let r = Math.floor(Math.random() * 2) + 1;
          if (r == 1) {
            if (!check(particles[i].x - 4, particles[i].y + 4)) {
              particles[i].y += 4;
              particles[i].x -= 4;
            } else {
              if (!check(particles[i].x + 4, particles[i].y + 4)) {
                particles[i].y += 4;
                particles[i].x += 4;
              }
            }
          }
        }
      }
    }

    if (mouseIsPressed) {
      for (let i = 0; i < 6; i++) {
        for (let j = 0; j < 6; j++) {
          let p = 's'
          let c = sandColor()
          let x = (Math.floor(mouseX / tw)) * tw + (i * 4) - 9;
          let y = (Math.floor(mouseY / th)) * th + (j * 4) - 9;
          let s = 4;

          let sand = new Particle(p, c, x, y, s)
          let d = true;
          for (var m in particles) {
            if (particles[m].x == x && particles[m].y == y && particles[m].p == "s") {
              d = false;
            }
          }
          if (d) {
            drect(c, x, y, s, s)
            particles.push(sand)
          }
        }
      }
    }
  }
}

function windowResized() {
  resizeCanvas(windowWidth, windowHeight);
}

document.addEventListener('contextmenu', event => event.preventDefault());
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.2/p5.min.js"></script>

Hosted example and full source code here: https://replit.com/@LoganStottle202/pixsim?v=1

A: a normal for() loop is 6 to 11 times faster than a for( in ) loop
Here's your current code:
function check(x, y) {
  found = false;
  let p;
  for (i in particles) {
    if (particles[i].x == x && particles[i].y == y) {
      found = true;
      p = particles[i].p;
    }
  }
  if (found) {
    return [found, p]
  } else {
    return [found];
  }
}

and I would also remove some unnecessary variables (they can be replaced with a return)
One more thing I would change, in javascript if you remove brackets from a for() loop or if() statement, it will only do the next statement. And that's something you can do here
I would do this:
function check(x, y) {
  for (let i = 0; i < particles.length; i++)
    if (particles[i].x == x && particles[i].y == y)
      return [true, particles[i].p];
  return [false];
}

benefits:

*

*Faster

*Easy to read

*Less text, smaller file


text:
Q: How to append all the elements with the same id in a pandas dataframe row? I have the below pandas dataframe, and I would like to transform into a sequence of elements into a single column without losing the temporal order of the id and fruit column.
id   fruit
---|------
101  apple
102  apple
101  watermelon
101  orange
102  orange
104  lemon
105  lemon
104  lemon
105  apple
103  grapes

For example, the new dataframe should look like this (*):
id               col
101  apple, watermelon, orange
102  apple, orange
103  grapes
104  lemon, lemon
105  apple

I tried to:
f = {'url' : lambda x: np.unique(x).tolist()}
df = df.groupby('id', as_index=False).agg(f).reindex(columns=df.columns)

def foo(row):
    #just to remove the brackets
    return ', '.join(row)

df4['url'] = df4['fruit'].apply(tweak)
df4

However, although this is working when I do:
list(df.loc[[362]]['fruit'])

The collected information in each row is not temporally sorted (following the order of appearance order of the fruit column). Thus, how can I get (*)?

A: apply join with set
df.groupby('id').fruit.apply(lambda x : ','.join(set(x))).reset_index()
Out[82]:
    id                    fruit
0  101  apple,watermelon,orange
1  102             apple,orange
2  103                   grapes
3  104                    lemon
4  105              apple,lemon

A: You'll need groupby + unique, followed by agg.
df.groupby('id').fruit.unique().agg(', '.join).reset_index()

    id                      fruit
0  101  apple, watermelon, orange
1  102              apple, orange
2  103                     grapes
3  104                      lemon
4  105               lemon, apple

Note that data within groups are not reordered, even if the groups are. If you don't want to sort the groups either, use sort=False.
df.groupby('id', sort=False).fruit.unique().agg(', '.join).reset_index()

    id                      fruit
0  101  apple, watermelon, orange
1  102              apple, orange
2  104                      lemon
3  105               lemon, apple
4  103                     grapes


text:
Q: How to manage asynchronous mouse events in Javascript I have JavaScript code where:

*

*When the user presses the left mouse button, a mousedown event is fired, which triggers a call to function OnMouseDown.

*When the user releases the left mouse button, a mouseup event is fired, which triggers a call to function OnMouseUp.

The two events are fired asynchronously.
For example, the mouseup event can be fired immediately after the mousedown event is fired (short mouse click), before the OnMouseDown ends. (Figure1)
I want to process the events sequentially, where the function OnMouseUp will only start after OnMouseDown ends.
I can achieve this by preventing the mouseup event from firing until after OnMouseDown ends (by calling removeEventListener('mouseup', OnMouseUp) when OnMouseDown begins) (Figure2)
But then I may lose a mouseup event altogether (Figure3)
Figure3 - mouseup event is lost
I am looking for a way to insure that

*

*a mouseup event after a mousedown event is not lost, and

*the OnMouseUp function begins after OnMouseDown ends.

How can I achieve this?
The following code example demonstrates the problem:

function sleep1 () {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve("Finished sleeping");
    }, 2000);
  });
}

// The mousedown event is fired when a pointing device button (usually a mouse button) is pressed on an element.
document.addEventListener('mousedown', async function(e) {
    console.log('BEG OnMouseDown');
  let retval = await sleep1();
  console.log('retval: ', retval);
    console.log('END OnMouseDown');
});

// The mouseup event is fired when a pointing device button (usually a mouse button) is released over an element.
document.addEventListener('mouseup', function(e) {
    console.log('BEG OnMouseUp');
    console.log('END OnMouseUp');
});

Clicking on the left mouse button and releasing results in the following printout, which shows that the function OnMouseUp ends before the function OnMouseDown ends, which fits figure1.
BEG OnMouseDown
BEG OnMouseUp
END OnMouseUp
Inside OnMouseDown:  Finished sleeping
END OnMouseDown

A: You can try async await,
Define an async function then use await keyword on the mouswdown event, it will not fire the next event untill the the async function is done

A: What i'm understanding is that you want to record events in the sequence they have fired.
Please check this solution:

// The mousedown event is fired when a pointing device button (usually a mouse button) is pressed on an element.
var ismousedown = false;
document.addEventListener('mousedown', function(e) {
        e.preventDefault();
        ismousedown = true;
    console.log('BEG OnMouseDown');
});

// The mouseup event is fired when a pointing device button (usually a mouse button) is released over an element.
document.addEventListener('mouseup', function(e) {
    e.preventDefault();
    if(ismousedown){
    ismousedown = false;
    console.log('BEG OnMouseUp');
    }
});

Is this what you're looking for? There is something else i have missed?

A: I solved the problem by:

*

*implementing a sleep based on here

*introducing a flag onMouseDownStillProcessing that is set to false/true at the beginning/end of OnMouseDown, respectively.

*waiting in the beginnning of OnMouseUp for onMouseDownStillProcessing to become true.


text:
Q: Get location of view passed into laravel view composer Is it possible to get the location of a view that is passed into a Laravel view composer?
View::composer('*', function($view) {
   // I want to find out the location of the view file here
   // e.g. master.something.header
   // then add this to an array
   $loadedViews = View::share("loadedViews");
   $loadedViews[] = $thisViewName;
});

The reason is that I want to have a variable that will be shared between views and contain an array of all the views that are loaded. Any css and js files will be located in directory structure that matches the views one.
This means I can then have a css and js view which then include the required css and js files for the views on the page. All css and js will be directly linked to a specific view.
If there is already a way to do this, or a way to get a list of loaded views, please let me know!

A: $view->getName() was the answer that I wanted.
$view->getPath() is the actual path to the file.


text:
Q: HSSF How to write result in Excel by using Constant Int column number I'm new to Java and Selenium, Selenium is quite fun, I'm working on Selenium WebDriver with TestNG Data Driven framework.
by refer to this tutorial
http://software-testing-tutorials-automation.blogspot.sg/2014/07/framework-for-selenium-webdriver-report.html#comment-form
there is a Excel Utility where write data to excel with using HSSF

SuiteUtility.WriteResultUtility(FilePath, TestCaseName, "Pass/Fail/Skip", DataSet+1, "PASS");

Instead of hardcode, I'm planning to using Constant file to replace it. eg,

public static final String KEYWORD_PASS = "PASS";
  public static final int COL_TEST_CASE_RESULT = 10; // put it in column no 10

so it will be like these and become more manageable

SuiteUtility.WriteResultUtility(FilePath_TestResult, TestCaseName, Constant.COL_TEST_CASE_RESULT, DataSet+1, Constant.KEYWORD_PASS);

My question is how to modify the code below so I can change the String colName to int column number.

public boolean writeResult(String wsName, String colName, int rowNumber, String Result){
 try{
  int sheetIndex=wb.getSheetIndex(wsName);
  if(sheetIndex==-1)
   return false;
  int colNum = retrieveNoOfCols(wsName);
  int colNumber=-1;
  HSSFRow Suiterow = ws.getRow(0);
  for(int i=0; i<colNum; i++){
   if(Suiterow.getCell(i).getStringCellValue().equals(colName.trim())){
    colNumber=i;
   }
  }
  if(colNumber==-1){
   return false;
  }
  HSSFRow Row = ws.getRow(rowNumber);
  HSSFCell cell = Row.getCell(colNumber);
  if (cell == null)
      cell = Row.createCell(colNumber);
   cell.setCellValue(Result);
   opstr = new FileOutputStream(filelocation);
   wb.write(opstr);
   opstr.close();
 }catch(Exception e){
  e.printStackTrace();
  return false;
 }
 return true;
}

A: public  void setData(String adr,String sht,int rn,int cn,String val) throws Exception{

    FileInputStream fsIP= new FileInputStream(new File(adr)); //Read the spreadsheet that needs to be updated

    XSSFWorkbook wb = new XSSFWorkbook(fsIP); //Access the workbook

    XSSFSheet worksheet = wb.getSheet(sht); //Access the worksheet, so that we can update / modify it.

    Cell cell = null; // declare a Cell object

    cell = worksheet.getRow(rn).getCell(cn);   // Access the second cell in second row to update the value

    cell.setCellValue(val);  // Get current cell value value and overwrite the value

    fsIP.close(); //Close the InputStream

    FileOutputStream output_file =new FileOutputStream(new File(adr));  //Open FileOutputStream to write updates

    wb.write(output_file); //write changes

    output_file.close();  //close the stream
}

It might be helped.


text:
Q: ¿Cómo hacer un if según 3 veces cliqueado un botón? ¿Cómo hacer un if/else, según cada 3 veces que se apriete un botón con cierta ID? ¿Y cómo hacer que cada una de las veces me muestre un alert?
Mi intento:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input id="play"onclick="start()"type="button" value="Jugar">
<input id="replay"type="button" value="volver a jugar">
<script>
function start(){
    var i = 0;
    var b = "";

    window.addEventListener("load", each3);

    function each3() {
        b = document.getElementById("play").addEventListener("click", contador);

        function contador() {
            i = i + 1;
        }

        if (i == 3) {
            alert('yay!');
        }
    }
}
</script>

</body>
</html>

Deseo solamente una solución en JavaScript.

A: Para realizar una acción cada 3 veces que se pulse un botón no tienes más que crearte un contador e ir actualizándolo en el evento click.
Mira este ejemplo:

(function(){
  var contador = 0;

  document.getElementById('play').addEventListener('click',
    function(){
      if (contador === 2){
        alert('Tercera vez que se pulsa el botón');
        contador = 0;
      }
      else{
        contador++;
      }
    });
})();
<input id="play" type="button" value="Jugar">

A: La solución de Asier Villanueva es la óptima, pero yo he intentado moldear tu código y hacerlo como tú quieres:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input id="play"onclick="start()"type="button" value="Jugar">
<input id="replay"type="button" value="volver a jugar">
<script>
function start(){

 i = 0;
 b = "";

document.getElementById("play").removeAttribute("onclick");
document.getElementById("play").setAttribute("onclick","contador()");
}

function contador() {

i = i + 1;

if (i == 3) {

alert('yay!');
}

}

</script>
</body>
</html>

</script>

</body>
</html>

A: He estado un momento intentando leer tu código y debo admitirlo, me resultó un poco ambiguo, porque hay como unas funciones muy simples y mucho espacio en blanco. Voy a ver si he entendido lo que quieres lograr.
Por lo que entiendo de tu enunciado, quieres que cada 3 veces que hagas click en un botón tome cierta acción, que en este caso es un alert().
Tienes tres funciones escritas pero solo te bastaría una para conseguir lo que tu quieres lograr, esto se podría llamar refactorización en este caso, porque estamos simplificando nuestro código para obtener las mismas funcionalidades que teníamos antes con un menor coste de recursos.
1 - Antes que nada, comentarte que el objeto window dispone de un método llamado onLoad(), el cual lo que suceda dentro de su bloque de código, lo hará después de cargar la estructura de tu DOM. Así podemos deshacernos de ese primer Listener que tienes para cargar, se quedaría así:
window.onload = loadEvents; // Cabe destacar que no hace falta declararla con ()

function loadEvents() {
   // Accion a realizar al cargar el DOM
   var contador = 0; //Nuestra variable que recogerá los clicks del botón.
   playButton = document.getElementById('play');
   // Guardamos nuestro botón en una variable para acceder a ella.
}

2 - Vale, con nuestra función de carga escrita y conseguido acceder a nuestro botón, podemos disponernos a conseguir la interacción con ese botón:
function loadEvents() {
   var contador = 0;
   playButton = document.getElementById('play');
   //Se puede añadir el Listener a la variable para mejor legibilidad.
   playButton.addEventListener('click', cuentaClicks, false);

}

3 - Nuestra función cuentaClicks esta declarada en el Listener pero no codificada, así que vamos a ello:
function cuentaClicks() {

   if (contador < 3) {
     contador++; // Esto es similar a => contador = contador + 1
    } else {
        alert('yai!'); //Después de tres clicks se muestra nuestro alert()
        contador = 0; // Reiniciamos el contador para usarlo de nuevo.
    }
}

4 - Nuestro código final quedaría así:
<script>
 window.onload = loadEvents;

  function loadEvents() {

   var contador = 0; // Variable global que utilizaremos de contador

   playButton = document.getElementById('play');
   //Se puede añadir el Listener a la variable para mejor legibilidad.
   playButton.addEventListener('click', cuentaClicks, false);

}

function cuentaClicks() {

   if (contador < 3) {
     contador++; // Esto es similar a => contador = contador + 1
   } else {
        alert('yai!'); //Después de tres clicks se muestra nuestro alert()
        contador = 0; // Reiniciamos el contador para usarlo de nuevo.
    }
}

</script>

5 - ¡Un saludo! y espero que respondas si te ha funcionado o no :)


text:
Q: Find the number of times a value of an object property occurs in an array I have an array
const arr = [{
    name:'john',
    class:'tenth'
},
{
    name:'josh',
    class:'ninth'
},
{
    name:'ajay',
    class:'tenth'
}]

How to find out how many times ninth and the tenth has occurred in the array. But with the use of a single function so that I can have the data of the students of each class and show when my page is loaded.
e.g.:
X- 2
IX- 1
XII- 9

etc

A: Example is below

const arr = [
  {
    name:'john',
    class:'tenth'
  },
  {
    name:'josh',
    class:'ninth'
  },
  {
    name:'ajay',
    class:'tenth'
  }
];

// Create function to return number of matched classes
// *** We can't use word `class` as function parameter,
// so we use `cls` here
const getClass = (cls) => {
  // Match var
  let mTimes = 0;
  // Loop arr
  for(let i = 0; i < arr.length; i++) {
    // If matches request, count
    if(arr[i].class === cls) mTimes++;
  }
  return mTimes;
}

// Use
console.log(getClass('tenth'));

A: Here is what you want:

const arr = [{
    name: 'john',
    class: 'tenth'
},
{
    name: 'josh',
    class: 'ninth'
},
{
    name: 'ajay',
    class: 'tenth'
}
];

console.log([...arr.reduce((a, c) => {
    if (a.has(c.class)) {
        a.get(c.class).count++;
    } else {
        a.set(c.class, { class: c.class, count: 1 });
    }
    return a;
}, new Map()).values()]);

A: you can try with next function. Sorry formatting not working on phone..

Function groupBy(arr, prop) {
   const map = new Map(Array.from(arr, obj => [obj[prop], []]));
}

arr.forEach(obj => map.get(obj[prop]).push(obj));
    return Array.from(map.values());
}

console.log(groupBy(data, "class"));

A: You could use forEach I have used rank as a key instead of class

var g={}
var count = 1
 const arrx = [{ name:'john',rank:'tenth' }, { name:'josh', rank:'ninth' }, { name:'ajay', rank:'tenth' }, { name:'steph', rank:'tenth' }, { name:'nick', rank:'tenth' }, { name:'ajay', rank:'ninth' }, { name:'ajay', rank:'ninth' }, ]
  arrx.forEach(o => {
    g[o.rank] = g[o.rank]||count
    g[o.rank] = count++
  })
  console.log(g)

A: Array.prototype.reduce

const arr = [{
    name: 'john',
    className: 'tenth'
  },
  {
    name: 'josh',
    className: 'ninth'
  },
  {
    name: 'ajay',
    className: 'tenth'
  }
]

function groupByClassName(arr) {
  return arr.reduce((cum, cur) => {
    if(!cum[cur.className]) cum[cur.className] = 0;
    cum[cur.className]++;
    return cum;
  }, {})
}

console.log(groupByClassName(arr));