text:
Q: Matching the two list of lists of different size and return the difference I have two lists:
l1=[[12,3,C,-],[10,2,A,-]]
l2=[[8,3,X,W],[15,2,Y,W],[16,2,X,W],[17,3,V,W],[20,2,Z,W],[21,1,V,W].......]

Now i want to compare these two lists and fetch unmatched part from l2 into new list.I mean to say it should match l1[1] with the field l2[1] and return not matched list.
Matching means when the element in 2nd position of the sublist of l1 compared to the same position in the sublists of l2 it should be neglected and whatever doesn't match must be returned. Actually i have to iterate over both lists to get the comparison element. e.g. 3,2 in l1 and upon comparison it should return the sublist with second position element 1.
This is my approach:
l3=[x for x in l2 if x[1] not in l1[1]]

But it's returning me even the matched part also.What is wrong with it?

A:
Matching means when the element in 2nd position of the sublist of l1
  compared to the same position in the sublists of l2 it should be
  neglected and whatever doesn't match must be returned.

Consider Adding the above statement in your comment to your question
Reduce your first list to a list of key elements. In case, your list is considerable bigger, make it a set
Traverse your second list and filter it by comparing with the reduced list using membership operator
>>> l1=[[12,3,'C','-'],[10,2,'A','-']]
>>> l2=[[8,3,'X','W'],[15,2,'Y','W'],[16,2,'X','W'],[17,3,'V','W'],[20,2,'Z','W'],[21,1,'V','W']]
>>> key = set(e[1] for e in l1)
>>> [e for e in l2 if e[1] not in key]
[[21, 1, 'V', 'W']]

A: l1=[[12,3,C,-],[10,2,A,-]]
l2=[[8,3,X,W],[15,2,Y,W],[16,2,X,W],[17,3,V,W],[20,2,Z,W],[21,1,V,W]]

You're approach was close but you want to use the map function to create a list of the second elements in l1
l3=[x for x in l2 if x[1] not in map( lambda y: y[1], l1) ]

Note map takes a function and a sequence and returns a list of the function results when applied to each member of the sequence (i.e. the second element of each sublist in l1).  If l1 is very large you can make a set of the second elements which will remove duplicates and make membership checking O(1).
l1set = set( map( lambda y: y[1], l1) )

then the creation of l3 would look like this,
l3=[x for x in l2 if x[1] not in l1set ]


text:
Q: Dynamically add textbox and assign it's value from a function I want to create n number of textboxes dynamically based upon the user input.
Each textbox must populate with a serial number.Here, what I have tried so far.
function generateSerial(sender,eventArgs){
        debugger;
        //var rw_Serail = stockin.rw_Serail;
        if(eventArgs.get_newValue()!="0"){
            if(eventArgs.get_newValue()!=eventArgs.get_oldValue()){
                create(eventArgs.get_newValue());
                //OpenWindow(null,null,"rw_Serial");
            }
        }
    }

Create will call a function and it's job is to create textboxes and assign a value.
function create(param) {
        debugger;
        var s= "";
        for(var i = 0; i < param; i++) {
            s+= `<input type="text" style="width:72%" name="txtSerial" value=${generateLicense()}>`
                   `<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML
        }
        document.getElementById("dvserialNo").innerHTML=s;
    }

as name suggests generateLicense() will return a serial number..
function generateLicense() {
   return "abcd1234Etc..";
}

Now while running this code, I am getting this error..
In chrome

Uncaught TypeError: generateLicense(...) is not a function

In firefox
TypeError: (("<input type=\"text\" style=\"width:72%\" name=\"txtSerial\" value=" + (intermediate value)) + ">") is not a function

Note: I want to create and assign it's value at the same time.

A: Concatenate the two elements in s+. And, of course, as one of the answers suggested include quotes for value="${generateLicense()}"
s+= `<input type="text" style="width:72%" name="txtSerial" value="${generateLicense()}">`
 + `<button type="button" style="margin-left: 5px;height: 24px;">Change</button>`; //Create one textbox as HTML

redpajama_set_name: RedPajamaStackExchange


text:
Q: changing startup page I added one new new page to my dotnetnuke application,now i want to cahnge my newly created page as default startup page for my dotnetnuke website. Please tell me how to change the page..

A: Log into your portal, go to Admin > Site Settings > Advanced Settings, and find your page in the Home Page dropdown.


text:
Q: Airflow cron not running in timezone I have airflow setup with default_timezone = US/Eastern. If I set a DAG with schedule_interval="0 17 * * *" it runs at 12pm instead of the expected 5pm. I understand that airflow stores all dates as UTC. How can I get something to run in my timezone instead of writing the interval in UTC?
I have also tried setting the tzinfo in the dag's start_date to pendulum.timezone('US/Eastern') with no luck.

airflow=1.10.0
rhel7
python=3.6
server's tz = EST


text:
Q: Production Kafka configuration in Lagom Framework with Kubernetes? How to configure kafka cluster in lagom framework in kubernetes in production mode.
Its expecting kafka_native service while starting service container.
Cassandra cas_native successfully configured but kafka not working

A: As you are using Kubernetes you can use service locator DNS and take advantage of Kube DNS Service... You have to have a headless service in front of  Kafka...


text:
Q: database schema name in persistence.xml I wanted to know what is the way to mention database schema name in persistence.xml file.
Here is my file.
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
             version="1.0">
    <persistence-unit name="ORDER"
                      transaction-type="RESOURCE_LOCAL">
        <provider>
        org.eclipse.persistence.jpa.PersistenceProvider
    </provider>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                      value="oracle.jdbc.OracleDriver"/>
            <property name="javax.persistence.jdbc.url"
                      value="xyzurl"/>
            <property name="javax.persistence.jdbc.password" value="YYYYY"/>
            <property name="javax.persistence.jdbc.user" value="XXXX"/>
        </properties>
    </persistence-unit>
</persistence>

The schema name is testdta.
Any inputs will be helpful.

A: Specify your schema name in against the javax.persistence.jdbc.user property.
<property name="javax.persistence.jdbc.user" value="testdta"/>
<property name="javax.persistence.jdbc.password" value="schema password"/>

In case you are not aware, specify the datasource URI here:
<property name="javax.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:service"/>

A: Have a look at this link. This page explains how you can create persistence.xml for an Oracle database.
https://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cfgdepds005.htm
Here is an example for toplink.jdbc.user property: (It is in TopLink of course!)
<properties>
    <property name="toplink.logging.level" value="INFO"/>
    <property name="toplink.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
    <property name="toplink.jdbc.url" value="jdbc:oracle:thin:@myhost:l521:MYSID"/>
    <property name="toplink.jdbc.password" value="tiger"/>
    <property name="toplink.jdbc.user" value="scott"/>
</properties>

Here, scott is the schema used for connecting to database.


text:
Q: What is the benefit of using Animator.StringtoHash("")? Why should you use Animator.StringToHash("") while you can use animator component with strings?

A: Animator.StringToHash is used for optimization purposes. Comparing two ints is faster than comparing two strings.
This is mostly used when comparing many animation state. Animator.StringToHash will convert the name of the animator(string) to an id(int). You can them compare animation state with integers instead of strings.
You can learn more about this here.


text:
Q: size inputs must be scalar can someone please explain me how can I fix the error "size inputs must be scalar"? When I run the code in matlab it works correctly but when i run the compiled exe I obtain this error:

Error using randperm
Size inputs must be scalar.
Error in randsample (line 162)
Error in 'mycode' (line
  .'indexesWith0=randsample(1:n-sumboo,nToAnalyze-sumboo); % '..)
MATLAB:NonScalarInput

nToAnalyze=options.nToAnalyze;
if isempty(nToAnalyze)
    Exclude='';
else
    if nToAnalyze >n
        error(['nToAnalyze must be smaller or equal than ' num2str(n)])
    end
    boo=double_y ==1; %
    notboo=~boo; %
    sumboo=sum(boo); %
    seq=1:n;  %

      indToExtractWith0=seq(notboo); % indexes of units which have 0
      indexesWith0=randsample(1:n-sumboo,nToAnalyze-sumboo); %
      UnitsToAnalyzeWith0=indToExtractWith0(indexesWith0); %
      UnitsToanalyze=[seq(boo) UnitsToAnalyzeWith0]; %
      Exclude=setdiff(seq,UnitsToanalyze); %
end

thank you

A: According to the MATLAB help there are two ways of using randsample with two input arguments:

y = randsample(n,k) returns a k-by-1 vector y of values sampled
  uniformly at random, without replacement, from the integers 1 to n.
y = randsample(population,k) returns a vector of k values sampled
  uniformly at random, without replacement, from the values in the
  vector population. The orientation of y (row or column) is the same as
  population.

So it's legal to supply a vector for the first argument, n, but not for the second one, k.
If you look inside the randsample function (type edit randsample) and go to line 162 you can see that the command that actually throws this error is
y = y(randperm(k));

where k is the second argument to randsample. So it looks as if somehow, when you run the compiled code, you're ending up with a value for nToAnalyze-sumboo that is a vector, not a scalar, and you just haven't replicated this case when you test your code in the editor.
This could happen if options.nToAnalyze is a vector; it could also happen if double_y is a matrix (dimension 2 or higher) as boo will then have the same dimension and sum(boo) will have one dimension less. Check the rest of your code to figure out where either of these could be happening.


text:
Q: How to use explain() in Node.js mongoose I am trying to see The executionStats on my console but I always get undefined or [object, object]. I just have a simple query where I want to see some stats. Can someone explain why this isn't working? If I just use my query for querying (while not using explain()) the query is successful.
This is my query when trying to use explain with all the other code. I want to see the performance of the query so I found out that the best way to get the performance time is by using explain().
  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

And this is my query code where I can sucssessfuly get data and show them on my page
  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

conn.collection('galery').find({ "user_id": req.session.userId}).toArray( (err, resultImg) =>{
.
.
.
});

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

This is my output of MongoDB Debug:
MongoDebug:  {
  queryPlanner: {
    plannerVersion: 1,
    namespace: 'nodejsnosql.galerija',
    indexFilterSet: false,
    parsedQuery: { uporabnik_id: [Object] },
    winningPlan: { stage: 'COLLSCAN', filter: [Object], direction: 'forward' },
    rejectedPlans: []
  },
  executionStats: {
    executionSuccess: true,

    nReturned: 3,
    executionTimeMillis: 0,
    totalKeysExamined: 0,
    totalDocsExamined: 5,
    executionStages: {
      stage: 'COLLSCAN',
      filter: [Object],
      nReturned: 3,
  ok: 1,
  '$clusterTime': {
    clusterTime: new Timestamp({ t: 1644428067, i: 1 }),
    signature: {
      hash: new Binary(Buffer.from("71a216b111009bfcef6bd4923029d8df7a219e1a", "hex"), 0),
      keyId: new Long("7027534341366349828")
    }
  },
  operationTime: new Timestamp({ t: 1644428067, i: 1 })
}

A: You need to change how you are logging the explain object to console.
      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

By using 'MongoDebug: ' + explain[0] you are implicitly calling .toString() on explain[0] as you are appending it to a string, so it must be a string. For objects, this converts them to [object, Object].
Instead you can pass it as a separate object to your console.log:
console.log('MongoDebug: ', explain);

Or convert it to JSON with extra spacing for better readability:
console.log(JSON.stringify(explain, null, 2));


text:
Q: Show and Hide Div for the text that comes dynamically I have a problem where we have to show/hide some text in the product description in the product detail page. The description has to be shortened upto desired number of lines and by clicking on "more" complete description is to be shown. I taken the following script from the link below:

Using javascript substring() to create a read more link

And the code is as follows:

But with the above script the entire description is converting into text format. But since the description contains unordered lists,header tags etc. it is not considering those. How to modify the above script to display the content as it is.

A: Use html() instead of text(). like this
var text = $('div.contentdetail').html();
var rest = $('div.contentdetail').html().substring(cutoff);

Rest is all correct. text() converts all html node data in pure text. html() preserves it. Give it a go, worked for me. In the previous link the problem was only for text. Since you have other elements like links and other stuff, you need to use html()


text:
Q: How to fix the ubuntu file system /dev/sda error? I encountered this error on my Ubuntu machine:
The root filesystem on /dev/sda1 requires a manual fsck

I launched the command
fsck -fy /dev/sda1

and the system has done operations on the filesystem but at the end of the procedure the system does not start but remains on the following screen:
/dev/sda1: THE FILE SYSTEM WAS MODIFIED

/dev/sda1: 603235/6373376 (0.2% not contiguous), ...

....

Pass 1: Checking inodes, blocks and sizes

...

Pass 5: Checking group summary information

(initramfs)

How can I start the system?


text:
Q: Having trouble routing to a page that will update a data entry by making get request using data object's ID I'm trying to route a page to my project that will allow the user to edit an existing data entry within a MongoDB database, however I am getting this error. The intended function of the program is that a user will be able to select an edit button on a specific data entry, which will open a form allowing them to altar that entry's content. It should do this by making a get request using the data's ID, however there is something wrong happening when I try to concatenate the route string, and the data's ID. Here is my Main.js file, my VehiclesList.js file, and my EditVehicles.js file:
Main.js
    import React, { Component } from "react";
import "./index.css";
import { Routes, Route } from "react-router-dom";

import VehicleList from "../VehicleList/index";
import AddVehicle from "../addVehicle/index";
import EditVehicle from "../editVehicle";

class Main extends Component {
  render() {
    return (

        <Routes>
          <Route exact path="/" element={<VehicleList />} />
          <Route path="/list" element={<VehicleList />} />
          <Route path="/addVehicle" element={<AddVehicle />} />
          <Route path="/editVehicle/:id" element={<EditVehicle />} />
        </Routes>

    );
  }
}

export default Main;

VehiclesList.js
import React, { Component, useState } from "react";
import "./index.css";
import axios from "axios";
import { Link } from "react-router-dom";
import VehicleService from "../services/services";

class VehicleList extends Component {
  constructor(props) {
    super(props);
    this.VehicleService = new VehicleService();
    this.state = {
      vehicles: [],
    };
    this.deleteVehicle = this.deleteVehicle.bind(this);
  }

  componentDidMount = () => {
    this.getVehicleList();
  };

  //get all vehicles
  getVehicleList() {
    axios
      .get("http://localhost:5000/vehicles")
      .then((res) => {
        console.log(res);
        this.setState({
          vehicles: res.data,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  //delete vehicle
  deleteVehicle(vehicleId) {
    this.VehicleService.deleteVehicle(vehicleId);
    this.getVehicleList();
    window.location.reload(false);
  }

  render() {
    const { vehicles } = this.state;
    return (

              #
              Make
              Model
              Year
              Price
              Status

            {vehicles &&
              vehicles.map((vehicle, idx) => {
                let status = "";
                if (vehicle.isSold) {
                  status = "Sold";
                } else {
                  status = "Available";
                }
                return (

                    {vehicle._id}
                    {vehicle.make}
                    {vehicle.model}
                    {vehicle.year}
                    {vehicle.price}
                    {status}

                      <Link
                        to={"/editVehicle/" + vehicle._id}
                        style={{ fontSize: "1.5rem" }}
                        className="edit_btn"
                      >
                        edit
                      </Link>

                      <button
                        onClick={() => this.deleteVehicle(vehicle._id)}
                        className="delete_btn"
                      >
                        Delete
                      </button>

                );
              })}

    );
  }
}

export default VehicleList;

EditVehicles.js
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";

class EditVehicle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      make: "",
      model: "",
      year: "",
      price: "",
      isSold: "",
    };
  }

  componentDidMount = () => {
    this.getVehicleById();
  };

  //get vehicle by ID
  getVehicleById() {
    axios
      .get(
        "http://localhost:5000/vehicles/editVehicle/" +
          this.props.match.params.id
      )
      .then((res) => {
        this.setState({
          make: res.data.make,
          model: res.data.model,
          year: res.data.year,
          price: res.date.price,
          isSold: res.data.isSold,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  //handle changes to data
  changeHandler = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  //update record on submit
  submitHandler = (e) => {
    e.preventDefault();
    const { make, model, year, price, isSold } = this.state;
    axios
      .post(
        "http://localhost:5000/vehicles/editVehicle/" +
          this.props.match.params.id,
        {
          make: make,
          model: model,
          year: year,
          price: price,
          isSold: isSold,
        }
      )
      .then((res) => {
        console.log(res);
        this.props.history.push("/");
      })
      .catch((err) => {
        console.log(err);
      });
  };

  render() {
    return (

        <form className="editVehicle_form" onSubmit={this.submitHandler}>
          <Link to="/" className="back_btn">
            Back
          </Link>

Update Vehicle Details

Please fill out all fields

          <input
            name="make"
            placeholder="Make"
            type="text"
            value={this.state.make}
            onChange={this.changeHandler}
            className="editVehicle_form_input"
          />

          <input
            name="model"
            placeholder="Model"
            type="text"
            value={this.state.model}
            onChange={this.changeHandler}
            className="editVehicle_form_input"
          />

          <input
            name="year"
            placeholder="Year"
            type="text"
            value={this.state.year}
            onChange={this.changeHandler}
            className="editVehicle_form_input"
          />

          <input
            name="price"
            placeholder="Price"
            type="text"
            value={this.state.price}
            onChange={this.changeHandler}
            className="editVehicle_form_input"
          />

            Available
            <input
              name="isSold"
              type="radio"
              value={false}
              onChange={this.changeHandler}
              className="editVehicle_form_radio"
            />

            Sold
            <input
              name="isSold"
              type="radio"
              value={true}
              onChange={this.changeHandler}
              className="editVehicle_form_radio"
            />

          <input type="submit" value="Save" className="editVehicle_submit" />
        </form>

    );
  }
}

export default EditVehicle;

My Routes to the VehiclesList, AddVehicle and DeleteVehicle pages all work. the only issue I'm running into is routing the EditVehicle page.
at first I was getting the error "Cannot read properties of undefined('params'), and then I changed the route to the EditVehicles page to this:
<Route path="/editVehicle/:id" component={EditVehicle} />

when I did it this way, I got an error back saying that this route did not have an element, and would result in an empty page.
I also tried doing it this way:
<Route path='/editVehicle/:id render={(props) => <EditVehicle {...props} />} />

this too just gave me an error saying that the route did not have an element.
is there an issue in my code that I am not seeing? or is there an easier way to do this?

A: The error tells you, that you don't have element attribute in Route:
<Route path="/editVehicle/:id" component={EditVehicle} />

Replace component to element
<Route path="/editVehicle/:id" element={<EditVehicle/>} />

You messed up with different versions of React-router-dom implementations.
see docs
Try to add useParams hook from React-router-dom in your EditVehicle component to get id:
let { id } = useParams();

A: Issue
The "edit vehicle" route is correct:
<Route path="/editVehicle/:id" element={<EditVehicle />} />

The issue is that in react-router-dom@6 there are no longer any route props. In other words, EditVehicle is a class-based component and this.props.match and this.props.history are undefined. It's only when the code attempts to access into this undefined object (i.e. this.props.match.params) that the error is thrown.
Additionally, the history object is no longer directly exposed in RRDv6, you'll need to use the useNavigate hook to access a navigate function.
Solution
You can either convert EditVehicle to a React function component or create a new custom withRouter Higher Order Component so that the route path params can be injected as props like the class component is expecting.

*

*Using custom withRouter HOC
Create a withRouter HOC that can use the React hooks and inject new props for the class component to access.
 import { useNavigate, useParams, /* other hooks */ } from 'react-router-dom';

 const withRouter = Component => props => {
   const navigate = useNavigate();
   const params = useParams();
   // ... other hooks ...
   return (
     <Component
       {...props}
       {...{ navigate, params, /* other props from hooks */ }}
     />
   );
 };

Decorate the EditVehicle component export:
 import withRouter from '../path/to/withRouter';

 ...

 export default withRouter(EditVehicle);

params and navigate (and others) are now injected as props, access accordingly in EditVehicle:
 // get vehicle by ID
 getVehicleById() {
   const { params: { id } } = this.props;

   axios.get("http://localhost:5000/vehicles/editVehicle/" + id)
     .then((res) => {
       const { data: { make, model, year, price, isSold } } = res;
       this.setState({ make, model, year, price, isSold });
     })
     .catch(console.log);
 }

 // update record on submit
 submitHandler = (e) => {
   e.preventDefault();
   const { make, model, year, price, isSold } = this.state;
   const { navigate, params: { id } } = this.props;

   axios
     .post(
       "http://localhost:5000/vehicles/editVehicle/" + id,
       { make, model, year, price, isSold }
     )
     .then((res) => {
       console.log(res);
       navigate("/");
     })
     .catch(console.log);
 };

*Conversion to React function component

*

*Use the useNavigate and useParams hooks directly

*Use React.useState to store the form field values

*use React.useEffect to update the state when the id path param updates

*Convert all class methods to functions, and remove references to this
Code:
 import React, { useEffect, useState } from "react";
 import axios from "axios";
 import { Link, useParams, useNavigate } from "react-router-dom";

 const EditVehicle = () => {
   const navigate = useNavigate();
   const { id } = useParams();

   const [state, setState] = useState({
     make: "",
     model: "",
     year: "",
     price: "",
     isSold: ""
   });

   useEffect(() => {
     // get vehicle by ID
     const getVehicleById = (id) => {
       axios
         .get("http://localhost:5000/vehicles/editVehicle/" + id)
         .then((res) => {
           const { make, model, year, price, isSold } = res.data;
           setState({ make, model, year, price, isSold });
         })
         .catch(console.log);
     };

     getVehicleById(id);
   }, [id]);

   //handle changes to data
   const changeHandler = (e) => {
     const { name, value } = e.target;
     setState((state) => ({
       ...state,
       [name]: value
     }));
   };

   //update record on submit
   const submitHandler = (e) => {
     e.preventDefault();
     const { make, model, year, price, isSold } = state;
     axios
       .post("http://localhost:5000/vehicles/editVehicle/" + id, {
         make,
         model,
         year,
         price,
         isSold
       })
       .then((res) => {
         console.log(res);
         navigate("/");
       })
       .catch(console.log);
   };

   return (

       <form className="editVehicle_form" onSubmit={submitHandler}>
         <Link to="/" className="back_btn">
           Back
         </Link>

Update Vehicle Details

Please fill out all fields

         <input
           name="make"
           placeholder="Make"
           type="text"
           value={state.make}
           onChange={changeHandler}
           className="editVehicle_form_input"
         />

         <input
           name="model"
           placeholder="Model"
           type="text"
           value={state.model}
           onChange={changeHandler}
           className="editVehicle_form_input"
         />

         <input
           name="year"
           placeholder="Year"
           type="text"
           value={state.year}
           onChange={changeHandler}
           className="editVehicle_form_input"
         />

         <input
           name="price"
           placeholder="Price"
           type="text"
           value={state.price}
           onChange={changeHandler}
           className="editVehicle_form_input"
         />

           Available
           <input
             name="isSold"
             type="radio"
             value={false}
             onChange={changeHandler}
             className="editVehicle_form_radio"
           />

           Sold
           <input
             name="isSold"
             type="radio"
             value={true}
             onChange={changeHandler}
             className="editVehicle_form_radio"
           />

         <input type="submit" value="Save" className="editVehicle_submit" />
       </form>

   );
 };


text:
Q: Should I use nouveau driver or akmod-nvidia on my Fedora 23 system with GT630 graphics card? would akmod-nvidia driver work on my set up or Am I stuck using the default nouveau? if nouveau is good. would it work on playing dota 2 or csgo? thanks. This games was working fine when I was from windows 10 same graphics card.

A: Games will most likely not work with nouveau. Everything else, however should work.
If you do want games, akmod-nvidia is the way to go.


text:
Q: Modify Android gradle.properties in Expo Managed App I'm working on a Expo React Native project that requires up to 15MB of local storage in android. This requires adding the following to the android/gradle.properties file.

AsyncStorage_db_size_in_MB=10

I've tried creating a plugin with
import { withGradleProperties } from "@expo/config-plugins";

export const modifyGradle = (config) => {
      const AsyncKey = "AsyncStorage_db_size_in_MB";
      return withGradleProperties(config, (config) => {
        config.modResults.push({
          type: "property",
          key: AsyncKey,
          value: 10,
        });

        return config;
      });
    };

And then adding to app.json as
expo:{
...
"plugins": ["./plugins/modifyGradle.js"],
...
}

What am I doing wrong here? How can this be done without ejecting from Expo?

A: First of all, as stated in docs, you should rename your plugin to something like withModifyGradle and as far as I can understand, you should not use import, use require instead:
const { withGradleProperties } = require('@expo/config-plugins');

module.exports = (config) => {
  const newGraddleProperties = [
    {
      type: 'property',
      key: 'AsyncStorage_db_size_in_MB',
      value: '10', // Maybe you should set this to 15?
    },
    // Added this to demostrate multiple gradle properties change
    {
      type: 'property',
      key: 'FLIPPER_VERSION',
     value: '0.144.0', // Fix app names with accented and diacritics characters
    },
  ];

  return withGradleProperties(config, (config) => {
    newGraddleProperties.map((gradleProperty) => config.modResults.push(gradleProperty));

    return config;
  });
};

After you create the config plugin set it up in app.config.js (as stated here) like this
expo:{
    ...
    plugins: [
        ['./plugins/withModifyGradle.js'],
    ],
    ...
}

As stated here, you can check if the plugin is working by running EXPO_DEBUG=1 expo prebuild in the project directory. After that, you should have an android folder with a gradle.properties file with the new properties at the end of the file.
If that succeeded, then you are ready to go with eas build, but after running that command, I needed to remove index.js, metro.config.js, android, ios and node_modules folders, and revert changes to my package.json file, then ran npm install to get back to expo.

A: The problem is yout config plugin name, it should be "withModifyGradle.js"
Plugins should be named using the following convention: with<Plugin Functionality> i.e. withFacebook.

https://docs.expo.dev/guides/config-plugins/#creating-a-plugin


text:
Q: How to get the index of a column of my jTable? What happens is I want to get the index of the header of my column of my jTable when I click, I have tried with:
Tabla.getSelectedColumn() But this only devains the index of the column when I click on the cell.

A: You can add a mouse listener to the table's column header.
In the mouse listener's mouseClicked() method, you can use the getTableHeader().columnAtPoint() method to get the index of the clicked column.
table.getTableHeader().addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        int column = table.getTableHeader().columnAtPoint(e.getPoint());
        System.out.println("Column index: " + column);
    }
});

This will print the index of the clicked column to the console every time a column header is clicked.
Alternatively, you can use Jtable's getSelectedColumn(), which will give you the
index of the selected column.
int selectedColumn = table.getSelectedColumn();

This will give you the index of the selected column.


text:
Q: Getting a subarray of hashes I have an array of hashes like this, which is sorted by the value for :a:
[{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]

How can I get a subset of this array that has the hashes with the minimum value for :a?
Here, the minimum value for :a is 0, so I need:
[{:a=>0, :b=>10}, {:a=>0, :b=>35}]

A: z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
z.select{|y| y[:a] == z.first[:a]}

A: To me it seems that the accepted answer makes the assumption that the :a value of the first element in the array is the minimum. So if the array were modified where :a => 1 in the first element, then the result is incorrect. Here's the example:
# original
z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
puts z.select{|y| y[:a] == z.first[:a]}.inspect
# => [{:a=>0, :b=>10}, {:a=>0, :b=>35}] the result is the expected one

# modified :a of first element
z = [{:a=>1, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
puts z.select{|y| y[:a] == z.first[:a]}.inspect
# => [{:a=>1, :b=>10}, {:a=>1, :b=>20}] here result does not have min :a

Now, not making that assumption I'm taking the extra step of finding the minimum value of :a
z = [{:a=>0, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
# find the min :a
m = z.map { |y| y[:a] }.min
puts z.select{|y| y[:a] == m}.inspect
# => [{:a=>0, :b=>10}, {:a=>0, :b=>35}]

# modified :a of first element
z = [{:a=>1, :b=>10}, {:a=>0, :b=>35}, {:a=>1, :b=>20}, {:a=>2, :b=>0}]
m = z.map { |y| y[:a] }.min
puts z.select{|y| y[:a] == m}.inspect
# => [{:a=>0, :b=>35}]


text:
Q: Codeigniter list only files non-recursively I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.
I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:
$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}

I'm sure there has to be a way easier and better solution, but had no luck finding it

A: You can get an array of filenames in a one-liner, using scandir()
http://php.net/manual/en/function.scandir.php
Here's an example that does an array_diff() to remove the "." and ".." directories.
 $files = array_diff(scandir('src/img/example'), array('..', '.'));

You can also use array_filter().
$files = array_filter(scandir('src/img/example'), function($item) {
  return !is_dir('directory/' . $item);
});

A: a possible option would be to use a DirectoryIterator
$arrFiles = [];

foreach (new DirectoryIterator('src/img/example/') as $objFile)
{
    if($objFile->isFile()) $arrFiles[] = $objFile->getFilename();
}


text:
Q: Sort a field of array upon mysql query I have a field: userids which contains 19,2,23 for example, which I populate based on user ids added to a room arbitrarily.  I list the corresponding names based on these userids.
Right now I get Richard, Evan, James from this query (19 = Richard, 2 = Evan, 23 = James).
What I would like to do is sort the array (the field) upon query so that it is 2,19,23 and the names are returned Evan, Richard, James.
So a query that looks like this:
    SELECT c.*,c.NAME as PAGE, ASORT(c.USERIDS) as USERIDS, p.*
    FROM TBL_CONTENT c, TBL_PAGE p
    WHERE c.PAGEID = p.ID AND FIND_IN_SET(?, c.USERIDS)

Should look like (help me with this query)?
of course, the ASORT function does not exist - I just include it as an example of what I am trying to do.
Any help here?
Thank you!

A: This works with mysql 8
For mysql 5.x , you need much more code to do that
SET @a = '19,2,23';

SELECT GROUP_CONCAT(ord ORDER BY ord)
FROM
(select  CAST(num as UNSIGNED) ord
from (SELECT @a as names) t
join json_table(
  replace(json_array(t.names), ',', '","'),
  '$[*]' columns (num varchar(50) path '$')
) j) z1

RESULTS in
# GROUP_CONCAT(ord ORDER BY ord)
2,19,23

For Mysql 5.x You can use a function
DELIMITER $$
CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_stringnumbers_and_sort`(_text TEXT) RETURNS text CHARSET utf8mb4
    DETERMINISTIC
BEGIN
SET @text = _text;
SELECT
GROUP_CONCAT((name+0) ORDER BY (name +0)) INTO @output
FROM
(
select
  SUBSTRING_INDEX(SUBSTRING_INDEX(t1.name, ',', numbers.n), ',', -1) name
from
  (select 1 n union all
   select 2 union all select 3 union all
   select 4 union all select 5) numbers INNER JOIN (SELECT @text as name) t1
  on CHAR_LENGTH(t1.name)
     -CHAR_LENGTH(REPLACE(t1.name, ',', ''))>=numbers.n-1
order by  n
) t2;

RETURN @output;
END$$
DELIMITER ;

SO that this query
SET @a = '19,2,23';
SELECT fn_split_stringnumbers_and_sort(@a);

has the same result
# fn_split_stringnumbers_and_sort(@a)
2,19,23

Caution
This function only would split 5 comma separated numbers if you have more than that you have to increase table  with more UNION


text:
Q: Detecting refresh event in GWT We need to detect the Refresh event (f5) / reload of the web application.
Is there an event in GWT that can detect this?
thanks,
mj

A: Add a Window Closing Handler:
HandlerRegistration registration = Window.addClosingHandler(new ClosingHandler() {
    void onWindowClosing(ClosingEvent event) {
        // call the server, or whatever
    }
});

EDIT
The HandlerRegistration is used to deregister the Handler if you don't need it anymore.


text:
Q: Implementing AJAX call on checkbox in Rails to update db Rails newbie here.
I am trying to make a checkbox called "Active" that will act as a form when the checkbox is checked/unchecked and use AJAX to automatically update the database with the changed attribute (without a submit button). I am using the instructions here: http://trevorturk.com/2010/08/24/easy-ajax-forms-with-rails-3-and-jquery/ but can't seem to make it work correctly.
In my view:
<%= form_for @post, :remote => true do |f| %>
<%= f.label :active %>
<%= f.check_box :active, :class => 'submittable' %>
<% end %>

In my posts_controller.rb
def update
if @post.update(post_params)
  flash[:notice] = "Your post was edited."
  redirect_to post_path(@post)
else
  render :edit
end
end

Then I made a file called 'archive.js.erb' in my views/posts folder with this code:
$('.submittable').live('change', function() {
  $(this).parents('form:first').submit();
});

A: I've tried your code, and the problem seems to be on the live method on javascript. It works if i change to the click function:
$(document).ready(function(){

    $('.submittable').click(function() {
        $(this).parents('form:first').submit();
    });

});

Edit: Forgot to mention that this javascript was included in app/assets/javascripts directory.  This is because the javascript must be loaded on document.ready for the jQuery ajax to have the effect that you want.
The arquive.js.erb file must exist in the case that you have an arquive action on your controller, and the javascript code that is in it will be executed later. This is not your case.


text:
Q: Nhibernate ordered paging by a lazy loading bag I have the following mapping:
<class name="Entity, Namespace.MyDomain" table="Entity" lazy="false" mutable="false" >
<id name="EntityId" column="ENTITY_ID"> <generator  class="native"/> </id>

<bag name="EntityList" inverse="true" lazy="true" cascade="all-delete-orphan">
       <key column="ENTITY_ID"/>
       <one-to-many class="Namespace.Entity.EntityList, Namespace.MyDomain"/>
</bag>

Now, I want to get an ordered paging by my EntityList.Name.
For example, if I have 2 entities:
1) Entity with EntityList of animal names (tiger)
2) Entity with EntityList of animal names (cat, dog)
Then, I would like to get the second entity first (because 'c' of cat is lower then 't' of tiger) and the first one afterwards.
Of course, it will affect my paging, because there might be a chance that entity with tiger will be shown on the first page, if i get my paging by by entity.id, but when i get it by entitylist.names, it might be displayed on other page.
Thanks in advance,
Mike.
p.s. - i'm using criteria.

A: var entityIds = session.CreateCriteria<Entity>()
    .CreateAlias("EntityList", "el")
    .AddOrder(Order.Asc("el.Name"))
    .SetProjection(Projections.Id)
    .List<int>();

var entities = session.CreateCriteria<Entity>()
    .Add(Expression.In(Projections.Id, entityIds))
    .SetFetchMode("EntityList", FetchMode.Eager)
    .List<Entity>();

// resort again
return entityIds.Select(id => entities.First(e => e.Id == id)).ToList();


text:
Q: log out confirmation box in javascript I have a php code for logout page but i need to have a confirmation box pop-up first if i click the navigation box to logout...if  I want to logout or not...can any1 help me?? please
code:
<?php
include("connection.php");

// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
$uid = $_POST['uid'];
    $stat="UPDATE users SET status='logout'";
        mysql_query($stat);
// Jump to login page
header('Location: index.php');

?>

A: maybe this is what you are trying to achieve?
var logout = confirm("Are you sure to logout?");

if(logout){
     location.href = "pathtologout.php";
}

A: Most simple:
Logout

A: If you just need a simple confirmation, you can do this
$('#logout').click(function(){
    var reallyLogout=confirm("Do you really want to log out?");
    if(reallyLogout){
        location.href="path/to/logout/file.php";
    }
});

If you can't use jQuery(!), you can use pure Javascript to attach the event handler
function logout(){
        var reallyLogout=confirm("Do you really want to log out?");
        if(reallyLogout){
            location.href="path/to/logout/file.php";
        }
}
var el = document.getElementById("logout");
if (el.addEventListener) {
        el.addEventListener("click", logoutfunction, false);
    } else {
        el.attachEvent('onclick', logoutfunction);
}


text:
Q: Two amplifiers in cascade I want to do a simulation with two type amplifiers (PA107DP) in cascade to expand the bandwidth.
How can I do ? just I connect the output of first to the input of second (out-one I connect it to -IN of second amp) or there are modifications necessary to make at the input of second amp (like resistance ect )


text:
Q: unable to access particular directory my exe unable to access paticular directory
it is getting error

Error Caused : Error Opening File --> ./LOG
  Unable to open log file,please check the Log path=./LOG

directory exists in same path, with chmod 777

A: Sorry it was my fault exe is trying to access "LOG " (i.e LOG with space at end )  :)


text:
Q: Parsing XML of unequal number of tags to make lists of equal length. openpyxl and Beautifulsoup I have an XML file that have book records that contains tags like the author, publication date, labels and so on. I'm going to parse this file to make 3 lists, one will have the book title, the author in another list, and finally the labels in a third list, later I will write these lists to Excel columns using openpyxl.
The problem is that some of the book records don't have a label tag. Using regular parsing technique with Beautiful soup will produce the first two lists with the same length, but the label list will have a shorter length.
I have three questions:
1- how do I create all three lists with equal length (empty entry for books that dont have the label tag?
2- The label list looks like this ['Energy;Green Buildings;High Performance Buildings', 'Computing', 'Computing;Design;Green Buildings',.......]. I have created about an additional 15 columns titled with the label names that I have, such as "Computing" and "Design". Is there any way that I can use openpyXL to create an X mark or colored cell for the book-label combination if a book contains a specific label, for example, if a book titled "Architecture" in row 5 has the "Design" label, I need to have either a X mark or colored cell in cell(row'5',col'Design').
3- Is there an easier method to accomplish this (parsing the XML file and writing efficiently in Excel)?
Here is a snap shot of the XML file and the code that I wrote ( also both the XML file and the Python files can be downloaded from here: http://www.ranialabib.com/#!python/icfwa
<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <records>
        <record>
            <database name="My Collection.enl" path="My Collection.enl">My Collection.enl</database>
            <ref-type name="Book">1</ref-type>
            <contributors>
                <authors>
                    <author>AIA Research Corporation</author>
                </authors>
            </contributors>
            <titles>
                <title>Regional guidelines for building passive energy conserving homes</title>
            </titles>
            <periodical/>
            <keywords/>
            <dates>
                <year>1978</year>
            </dates>
            <publisher>Dept. of Housing and Urban Development, Office of Policy Development and Research : for sale by the Supt. of Docs., U.S. Govt. Print. Off.</publisher>
            <urls/>
            <label>Energy;Green Buildings;High Performance Buildings</label>
        </record>
    <record>
            <database name="My Collection.enl" path="My Collection.enl">My Collection.enl</database>
            <ref-type name="Book">1</ref-type>
            <contributors>
                <authors>
                    <author>Akinci, Burcu</author>
                    <author>Ph, D</author>
                </authors>
            </contributors>
            <titles>
                <title>Computing in Civil Engineering</title>
            </titles>
            <periodical/>
            <pages>692-699</pages>
            <keywords/>
            <dates>
                <year>2007</year>
            </dates>
            <publisher>American Society of Civil Engineers</publisher>
            <isbn>9780784409374</isbn>
            <electronic-resource-num>ISBN 978-0-7844-1302-9</electronic-resource-num>
            <urls>
                <web-urls>
                    <url>http://books.google.com/books?id=QigBgc-qgdoC</url>
                </web-urls>
            </urls>
        </record>

import xml.etree.ElementTree as ET
fhand = open('My_Collection.xml')
data = fhand.read()

Title=list()
Year=list()
Label=list()

tree = ET.fromstring(data)
titles = tree.findall('.//title')
years = tree.findall('.//year')
labels = tree.findall('.//label')

for t in titles :
    Title.append(str(t.text))
print 'Titles: ', len(Title)
print Title

for y in years :
    Year.append(str(y.text))
print 'years: ', len(Year)
print Year

for l in labels :
    Label.append(str(l.text))
print 'Labels: ', len(Label)
print Label

from openpyxl import Workbook
wb = Workbook()
ws = wb.active

for row in zip(Title, Year, Label):
        ws.append(row)

wb.save("Test2.xlsx")

Here is a code that I wrote based on Charlie's suggestion, the code didn't work. I got an error message saying"TypeError: 'NoneType' object is not iterable".I'm not sure what the problem is.
Also how do I get the text of all 3 tags( Title, Year, Label) of each record in one list, and how easy is to write such a large number of lists (200 list for 200 books) to Excel using openpylx?
import xml.etree.ElementTree as ET
fhand = open('My_Collection.xml')
data = fhand.read()
Label_lst=list()
for record in tree.find("records/record") :
    label = record.find("label")

for l in label:
        if label is not None: label = label_lst.append(label.text)
    else:
        label = label_lst.append(' ')
print label_lst

A: If you want to preserve the record structure you should parse record-by-record rather just creating lists of the attributes. You can loop through the records and extract the relevant fields or for record in parsed_xml.find("records/record"); label = record.find("label"); if label is not None: label = label.text You can then write the rows straight to Excel without having to zip over the columns.

A: I just figured it out. I still used columns though.
from openpyxl import Workbook
import xml.etree.ElementTree as ET

fhand = open ('My_Collection')
tree =ET.parse('My_Collection.xml')
data= fhand.read()
root = tree.getroot()
tree = ET.fromstring(data)

title_list= ['Title']
year_list = ['Year']
author_list= ['Author']
label_list = ['Label']

for child in tree:
    for children in child:
        if children.find('.//title')is None :
            t='N'
        else:
            t=children.find('.//title').text
        title_list.append(t)
    print title_list
    print len(title_list)

for child in tree:
    for children in child:
        if children.find('.//year')is None :
            y='N'
        else:
            y=children.find('.//year').text
        year_list.append(y)
    print year_list
    print len(year_list)

for child in tree:
    for children in child:
        if children.find('.//author')is None :
            a='N'
        else:
            a=children.find('.//author').text
        author_list.append(a)
    print author_list
    print len(author_list)

for child in tree:
    for children in child:
        if children.find('label')is None :
            l='N'
        else:
            l=children.find('label').text
        label_list.append(l)
    print label_list
print len(author_list)

for item in label_list:

wb = Workbook()
ws = wb.active

for row in zip(title_list, year_list, author_list, label_list):
        ws.append(row)

wb.save("Test3.xlsx")


text:
Q: How to add a Calculated field to AllContentType? Today, I'm having a problem is after I had created a Calculated field. It seems there is no way to add AllContentTypes. And the DefaultView, maybe I can handle this. And I also saw this method:
spList.Fields.AddFieldAsXml(spFieldUser.SchemaXml, True, SPAddFieldOptions.AddToAllContentTypes);

But in this case, I'm not sure I can use it or not. Because my code is:
                      //SPField tempSPField = spList.Fields.CreateNewField(createSPColumnObject.ColumnType, createSPColumnObject.ColumnName);//We can not use this code line for creating Calculated (there is no constructor for this)
                        SPFieldCollection collFields = spList.Fields;
                        string strSPFieldCalculatedName = collFields.Add(createSPColumnObject.ColumnName, SPFieldType.Calculated, false);
                        if (createSPColumnObject.IsAddedToDefaultView)
                        {
                            SPView spView = spList.DefaultView;
                            spView.ViewFields.Add(strSPFieldCalculatedName);
                            spView.Update();
                        }
                        SPFieldCalculated spFieldCalculated = null;
                        //
                        spFieldCalculated = (SPFieldCalculated)collFields[createSPColumnObject.ColumnName];
                        spFieldCalculated.ShowInDisplayForm = true;
                        //spFieldCalculated.ShowInEditForm = true;
                        spFieldCalculated.ShowInListSettings = true;
                        //spFieldCalculated.ShowInNewForm = true;
                        spFieldCalculated.ShowInViewForms = true;
                        //
                        spFieldCalculated.Description = createSPColumnObject.ColumnDescription;
                        spFieldCalculated.Formula =  string.Format(@"={0}",createSPColumnObject.CalcFormula);
                        spFieldCalculated.Update();
                        //spList.Fields.AddFieldAsXml(spFieldCalculated.SchemaXml, createSPColumnObject.IsAddedToDefaultView, SPAddFieldOptions.AddToAllContentTypes);// also use this code line because we will get an exception with a duplicate column ID.

                        spFieldCalculated.OutputType = SPFieldType.Text;
                        spList.Update();

I totally created a Calculated column but how can I add it to allcontent types ? everybody could help me out this ? BTW, to the DefaultView, I did like the above is right ? Could eveybody let me know this ?
I just worry about everybody get misunderstanding ? Or review with missing code. So could everybody please to take a look on my code clearly ? Thanks all.
Many thanks, :)
Standley Nguyen

A: I'm not sure if i fully understand what you are trying to do however i may be able to shed some light on some parts of what you are trying to do.
When you create your field does it then appear in your site actions -> site settings -> Site columns. If so you have created this correctly. If it doesn't there are hundreds of examples of how to do this if you search google.
Once you have your field create you then need to consider which content types you want to add it to. Once you have these content types you then have to add something called a field link to the Content type.
This isn't my code i have picked it off the web but this should do what you require.
  SPContentType ct = web.ContentTypes[contentType];
  ct.FieldLinks.Add(new SPFieldLink(field));
  ct.Update();

Cheers
Truez


text:
Q: How does one write the Pythagoras Theorem in Scala?
The square of the hypotenuse of a right triangle is equal to the sum of the squares on the other two sides.

This is Pythagoras's Theorem. A function to calculate the hypotenuse based on the length "a" and "b" of it's sides would return sqrt(a * a + b * b).
The question is, how would you define such a function in Scala in such a way that it could be used with any type implementing the appropriate methods?
For context, imagine a whole library of math theorems you want to use with Int, Double, Int-Rational, Double-Rational, BigInt or BigInt-Rational types depending on what you are doing, and the speed, precision, accuracy and range requirements.

A: This only works on Scala 2.8, but it does work:
scala> def pythagoras[T](a: T, b: T, sqrt: T => T)(implicit n: Numeric[T]) = {
     | import n.mkNumericOps
     | sqrt(a*a + b*b)
     | }
pythagoras: [T](a: T,b: T,sqrt: (T) => T)(implicit n: Numeric[T])T

scala> def intSqrt(n: Int) = Math.sqrt(n).toInt
intSqrt: (n: Int)Int

scala> pythagoras(3,4, intSqrt)
res0: Int = 5

More generally speaking, the trait Numeric is effectively a reference on how to solve this type of problem. See also Ordering.

A: Some thoughts on Daniel's answer:
I've experimented to generalize Numeric to Real, which would be more appropriate for this function to provide the sqrt function. This would result in:
def pythagoras[T](a: T, b: T)(implicit n: Real[T]) = {
   import n.mkNumericOps
   (a*a + b*b).sqrt
}

It is tricky, but possible, to use literal numbers in such generic functions.
def pythagoras[T](a: T, b: T)(sqrt: (T => T))(implicit n: Numeric[T]) = {
   import n.mkNumericOps
   implicit val fromInt = n.fromInt _

   //1 * sqrt(a*a + b*b)   Not Possible!
   sqrt(a*a + b*b) * 1    // Possible
}

Type inference works better if the sqrt is passed in a second parameter list.
Parameters a and b would be passed as Objects, but @specialized could fix this. Unfortuantely there will still be some overhead in the math operations.
You can almost do without the import of mkNumericOps. I got frustratringly close!

A: The most obvious way:
type Num = {
  def +(a: Num): Num
  def *(a: Num): Num
}

def pyth[A <: Num](a: A, b: A)(sqrt: A=>A) = sqrt(a * a + b * b)

// usage
pyth(3, 4)(Math.sqrt)

This is horrible for many reasons.  First, we have the problem of the recursive type, Num.  This is only allowed if you compile this code with the -Xrecursive option set to some integer value (5 is probably more than sufficient for numbers).  Second, the type Num is structural, which means that any usage of the members it defines will be compiled into corresponding reflective invocations.  Putting it mildly, this version of pyth is obscenely inefficient, running on the order of several hundred thousand times slower than a conventional implementation.  There's no way around the structural type though if you want to define pyth for any type which defines +, * and for which there exists a sqrt function.
Finally, we come to the most fundamental issue: it's over-complicated.  Why bother implementing the function in this way?  Practically speaking, the only types it will ever need to apply to are real Scala numbers.  Thus, it's easiest just to do the following:
def pyth(a: Double, b: Double) = Math.sqrt(a * a + b * b)

All problems solved!  This function is usable on values of type Double, Int, Float, even odd ones like Short thanks to the marvels of implicit conversion.  While it is true that this function is technically less flexible than our structurally-typed version, it is vastly more efficient and eminently more readable.  We may have lost the ability to calculate the Pythagrean theorem for unforeseen types defining + and *, but I don't think you're going to miss that ability.

A: There is a method in java.lang.Math:
public static double hypot (double x, double y)

for which the javadocs asserts:

Returns sqrt(x2 +y2) without intermediate overflow or underflow.

looking into src.zip, Math.hypot uses StrictMath, which is a native Method:
public static native double hypot(double x, double y);


text:
Q: Grammar spec resolving Shift/Reduce conflicts I'm using Jison (Bison) to create a simple markup language.  I'm clearly new to this, but slight variations are working very well.  I just don't understand the source of the S/R conflict.
It doesn't seem matter that 'Text' is returned by two lexer actions (with different Start Conditions) and I like this because it seems to allow the grammar to have fewer rules and because the error messages to the user are consistent.  I've tried making the 'Text' rule common regardless of context and I've also tried giving each token a different name, but it doesn't seem to have any effect on the S/R Conflicts when it's all together.
The parser is SUPPOSED to create a json-object with plain-text, sub-arrays, and various special nodes.
Specification:
/* lexical grammar */
%lex

%s bracketed

%%

<bracketed>(\\.|[^\\\,\[\]])+       { yytext = yytext.replace(/\\(.)/g, '$1'); return 'Text'; }
<INITIAL>(\\.|[^\\\[])+             { yytext = yytext.replace(/\\(.)/g, '$1'); return 'Text'; }
"["                                 { this.begin('bracketed'); return '['; }
"]"                                 { this.popState(); return ']'; }
","                                 return ','
<<EOF>>                             return 'END'

/lex

%start template

%%

template
    : sentence END
    ;

sentence
    : /* empty */
    | sentence Text
    | sentence '[' ']'
    | sentence '[' dynamic ']'
    ;

dynamic
    : sentence
    /*| dynamic ',' sentence*/
    ;

Warnings:
Conflict in grammar: multiple actions possible when lookahead token is ] in state 5
- reduce by rule: sentence ->
- shift token (then go to state 6)

States with conflicts:
State 5
  sentence -> sentence [ .] #lookaheads= END Text [ ]
  sentence -> sentence [ .dynamic ] #lookaheads= END Text [ ]
  dynamic -> .sentence #lookaheads= ]
  sentence -> . #lookaheads= ] Text [
  sentence -> .sentence Text
  sentence -> .sentence [ ]
  sentence -> .sentence [ dynamic ]

Different generator algorithms have more or less trouble, but they all seem to have trouble.
Thanks!

A: The conflict comes fundamentally from these two rules:
sentence: sentence '[' Text ']'
        | sentence '[' sentenceList ']'

The reason is that after seeing a sentence and a [ and looking at the next token being Text, the parser doesn't known whether to shift the Text, matching the first rule, or to treat that Text as the beginning of a sentenceList going towards matching the second rule.
Now if you had a parser generator that use 2-token lookahead, this wouldn't be a problem, but bison is LALR(1) (the 1 being one token lookahead).
There are a couple of things you could try:

*

*do extra lookahead in the lexer to differentiate Text-followed-by-] from Text-not-followed-by-] as two distinct tokens then rewrite the rules to use both of these tokens.

*Use bison's %glr-parser feature to use GLR parser.  This will parse the sentence both ways and later throw away the one that doesn't match

*refactor the grammar to not need 2-token lookahead.
One refactoring that works in your case would be to rewrite the sentence rules to make them all right-recursive instead of left-recursive:
sentence: /* empty */
        | Text sentence
        | '[' ']' sentence
        | '[' Text ']' sentence
        | '[' sentenceList ']' sentence
        ;

This avoids having sentence (or any other rule that starts with sentence such as sentenceList) start with a null reduction of the sentence: /*empty*/ rule.  So the parser can freely shift a Text in the problematic case deferring the reduction until it sees the next token.  It does have memory use implications, however, as it results in a parser that will essentially shift the entire input on to the parser stack and then reduce it one sentence at a time.
Another refactor you could do would be to subsume the [Text] and [] constructs into the [sentenceList]:
sentence: /* empty */
        | sentence Text
        | sentence '[' sentenceList ']'
        ;

sentenceList: sentence
            | sentenceList ',' sentence

So now a sentenceList is one or more sentences separated by commas (instead of two or more), and in the action for the sentence '[' sentenceList ']' rule, you'd check the sentenceList to see if it was two or more sentences and act appropriately.


text:
Q: Dealing with queues and test cases for queues Hello Im trying to understand what exactly is wrong with mo program. I have written code for enqueue, dequeue, top and size for queues in racket. I have also written test cases to try out my program within the module. When i try to run the test cases by typing out the following command "racket run-tests.rkt | less", i get the following error:
"
default-load-handler: expected only a module' declaration forqueue', but found an extra expression in: #
=== context ===
default-load/use-compiled
"
Here are my three files and the code within them
1- queue.rkt
(module queue racket
  (provide make-queue enqueue dequeue top size queue-tests)
  (struct queue (front back size) #:mutable #:transparent)

    (define (make-queue) (queue null null 0))

(define (enqueue q elt)
    (set-queue-back! q (cons elt (queue-back q)))
    (set-queue-size! q (+ (queue-size q) 1))
    )
(define (dequeue q)
    (cond  ((eq? (queue-size q) 0) null)
           ((null? (queue-front q))
            (begin
              (set-queue-front! q (cdr (reverse (queue-back q))))
              (set-queue-back! q null)
              (set-queue-size! q (- (queue-size q) 1))))
           (else
            (begin
              (set-queue-front! q (cdr (queue-front q)))
              (set-queue-size! q (- (queue-size q) 1))))
           )
  )

  (define (top q)
    (cond ((eq? (queue-size q) 0) null)
          ((null? (queue-front q)) (last (queue-back q)))
          (else (car (queue-front q)))))

   (define (size q)
    (queue-size q))

  ; Test cases Here
  (include "test-queue.rkt")
)

2-  test-queue.rkt
 #lang racket/base

 (require rackunit)

 (define queue-tests
  (test-suite
    "Tests for the Queue"

    (test-case "Initial Queue Properties"
    (let  ((q (make-queue)))
      (check-equal? (size q) 0 "Queue initially should have size zero.")
      (check-equal? (dequeue q) null "Dequeue on an empty queue returns null")
      (check-equal? (size q) 0 "Dequeue on empty queue leaves size as zero")
      ))

    (test-case "One Element queue ---- Functional test"
       (let ((q (make-queue)))
         (check-equal? (size q) 0 "Stack initially should be of size zero")
         (enqueue q 1)
         (check-equal? (size q) 1 "Added one element to back of queue")
         (check-equal? (top q) 1 "Take a sneak peak at our first element")
         (dequeue q)
         (check-equal? (size 1) 0 "size should now be zero")
         (check-equal? (dequeue q) null "dequeue on empty queue returns null")
         ))

    (test-case "One Element queue --- Internal Test"
       (let  ((q (make-queue)))
         (check-equal? (size q) 0 "queue initially should have size zero.")
         (enqueue q 3)
         (check-equal? (size q) 1 "Added one element.")
         (check-equal? (queue-back q) '(3) "Is the element in the back list?")
         (check-equal? (top s) 3 "Look at our one element.")
         (check-equal? (queue-front q) '(3) "Is the element in the front list?")
         (dequeue s)
         (check-equal? (queue-front q) '() "Is the data empty now?")
         ))

    (test-case "Multi Element queue --- Functional Test"
    (let  ((q (make-queue))
           (elts (list 8 6 7 5 3 0 9))
           )
      (check-equal? (size q) 0 "queue initially should have size zero.")
      (for ((i elts)
            (num (in-range 1 8)))
           (enqueue q i)
           (check-equal? (size q) num "Testing size.")
           (check-equal? (top q) i "Testing top with multiple additions.")
           )
      (for ((i (reverse elts))
            (num (reverse (stream->list (in-range 1 8)))))
           (check-equal? (top q) i "Testing top with multiple deletions")
           (dequeue q)
           (check-equal? (size q) (- num 1) "Testing size.")
           )
      ))

    (test-case "Multi Element queue --- Ebb and Flow Test"
       (let  ((q (make-queue))
              (elts (list 8 6 7 5 3 0 9))
              )
         (check-equal? (size q) 0 "queue initially should have size zero.")
         (for ((i elts)
           (num (in-range 1 8)))
              (enqueue q i)
              (check-equal? (size q) num "Testing size, first flow.")
              (check-equal? (top q) i "Testing top with multiple additions.")
           )
         (for ((i (reverse elts))
               (num (reverse (stream->list (in-range 1 8)))))
              (check-equal? (top q) i "Testing top with multiple deletions")
              (dequeue q)
              (check-equal? (size q) (- num 1) "Testing size, first ebb.")
           )
         (for ((i elts)
               (num (in-range 1 8)))
               (enqueue q i)
               (check-equal? (size q) num "Testing size, second flow.")
               (check-equal? (top q) i "Testing top with multiple additions.")
           )
         (for ((i (reverse elts))
               (num (reverse (stream->list (in-range 1 8)))))
               (check-equal? (top q) i "Testing top with multiple deletions")
               (dequeue q)
               (check-equal? (size q) (- num 1) "Testing size, second ebb.")
           )
      ))

   (test-case "Multi Element queue --- Internal Test"
    (let  ((q (make-queue))
           (elts (list 5 8 8 2 3 0 0))
           (tmp null)
           )
      (for ((i elts)
            (num (in-range 1 8)))
           (enqueue q i)
           (check-equal? (size q) num "Testing size, second flow.")
           (set! tmp (cons i tmp)) ; "push" element to a list
           (check-equal? (queue-front q) tmp "Queue data is in correct form.")
           )
      ))

    ))

3- run-tests.rkt
#lang racket/base

(require "queue.rkt")

(require rackunit/text-ui)

(run-tests queue-tests)

Any kind of help in spotting the bug present would be appreciated. Thanks in advance.

A: The error you're referring to could be caused, I believe, by having the language level set incorrectly in your "queue.rkt" file.  In particular, the language for all three of these should be set to
"Use Language Declared in Source".
Honestly, I'm really not sure why you're building this as three separate modules; I think it's causing you additional difficulty, but it should certainly be possible to do it this way.
Edit: looks like you have paren problems.  In particular, you have three close-parens after your definition of 'size'.  Does DrRacket not highlight this problem for you when you run?
Edit 2: ooh, yucky: you're using "include". Don't use include.
Edit 3: Okay, here: I reformatted your code to be in one file:
(module queue racket

  (require rackunit)

  (provide make-queue enqueue dequeue top size)
  (struct queue (front back size) #:mutable #:transparent)

  (define (make-queue) (queue null null 0))

  (define (enqueue q elt)
    (set-queue-back! q (cons elt (queue-back q)))
    (set-queue-size! q (+ (queue-size q) 1))
    )
  (define (dequeue q)
    (cond  ((eq? (queue-size q) 0) null)
           ((null? (queue-front q))
            (begin
              (set-queue-front! q (cdr (reverse (queue-back q))))
              (set-queue-back! q null)
              (set-queue-size! q (- (queue-size q) 1))))
           (else
            (begin
              (set-queue-front! q (cdr (queue-front q)))
              (set-queue-size! q (- (queue-size q) 1))))
           )
    )

  (define (top q)
    (cond ((eq? (queue-size q) 0) null)
          ((null? (queue-front q)) (last (queue-back q)))
          (else (car (queue-front q)))))

  (define (size q)
    (queue-size q))

  (test-case "Initial Queue Properties"
             (let  ((q (make-queue)))
               (check-equal? (size q) 0 "Queue initially should have size zero.")
               (check-equal? (dequeue q) null "Dequeue on an empty queue returns null")
               (check-equal? (size q) 0 "Dequeue on empty queue leaves size as zero")
               ))

  (test-case "One Element queue ---- Functional test"
             (let ((q (make-queue)))
               (check-equal? (size q) 0 "Stack initially should be of size zero")
               (enqueue q 1)
               (check-equal? (size q) 1 "Added one element to back of queue")
               (check-equal? (top q) 1 "Take a sneak peak at our first element")
               (dequeue q)
               (check-equal? (size 1) 0 "size should now be zero")
               (check-equal? (dequeue q) null "dequeue on empty queue returns null")
               ))

  #;(test-case "One Element queue --- Internal Test"
             (let  ((q (make-queue)))
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (enqueue q 3)
               (check-equal? (size q) 1 "Added one element.")
               (check-equal? (queue-back q) '(3) "Is the element in the back list?")
               (check-equal? (top s) 3 "Look at our one element.")
               (check-equal? (queue-front q) '(3) "Is the element in the front list?")
               (dequeue s)
               (check-equal? (queue-front q) '() "Is the data empty now?")
               ))

  (test-case "Multi Element queue --- Functional Test"
             (let  ((q (make-queue))
                    (elts (list 8 6 7 5 3 0 9))
                    )
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size.")
                 )
               ))

  (test-case "Multi Element queue --- Ebb and Flow Test"
             (let  ((q (make-queue))
                    (elts (list 8 6 7 5 3 0 9))
                    )
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, first flow.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size, first ebb.")
                 )
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, second flow.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size, second ebb.")
                 )
               ))

  (test-case "Multi Element queue --- Internal Test"
             (let  ((q (make-queue))
                    (elts (list 5 8 8 2 3 0 0))
                    (tmp null)
                    )
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, second flow.")
                 (set! tmp (cons i tmp)) ; "push" element to a list
                 (check-equal? (queue-front q) tmp "Queue data is in correct form.")
                 )
               ))

  )

When I run this code, I get a pretty straightforward error in one of your test cases.
More generally, I'm taken aback that you would write this much test code without running it :). I would personally have written one small test case and then tried it out, rather than doing all of that work before discovering a more fundamental problem. I admire your tenacity, but I think you need a bit more paranoia :)
Let me know if you have more trouble.
EDIT: splitting into two files, per your request.
File 1: queue.rkt
(module queue racket

  (provide make-queue enqueue dequeue top size)
  (struct queue (front back size) #:mutable #:transparent)

  (define (make-queue) (queue null null 0))

  (define (enqueue q elt)
    (set-queue-back! q (cons elt (queue-back q)))
    (set-queue-size! q (+ (queue-size q) 1)))

  (define (dequeue q)
    (cond  ((eq? (queue-size q) 0) null)
           ((null? (queue-front q))
            (begin
              (set-queue-front! q (cdr (reverse (queue-back q))))
              (set-queue-back! q null)
              (set-queue-size! q (- (queue-size q) 1))))
           (else
            (begin
              (set-queue-front! q (cdr (queue-front q)))
              (set-queue-size! q (- (queue-size q) 1))))))

  (define (top q)
    (cond ((eq? (queue-size q) 0) null)
          ((null? (queue-front q)) (last (queue-back q)))
          (else (car (queue-front q)))))

  (define (size q)
    (queue-size q))

  )

File 2: queue-tests.rkt, in the same dir:
(module test-queue racket

  (require "queue.rkt"
           rackunit)

  (test-case "Initial Queue Properties"
             (let  ((q (make-queue)))
               (check-equal? (size q) 0 "Queue initially should have size zero.")
               (check-equal? (dequeue q) null "Dequeue on an empty queue returns null")
               (check-equal? (size q) 0 "Dequeue on empty queue leaves size as zero")
               ))

  (test-case "One Element queue ---- Functional test"
             (let ((q (make-queue)))
               (check-equal? (size q) 0 "Stack initially should be of size zero")
               (enqueue q 1)
               (check-equal? (size q) 1 "Added one element to back of queue")
               (check-equal? (top q) 1 "Take a sneak peak at our first element")
               (dequeue q)
               (check-equal? (size 1) 0 "size should now be zero")
               (check-equal? (dequeue q) null "dequeue on empty queue returns null")
               ))

  (test-case "One Element queue --- Internal Test"
             (let  ((q (make-queue)))
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (enqueue q 3)
               (check-equal? (size q) 1 "Added one element.")
               (check-equal? (queue-back q) '(3) "Is the element in the back list?")
               (check-equal? (top s) 3 "Look at our one element.")
               (check-equal? (queue-front q) '(3) "Is the element in the front list?")
               (dequeue s)
               (check-equal? (queue-front q) '() "Is the data empty now?")
               ))

  (test-case "Multi Element queue --- Functional Test"
             (let  ((q (make-queue))
                    (elts (list 8 6 7 5 3 0 9))
                    )
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size.")
                 )
               ))

  (test-case "Multi Element queue --- Ebb and Flow Test"
             (let  ((q (make-queue))
                    (elts (list 8 6 7 5 3 0 9))
                    )
               (check-equal? (size q) 0 "queue initially should have size zero.")
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, first flow.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size, first ebb.")
                 )
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, second flow.")
                 (check-equal? (top q) i "Testing top with multiple additions.")
                 )
               (for ((i (reverse elts))
                     (num (reverse (stream->list (in-range 1 8)))))
                 (check-equal? (top q) i "Testing top with multiple deletions")
                 (dequeue q)
                 (check-equal? (size q) (- num 1) "Testing size, second ebb.")
                 )
               ))

  (test-case "Multi Element queue --- Internal Test"
             (let  ((q (make-queue))
                    (elts (list 5 8 8 2 3 0 0))
                    (tmp null)
                    )
               (for ((i elts)
                     (num (in-range 1 8)))
                 (enqueue q i)
                 (check-equal? (size q) num "Testing size, second flow.")
                 (set! tmp (cons i tmp)) ; "push" element to a list
                 (check-equal? (queue-front q) tmp "Queue data is in correct form.")
                 )
               )))


text:
Q: What is the correct pattern to use when multiple events can cause a calculation? I've been having a lot of annoying problems with accessing bitmaps lately and I'm starting to think I need to re-evaluate the design of my application.
At present, I have one object that creates two others. One of these others provides a series of bitmaps (e.g. from a webcam) and the other provides a series of coordinate pairs (e.g. from a mouse or touchpad). The parent object has listeners for the events that the children objects generate. The events are have custom arguments which carry the new information (bitmap or coordinates) as a payload. For instance:
public class NewImageEventArgs : EventArgs
{
    public NewImageEventArgs(Bitmap image)
    {
        Image = image;
    }
    public Bitmap Image { get; private set; }
}

The listener methods in the parent object copy the payload to the object-level representation. When either listener (bitmap or coordinates) is triggered, they subsequently call a shared method, which uses both the bitmap and the coordinates to do some calculation.
private void PointerModule_NewPosition(object sender, NewPositionEventArgs e)
{
    this.p = e.Position;
    this.Invalidated();
}

It seems to me that my recurring problems with OutOfMemory and InvalidOperation ("Object is currently in use elsewhere") exceptions stem from the fact that each new event may be on a different thread. When a bitmap is being used on one thread, exceptions are raised when another thread tries to simultaneously access it.
Do I need to fundamentally change the shape of my program? Are there any precautions I can take to eliminate this type of problem?

A: EDIT:
I reread your question and I might have responded to a slightly different question than you've asked. However I fought the same problems with "Object is used elsewhere" exceptions and the lesson I learned is summarized in the link in the bottom. Neither bitmap.Clone() nor new Bitmap(source) creates deep image copy. This is causing the exceptions.
In my application I use pattern :
public class ImageProvider()
{
public event EventHandler LiveImageUpdated;
private object _currentImageLock = new object();

private Bitmap _currentImage;
public Bitmap CurrentImage
{
    get
      {
       lock (_currentImageLock)
         {
            return DeepImageCopy(_currentImage)
         }
       }
     private set
     {
       lock(_currentImageLock)
       {
            _currentImage = value
       }
        if (LiveImageUpdated != null)
        {
          foreach (Delegate del in LiveImageUpdated.GetInvocationList())
          {
              EventHandler handler = (EventHandler)del;
              handler.BeginInvoke(this, EventArgs.Empty, null, null);
           }
        }
     }
}

}
And I asked this question :
How to create a Bitmap deep copy
Application works without a problem. So basically I skipped the part with pushing new image as an argument and listeners are asking for deep copy of the image and they are not sharing images. Performancewise it works without a problem.


text:
Q: Using the return value of a function as the value in a dictionary in python I'm creating a python application that requires a user to log into a web service.  The credentials are passed to the server in a POST request as a json dictionary.  In order to avoid unnecessarily saving the password in a variable I figured I would do something like the following:
json.dumps({'username': raw_input('Username: '), 'password': getpass.getpass()})

*

*Is there any guarantee that raw_input will get called before getpass?

*Is there actually any benefit in this method over saving the output of the functions first and then creating the dictionary from the variables?

*Is this a 'pythonic' way of doing things?  My guess is no since there is a lot of stuff crammed into a single line and it's arguably not very readable.

A: *

*yes , since python is evaluated left to right like english. the functions will be called left to right.

*its slightly shorter

*not super pythonic but not aweful either

A: If you want to insure raw_input() called before getpass(), I think you should use variables like this:
username = raw_input('Username: ')
passwd = getpass.getpass()

user_dict = {username : passwd}

Use variable will make your code more readable and easy to maintenance or debug.
First, the code will be execute as raw_input('Username: ') then getpass.getpass() make a dict at last.
Second, it's more shorter and if your program is small and easy that's a good way .
Third, it's short, kind of pythonic I guess but not good in engineering side.