text:
Q: Pass a PHP variable in a link to a Modal box Hi i have a html link to a modal box which works perfectly, now what I am trying to do is pass a variable to the form in the modal box, how ever the link shows but nothing happens once it is clicked.
Here is my normal code:
    Add

Here is my PHP code
   echo "Add";

A: Use your normal code and add PHP only when you need a PHP variable:
<a href="#accSettings1?ip_address=<?=$ip_address?>" role="button" class="btn btn-small btn-primary hidden-tablet hidden-phone" data-toggle="modal" data-original-title=""> Add

if it's your application that doesn't work - then debug it first.
Use handwritten example to exercise with. Make it work. And then add a dynamical part using PHP to fill the variable. After that you have to verify if dynamical code produced the same result as a static one. To do that instead of hover you have to inspect page source and compare it with original code. Find the differences and correct them.
To me, such an url like #accSettings1?ip_address=value looks quite unusual.      ?ip_address=value#accSettings1 looks more familiar to me. Though I am not a JS pro, nor I know your app internals and URLs intention


text:
Q: Docker restore failing New to Docker.  Trying restore a mysql database from tar.
sudo docker run -it -v web_db_data:/volume -v /tmp:/backup alpine \ sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/web_db_data.tar.bz2"

I get the error:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:296: starting container process caused "exec: \" sh\": executable file not found in $PATH": unknown.

A: The shell "sh" is not found in the $PATH Variable of the container, you can try to install it in the Dockerfile, or you can try bash, maybe it is installed

A: You're running a command that was written for multiple lines with a \ and compressing it onto a single line. The \ then escapes a space so your container is looking the sh command with a leading space. Change:
sudo docker run -it -v web_db_data:/volume -v /tmp:/backup alpine \ sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/web_db_data.tar.bz2"

to
sudo docker run -it -v web_db_data:/volume -v /tmp:/backup alpine sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/web_db_data.tar.bz2"

or leave it as multiple lines:
sudo docker run -it -v web_db_data:/volume -v /tmp:/backup alpine \
  sh -c "rm -rf /volume/* /volume/..?* /volume/.[!.]* ; tar -C /volume/ -xjf /backup/web_db_data.tar.bz2"

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML5 Geolocation with ArcGIS for JavaScript API? My organization would prefer to use its own basemaps rather than those provided by ArcGIS Online due to the accuracy of information that is represented in them. The area we service is rapidly developing, and as such, there is no way for Esri to keep up with the data as well as we can.
As such, the basemaps are all created with a spatial reference based on a State Plane projection and hosted on our server this way. This causes problems whenever I attempt to use the HTML5 Geolocation feature in my code, as it returns a latitude/longitude value.
I have toyed with several methods for using these values in my code, primarily: using a Geometry Service to project them into my desired spatial reference or overlaying Esri's basemaps with our data in order to have our data converted to the spatial reference of their maps. However, the former method requires thorough error handling and the latter creates a significant loss of accuracy as well as some graphical issues due to labels overlapping.
Is there a better way to handle this issue?

A: I think your first solution, to project the Lat/Long coordinates to your preferred state plane is the right way to go. However, I'm not sure what you mean by "a Geometry Service". Do you mean you're using a 3rd-party web method to perform the coordinate transformation? If so, I would discourage that, as there's not a good reason to have such a dependency in your app, also because it is cleaner and faster to perform the coordinate conversion directly in your client.
With that said, have you tried using something like Proj4js to perform the Lat/Long --> state plane conversion directly in your client code?
I typically have the opposite problem, where our chosen web mapping API wants Lat/Long coordinates, and some functions feed it data from a legacy webservice that outputs sate plane coordinates. So I have to go from state plane --> Lat/Long. To do that, using Proj4js, looks like this:
Utils.ToProj4jsLonLat = function(x, y)
{
    // Append South Carolina State Plane Ft Proj4 expression to Proj4js projection candidates.
    // http://www.spatialreference.org/ref/esri/102733/proj4js/
    Proj4js.defs["ESRI:102733"] = "+title=NAD83SouthCarolinaStatePlaneFt +proj=lcc +lat_1=32.5 +lat_2=34.83333333333334 +lat_0=31.83333333333333 +lon_0=-81 +x_0=609600.0000000001 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs";

    var esri102733 = new Proj4js.Proj('ESRI:102733');
    var epsg4326 = new Proj4js.Proj('EPSG:4326');

    // Note that x = LONGITUDE and y = LATITUDE
    var point = new Proj4js.Point(x, y);

    Proj4js.transform(esri102733, epsg4326, point);
    return point;
};

So to make that work for you, you'd first need to look up your state plane projection definition as a Proj4 expression on SpatialReference.org. On the left side, look for the "Proj4js format" link, follow it, and copy the provided text.

Back in the code, prepend a title value (+title=WhatEverYouWantHere) to the start of the Proj4 expression, then flipflop the esriXXXXXX and epsg4326 parameters, and you'll have a function that uses Proj4js to perform a Lat/Long-->state plane coordinate conversion.


text:
Q: Listing files Jlist with jfilechooser I need to create a mp3 player, with a play list.
i am having difficult in listing at JList the files I am selecting with JFileChooser.
Can anybody help me doing this?
tks

A: Here is simple example for you, how to add selected files to JList :
public class ListExample extends JFrame {

    private DefaultListModel<String> model;

    ListExample() {
        JList<String> l = new JList<>(model = new DefaultListModel<String>());
        JButton btn = new JButton("add");
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser fc = new JFileChooser();
                fc.setMultiSelectionEnabled(true);
                fc.showOpenDialog(new JFrame());
                File[] selectedFiles = fc.getSelectedFiles();
                for(File f : selectedFiles){
                    model.addElement(f.getName());
                }
            }
        });
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(l));
        getContentPane().add(btn,BorderLayout.SOUTH);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new ListExample();
    }
}

Also read tutorial for lists


text:
Q: Omniauth user values return null I am making an app with rails, Rspotify, and Angular. A user authenticates with Spotify, they search for music, add music to playlists (make playlists), and then that info is stored in PostgreSQL. I make an API on all of that data, and display it with Angular.
I have been able to get the music + music search functionality working fine. I am working to make a user and user model, but I am not doing something right when it comes to sessions and authenticating the user. I get redirected to the right path, and don't see any errors, but my code returns
{
"country": null,
"display_name": null,
"email": null,
"images": null,
"product": null,
"external_urls": null,
"href": null,
"id": null,
"type": null,
"uri": null
}

Here is my code;
routes.rb
root to: "home#index"

  #auth
  get '/auth/:spotify/callback', to: 'sessions#create', via: [:get, :post]

  resources :users

  get '/home', to: 'users#home'

users_controller.rb
class UsersController < ApplicationController

    # user's home, where current null data is
    def home
        @spotify_user = RSpotify::User.new
        render :json => @spotify_user
    end

    def music
        @music = RSpotify::Track.search(params[:search])
        render :json => @music
    end

end

sessions_controller.rb
class SessionsController < ApplicationController

    def create
        auth = request.env["omniauth.auth"]
        @spotify_user = RSpotify::User.new(:provider => auth['provider'],
                          :uid => auth['uid'].to_s) || User.create_with_omniauth(auth)
        reset_session
        redirect_to "/home", :notice => "Authenticated!"
    end

    #sign out
    def destroy
      session[:user_id] = nil
      redirect_to root_url, notice: "Signed out!"
    end
end

users.rb
class User < ActiveRecord::Base

    def self.from_omniauth(auth)
        where(auth.slice("provider", "uid")).first || create_from_omniauth(auth)
    end

    def self.create_from_omniauth(auth)
        create! do |user|
            user.provider = auth["provider"]
            user.uid = auth["uid"]
            user.name = auth["info"]["nickname"]
        end
    end
end

I have also noticed that I do not receive a uid from Spotify. When I ran
render :text => "<pre>" + env["omniauth.auth"].to_yaml and return
in my sessions#create, it returned back info but the uid was blank. For reference, the only guide I have been able to use is RailsCasts 241 Simple Omniauth. I have been having this problem for a while, and I know I am sooooo close to figuring it out because I finally have zero errors, and can see the data. If anyone has done something like this before and could point me in the right direction, I would be beyond grateful. Thanks for any and all help.

A: You're confusing your app's Users with the Spotify gem's RSpotify::Users.
When a user signs up with OmniAuth, you have to save it to the database. Then, in your UsersController, you have to find that user and send it as json.
Look at what you are doing here:
@spotify_user = RSpotify::User.new
render :json => @spotify_user

You are creating a new user (which has every single attribute as nil) and then you are rendering it as json.


text:
Q: Return the name of the MySQL column where a select match was I have this MySQL query:
SELECT *
  FROM profiles
 WHERE phone = :query
    OR email = :query
    OR facebook = :query
    OR instagram = :query

I need to know what columns the match occurred in. So if the match occurred in.
How do I get that data in the MySQL query?
Edit: The optimal result would be to get all names of matched columns in the returned row.
Edit 2: If I have this table:
+----+---------+----------------+----------------+----------+-----------+
| ID |  Name   |     email      |     phone      | facebook | instagram |
+----+---------+----------------+----------------+----------+-----------+
|  0 | Jill    | jill@aol.com   | (123)123-1245  | fbjill   | igjill    |
|  1 | Jack    | jack@aol.com   | (123)111-1111  | fbjack   | igjack    |
|  2 | Bob     | bob@aol.com    | (123)222-2222  | fbbob    | igbob     |
|  3 | jMarie  | jill@aol.com   | (123)123-1245  | none     | none      |
+----+---------+----------------+----------------+----------+-----------+

and I query this:
SELECT *
      FROM profiles
     WHERE phone = fbjill
        OR email = fbjill
        OR facebook = fbjill
        OR instagram = fbjill

I need it to return the all the data of the row but with an additional columns stating the name of the columns it came from.

A: You could use CONCAT_WS here:
SELECT *,
    CONCAT_WS(',', IF(phone = :query, 'phone', NULL),
                   IF(email = :query, 'email', NULL),
                   IF(facebook = :query, 'facebook', NULL),
                   IF(instagram = :query, 'instagram', NULL)) AS matching_cols
FROM profiles
WHERE -- your conditions here

This would return a CSV string, consisting of up to 4 columns, which matched the incoming :query string parameter.

A: You can SELECT your conditions.
SELECT
    *,
    phone = :query as phone_match,
    email = :query as email_match,,
    facebook = :query as facebook_match,
    instagram = :query as instagram_match
FROM profiles
WHERE
    phone = :query
    OR email = :query
    OR facebook = :query
    OR instagram = :query

That will return 1 for each match, 0 for non-matches.

A: Use
SELECT *,
       MAKE_SET (       (phone = :query)
                  + 2 * (email = :query)
                  + 4 * (facebook = :query)
                  + 8 * (instagram = :query), 'phone',
                                              'email',
                                              'facebook',
                                              'instagram') from_where
FROM profiles
HAVING from_where != ''

or the same with LIKE operator (see fiddle).


text:
Q: Design of queryable web based results I'm trying to accomplish something like a facebook news feed wall, loading N number of results from the overall dataset, starting with the most recent, date descending. When you click "more", it displays the next N underneath and so on until you finish the dataset.
I'm struggling to come up with the best design to accomplish this. Ive always been told that stateless web services are the only way to build a scalable enterprise application, which means that as I understand it, keeping the whole results object cached serverside on the first call to the page, and just taking N results from it with each subsequent web service call is a no no?
If that's the case, then something like GetResults(int pageindex, int pagesize) would work.... and thats how I WAS going to do it but then I realised it would not work if someone added a new DB record in between calls. Eg you start with 23 wall feed items in the DB and want to display them 10 at a time.

*

*First call, page 1, page size 10 will return results 14-23 (most recent first)

*Someone then adds 2 new posts, so you have 25 now in the DB

*Second call, page 2, page size 10 will return results 6-15, two of which were already returned in the first call.

So this offsetting approach doesn't work because you can't guarantee the underlying dataset will remain the same between calls.
Im confused, how do I accomplish this?
Edit: Sorry a little more info. To avoid the problem of huge data table lookups, I had considered the option of pre-populating a "transient" table with the last few days data for that user when you first load the screen, then just reading the results a page at a time from that transient table to make it faster reading, with a slightly slower load time. Then when you exhaust that data, you bring in the next period (say 2 weeks) into the transient table and continue reading.
The difficulty is that users will "Post" items which then automatically will be picked up by users who match their search criteria. Eg if your criteria state you want to meet people between 25 and 32 and within 50 miles of you, then when you load up your news feed, you want it to show posts from all users who match your criteria. Kindof like a dynamic friends list.
How I was going to achieve this was at time of login, a stored proc would run which would populate a transient table in the DB by selecting all users and filtering down based on age and location criteria which I have in static lookup tables (postcode distances etc), then it will save the list of Users who match your criteria to this transient table for use whenever you then need to filter posts or search users. If you update your preferences, it will also recalculate this but only when you update prefs or re-login. So any new users signing up won't appear until you next login, which is fine I think.
Then when it comes time to display your news feed, all it does is retrieves this list of User Ids from the DB who match your criteria, then brings back all NewsFeedPosts which were posted by those users. Hey presto, dynamic news feed!
But obviously this is a subset of the entire NewsFeedPost table which is generated on the fly, so it doesn't make sense to recalculate this every time a user clicks "more", so this was how I was thinking about implementing it.
Tables - NewsFeedCurrent, NewsFeedRecent, NewsFeedArchive
New posts are created in the current table. Every night a batch job runs that moves all data from current that is 2 days old, to the recent table, and any data in the recent table that is a week old to the archive table.
The thinking being that 90% of the time, the user will only be interested in the last 2 days of data. So keep table small for access time. Another 9% of the time the user may want the last weeks data. So keep that separate in a secondary table. Then only 1% of the time the user wants data more than a week old so keep that in a larger, slow archive table that will be slower, but gives you performance boost by keeping current and recent tables small.
So when you first hit the news feed page, what it was going to do is take the pre-generated user list for your account and pull out all NewsFeedCurrent items and put them in a transient table, say TempNewsFeed under your user ID. You can then work with this resultset just by pulling back everything for your user id, no filtering required for items you arent interested in as they are pre-filtered. this will add a second or so to the page load but will improve response time when fetching results. Then when that data is exhausted, it will then - again using the list of users matching your criteria - pull out all relevant data from the Recent table, adding it to the TempNewsFeed table, allowing you to continue fetching data up to a week old. When thats exhausted, it will finally go to the archive table and using the user id list, pull out all data matching this and put in the temp table, allowing you to continue navigating the remaining data. This will give a fairly significant delay as it populates the archive data but if you are going back a week, then you will have to accept 5-10 seconds wait while it populates the data and says "loading data...". Once it has though, navigating historical data will be just as quick as recent data as it will all be in the transient table.
If you refresh the screen or go back onto it from another screen, it clears out the transient table and starts again from the Current table data.

A: Hope my answer makes sense, makes the right assumptions ...
I would divide the news feed into two sections.  The first is for incoming news - which would be powered with AJAX calls.  It is constantly saying "What is new?"  The second section is for older news, where the user can lazily load more news by scrolling down.
Newest News Items
The important point is to make note of the maximum news feed id on your page.  Let's imagine that is 10000.  When the user loaded the page, news feed id 10000 was the latest news item.
When the new section is updated with AJAX, we simply ask, "What is newer than id 10000?" and we load those items onto the page.  After we load them, we also increment the id on the page.  For example, if we start with id 10000 and we load five new news items, the new id would be 10005.  The next call would ask, "What is newer than 10005?"
Older News Items
The older section would keep track of the oldest news item on the page.  Let's imagine they scroll back for a weeks worth of news.  The minimum news item id would be 9000.  When they want to scroll back further, we simply ask, "What is older than 9000?"
The idea then is to maintain on the page the maximum news item id and the minimum news item id and then keep loading from that reference point.


text:
Q: get offline messages of publisher I have implemented XEP-0060 pubsub using openfire , i am able to publish messages over an existing node and i have other subscribers who can get those published messages.
now the issue is , i am not be able to receiver the old messages i mean if the subscribers are offline and when they come back online then how can i get the old messages which were being published by the publisher long time back.
My node on which publishers are publishing is configured as follows
<iq from="pubsub.example.com" type="result" id="meta1" to="lime@example.com/localhost">
<query xmlns="http://jabber.org/protocol/disco#info" node="mynode/loc">
<identity category="pubsub" type="leaf"/>
<feature var="http://jabber.org/protocol/pubsub"/>
<feature var="http://jabber.org/protocol/disco#info"/>
<x xmlns="jabber:x:data" type="result">
<field type="hidden" var="FORM_TYPE">
<value>http://jabber.org/protocol/pubsub#meta-data</value>
</field>
<field type="text-single" label="Short name for the node" var="pubsub#title">
<value/>
</field>
<field type="text-single" label="Description of the node" var="pubsub#description">
<value/>
</field>
<field type="boolean" label="Allow subscriptions to node" var="pubsub#subscribe">
<value>1</value>
</field>
<field type="boolean" label="New subscriptions require configuration" var="pubsub#subscription_required">
<value>0</value>
</field>
<field type="boolean" label="Deliver payloads with event notifications" var="pubsub#deliver_payloads">
<value>1</value>
</field>
<field type="boolean" label="Notify subscribers when the node configuration changes" var="pubsub#notify_config">
<value>1</value>
</field>
<field type="boolean" label="Notify subscribers when the node is deleted" var="pubsub#notify_delete">
<value>1</value>
</field>
<field type="boolean" label="Notify subscribers when items are removed from the node" var="pubsub#notify_retract">
<value>1</value>
</field>
<field type="boolean" label="Only deliver notifications to available users" var="pubsub#presence_based_delivery">
<value>0</value>
</field>
<field type="text-single" label="Type of payload data to be provided at this node" var="pubsub#type">
<value/>
</field>
<field type="text-single" label="Message body XSLT" var="pubsub#body_xslt">
<value/>
</field>
<field type="text-single" label="Payload XSLT" var="pubsub#dataform_xslt">
<value/>
</field>
<field type="list-single" label="Specify who may subscribe and retrieve items" var="pubsub#access_model">
<option>
<value>authorize</value>
</option>
<option>
<value>open</value>
</option>
<option>
<value>presence</value>
</option>
<option>
<value>roster</value>
</option>
<option>
<value>whitelist</value>
</option>
<value>open</value>
</field>
<field type="list-single" label="Publisher model" var="pubsub#publish_model">
<option>
<value>publishers</value>
</option>
<option>
<value>subscribers</value>
</option>
<option>
<value>open</value>
</option>
<value>open</value>
</field>
<field type="list-multi" label="Roster groups allowed to subscribe" var="pubsub#roster_groups_allowed"/>
<field type="jid-multi" label="People to contact with questions" var="pubsub#contact"/>
<field type="text-single" label="Default language" var="pubsub#language">
<value>English</value>
</field>
<field type="jid-multi" label="Node owners" var="pubsub#owner">
<value>mypublisher@example.com</value>
</field>
<field type="jid-multi" label="Node publishers" var="pubsub#publisher"/>
<field type="list-single" label="Select entity that should receive replies to items" var="pubsub#itemreply">
<value>owner</value>
</field>
<field type="jid-multi" label="Multi-user chat room to which replies should be sent" var="pubsub#replyroom"/>
<field type="jid-multi" label="Users to which replies should be sent" var="pubsub#replyto"/>
<field type="boolean" label="Send items to new subscribers" var="pubsub#send_item_subscribe">
<value>1</value>
</field>
<field type="boolean" label="Persist items to storage" var="pubsub#persist_items">
<value>1</value>
</field>
<field type="text-single" label="Max number of items to persist" var="pubsub#max_items">
<value>5</value>
</field>
<field type="text-single" label="Max payload size in bytes" var="pubsub#max_payload_size">
<value>5120</value>
</field>
</x>
</query>
</iq>

A: yeah i got it , when the subscriber gets online using following stanza he/she can retrive the old published items
subid is must in this case
<iq type='get'
    from='subscriber@example.com'
    to='pubsub.example.com'
    id='items1'>
  <pubsub xmlns='http://jabber.org/protocol/pubsub'>
    <items node='mynode'
subid="8839399494949"/>
  </pubsub>
</iq>


text:
Q: event listener works in jsFiddle but not on page
Possible Duplicate:
Why does jQuery or a DOM method such as `getElementById` not find the element?

This Event listener works on jsFiddle, but not when I call it from my PHP page.
function addDice() {
 var add = document.getElementById("add");
alert("test");
}

var el = document.getElementById("add");
el.addEventListener("click", addDice, false);

CAll ADD

I have the script in my index page between the


text:
Q: check db and return result I am simply trying to check db to see if user is friends with other user
in controller
    [NonAction]
    public bool IsFriend(int UserId, int id)
    {
            int query = _service.IsFriend(UserId, id);
            if (query > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
    }

this will work if I can pass the correct parameters for it
how could i use this from the view where i have data. I know its not  great id eg
IsFriend(User.Id, Model.Userid)
model.userid is friend checking
userid is id of signed in user
is this even possible to do this from a view?
using razor cshmtl

A: You may move the method to a more common place ( may be a helper class ) and then add a using statement in your view and call the function
@model YourPageViewModel

@using YourProject.HelperNameSpaceName

  @foreach(var friend in Model.KnownPeople)
  {

@friend.Name

@(IsFriend(friend.ID, Model.UserId)??"is friend":" is not friend")

  }

But what i recommend you to do is to do this thing in your action method instead of your view. Just do the check in your Action method and add only the Friend users to your Friends collection property of your view model. Then in the view, simply display it.
public ActionMethod Profile(int userId)
{
  var profileViewModel=new ProfileViewModel();
  var knownPeoples=repo.GetAllKnownPeopls(userId);
  foreach(var person in knownPeoples)
  {
    if(IsFriend(person.ID, profileViewModel.CurrentUserID))
      profileViewModel.Friends.Add(person);
  }
  return View(profileViewModel);
}

Now in your view, simply write display code only
@model ProfileViewModel
@foreach(var friend in Model.Friends)
{

@friend.Name

}


text:
Q: Symfony & Doctrine InnerJoin I'm trying do a join with doctrine query builder.
$query = $this->createQueryBuilder('od');
$query->innerJoin(Order::class, 'o', Expr\Join::WITH, 'o.orderid = od.orderid');
$query->where('o.userid = :userid')
$query->andWhere('od.orderstatusid IN (:orderstatusid)')
$query->setParameter('userid', $userid);
$query->setParameter('orderstatusid', array(5, 6, 7, 8, 10))

The request failed because the generate SQL is :
SELECT od FROM OrderDetail od INNER JOIN Order o WITH o.orderid = od.orderid WHERE o.userid = :userid AND od.orderstatusid IN (:orderstatusid)

Or it should be
SELECT od FROM OrderDetail od INNER JOIN Order o ON o.orderid = od.orderid WHERE o.userid = :userid AND od.orderstatusid IN (:orderstatusid)

I cant use $query->innerJoin(Order::class, 'o', Expr\Join::ON, 'o.orderid = od.orderid'); because i got this error :
[Syntax Error] line 0, col 91: Error: Expected Doctrine\\ORM\\Query\\Lexer::T_WITH, got 'ON'

If i dont use join condition, doctrine doesnt get it from the model so i dont have the good results.
How can you have a join and a where with querybuilder ?
Thanks for your help
Edit :
This is the model :
OrderDetail:
    type: entity
    table: order_detail
    repositoryClass: OrderDetailRepository
    id:
        orderdetailid:
            type: integer
            nullable: false
            options:
                unsigned: false
            id: true
    fields:
        ...
    lifecycleCallbacks: {  }
    manyToOne:
        order:
            targetEntity: Order
            inversedBy: orderdetails
            joinColumn:
                name: orderid
                referencedColumnName: orderid

Order:
    type: entity
    table: order
    id:
        orderid:
            type: integer
            nullable: false
            options:
                unsigned: false
            id: true
    fields:

    lifecycleCallbacks: {  }
    oneToMany:
        orderdetails:
            targetEntity: OrderDetail
            mappedBy: order
            fetch: EAGER

A: After checking out your entities I think your query can be simplified a bit. You don't actually need the WITH at all.
    $result = $this->createQueryBuilder('od')
        ->join('od.order', 'o')
        ->addSelect('o')
        ->where('o.userid = :userid')
        ->andWhere('od.orderstatusid IN (:orderstatusid)')
        ->setParameter('userid', $userid)
        ->setParameter('orderstatusid', array(5, 6, 7, 8, 10))
        ->getQuery()->getResult()
    ;

Doctrine is smart enough to know that od.order means the OrderDetail -> Order relationship and manage that join for you. You only really need to use WITH when you have some pretty specific query requirements.

A: In Doctrine documentation explain this:
$qb->innerJoin('u.Group', 'g', Expr\Join::WITH, $qb->expr()->eq('u.status_id', '?1'));

OR
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1');

OR
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id');

I recommend use this way:
$query->innerJoin('od.Order', 'o', 'WITH', 'od.orderstatusid IN (:orderstatusid)');

This way query is most optimtimal and don't need use "o.orderid = od.orderid" and "$query->andWhere('od.orderstatusid IN (:orderstatusid)')".


text:
Q: LINQ to Entities. How to create "Reusable" methods that "wrap" entities? SETUP
I have an "Order" class and an "OrderDetail" class.
The Order class has a property called "OrderDetails" of type IQueryable.
I have a method in each class called "GetData" and this method returns IQueryable of the class it is in.
The "GetData" methods are wrappers around the Entities that are used to transform the Entities into friendlier .NET classes / properties.
For example: The OrderDetail Entity has a "PullDate" in the database as Char(10) but I want the OrderDetail Class to have a property called "PullDate" that is of type DateTime in the class.
CODE
public class Order
{
    [Key]
    public int ID { get; set; }
    public IQueryable<OrderDetail> OrderDetails { get; set; }

    public static IQueryable<Order> GetData()
    {
        IQueryable<Order> orders;
        var db = new OrderEntities();

        // NOTE: This code will work
        try
        {
            var data =
                (from O in db.Orders
                 where O.OrderID == 1
                 select new Order
                 {
                     ID = O.OrderID,
                     OrderDetails =
                         (from OD in db.OrderDetails
                          where OD.OrderID == O.OrderID
                          select new OrderDetail
                          {
                              ID = OD.OrderDetailID,
                              OrderID = OD.OrderID,
                              PullDate = OD.PullDate == "00000000" ?
                                  (DateTime?)null : db.yyyyMMddToDate(OD.PullDate),
                              Description = OD.Desc
                          })
                 });

            orders = data.AsQueryable();
            var orderList = orders.ToList();
        }
        catch (Exception ex)
        {
            throw;
        }

        // NOTE: This code will NOT work
        try
        {
            var data = (from O in db.Orders
                        where O.OrderID == 1
                        select new Order
                        {
                            ID = O.OrderID,
                            OrderDetails = (from OD in OrderDetail.GetData(db)
                                            where OD.OrderID == O.OrderID
                                            select OD)
                        });

            orders = data.AsQueryable();
            var orderList = orders.ToList();
        }
        catch (Exception ex)
        {

            throw;
        }

        return orders;
    }
}

public class OrderDetail
{
    [Key]
    public int ID { get; set; }
    public int OrderID { get; set; }
    public DateTime? PullDate { get; set; }
    public string Description { get; set; }

    public static IQueryable<OrderDetail> GetData(OrderEntities db)
    {
        IQueryable<OrderDetail> orderDetails;

            var data = (from OD in db.OrderDetails
                        select new OrderDetail
                        {
                            ID = OD.OrderDetailID,
                            OrderID = OD.OrderID,
                            PullDate = OD.PullDate == "00000000" ?
                                (DateTime?)null : db.yyyyMMddToDate(OD.PullDate),
                            Description = OD.Desc
                        });

            orderDetails = data.AsQueryable();
            var orderList = orderDetails.ToList();

            return orderDetails;
    }
}

ERROR
    LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Models.OrderDetail] GetData(Models.OrderEntities)' method, and this method cannot be translated into a store expression.
Request
I would like the Order.GetData method to call the OrderDetail.GetData method using LINQ.
I need to "join" the GetData methods together or "sub select" the OrderDetail.GetData while inside the Order.GetData class.
Both of the classes are querying EntityFramework inside of their GetData methods.
Projection is a requirement.
My goal is to create "Reusable" methods like "GetData" in my DTO classes that will contain specific SQL / Entity logic.
For example, I am using a lot of custom SQL functions like "db.yyyyMMddToDate" in my DTO classes to transform the Entities into something more object / .NET friendly and I don't want to "retype" all that logic each time I need to "join / sub select" data from entities.
In LINQ to Objects this would be the same as joining two different lists from different classes.
But it seems that LINQ to Entity does not know how to join methods from other classes even if the method is marked as Queryable.
I understand that LINQ to Entity is treating the "GetData" methods as if they were SQL functions but I need a way to tell LINQ to Entity that these are just more Entities to join together to get the results.

A: You get this error because, when dealing with LINQ to Entities, you are not passing in lambdas to the LINQ operators like you do in LINQ to Object. You are passing expression trees. The code that you write in those queries will never be executed. It will be interpreted by Entity Framework as a series of instruction to translate into an other language like SQL.
The GetData method doesn't mean anything in SQL. In fact, it doesn't mean anything outside of your own program. This is why LINQ to Entities do not recognize your method as a valid construct.
To access the details of an order in a scenario like yours, you need to build your query so that EF knows to include the OrderDetails entities inside the primary query using the Include operator. When doing this, EF expects your object to have a property similar to this one:
public virtual ICollection<OrderDetail> OrderDetails { get; set; }

This is how EF will know where to put the resulting objects from queries that includes those elements.
var ctx = new DatabaseContext();
var query = ctx.Orders
   .Where(o => o.OrderId == 1)
   .Include(o => o.OrderDetails);

This query will asks the remote server for all Orders, with an OrderId of 1, with all its matching OrderDetails. EF will then automatically create all of the related client side entities for you.
Here's the official documentation on EF about this topic: http://msdn.microsoft.com/en-ca/data/jj574232.aspx


text:
Q: couple of messages in one packet I wrote a dissector,
I found one packet which contains couple of different/indifferent messages inside it,
Can someone point on the problem ?
Is this even a problem ?
I reassemble TCP packets...
This is the function of dissection:
(FRAME_HEADER_LEN = 8)
static void
dissect_PROTOC(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
    //Reassembling TCP fragments
    tcp_dissect_pdus(tvb, pinfo, tree, TRUE, FRAME_HEADER_LEN,
                     get_PROTOC_message_len, dissect_PROTOC_message);

}

static guint get_PROTOC_message_len(packet_info *pinfo, tvbuff_t *tvb, int offset)
{
    /* the packet's size is "length" + 4bytes of TYPESIZE + 4bytes of LENGTHSIZE + 256bytes of CONTEXTIDSIZE */
    return (guint)(tvb_get_ntohl(tvb, offset + 4) + CONTEXT_ID_SIZE + TYPE_SIZE + LENGTH_SIZE); /* e.g. length is at offset 4 */
}

static void dissect_PROTOC_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
    /* my dissecting code */
    guint32 packet_type = tvb_get_ntohl(tvb, 0);

    col_set_str(pinfo->cinfo, COL_PROTOCOL, "PROTOC");
    /* Clear out stuff in the info column */
    col_clear(pinfo->cinfo,COL_INFO);
    col_add_fstr(pinfo->cinfo, COL_INFO, "%d > %d [%s]",pinfo->srcport, pinfo->destport,
             val_to_str(packet_type, packettypenames, "Unknown (0x%02x)"));

    if (tree) { /* we are being asked for details */
        proto_item *ti              = NULL;
        proto_tree *PROTOC_tree         = NULL;
        proto_item *PROTOC_data         = NULL;
        proto_tree *PROTOC_data_tree    = NULL;
        guint32 type    = 0;
        guint32 length  = 0;
        gint offset     = 0;

        ti = proto_tree_add_item(tree, proto_PROTOC, tvb, 0, -1, ENC_NA);
        proto_item_append_text(ti, ", Type: %s",
            val_to_str(packet_type, packettypenames, "Unknown (0x%02x)"));
        PROTOC_tree = proto_item_add_subtree(ti, ett_PROTOC);

        //getting type
        type = tvb_get_ntohl(tvb, offset);
        proto_tree_add_item(PROTOC_tree, hf_PROTOC_pdu_type, tvb, 0, TYPE_SIZE, ENC_BIG_ENDIAN);
        offset += TYPE_SIZE;

        //getting length for the data length
        length = tvb_get_ntohl(tvb, offset);
        proto_tree_add_item(PROTOC_tree, hf_PROTOC_len, tvb, offset, LENGTH_SIZE, ENC_BIG_ENDIAN);
        offset += LENGTH_SIZE;
        proto_tree_add_item(PROTOC_tree, hf_PROTOC_contextid, tvb, offset, CONTEXT_ID_SIZE, ENC_BIG_ENDIAN);
        offset += CONTEXT_ID_SIZE;
        PROTOC_data = proto_tree_add_item(PROTOC_tree, hf_PROTOC_data, tvb, offset, length, FALSE);
        PROTOC_data_tree = proto_item_add_subtree(PROTOC_data, ett_PROTOC_data);
        offset += length;

    }
}

A:
I found one packet which contains couple of different/indifferent messages inside it,

...

I reassemble TCP packets...

That's pretty common for protocols running over TCP; there is no guarantee that TCP segment boundaries will correspond to packet boundaries in protocols running on top of TCP.  A TCP segment can contain parts of, or all of, more than one higher-level protocol packet, and a higher-level protocol packet can be composed of data from more than one TCP segment.


text:
Q: How to implement "User can delete his own posts" on the "Role-based access control" model? I've read some articles about Role-based access control, but not clear enough to handle this case: how to implement "user can delete his own posts"?
For normal roles and permissions, when user do something, I can just check if the roles and permissions the user have, and determine if the user can do it.
But for "user can delete his own posts", I have to check if the posts belong to him or not. So I have to hard-code something, then it is out of the control of the control system.
Do I miss something and how to do it correctly?

A: It's not entirely clear to me what problem you are trying to solve. You always have to "hard-code" something since you need to define who can access what. Something is not out of the control system either if you decide it should be in, it really depends on your implementation.
For what you are trying to do, I would generally define an "owner" role then define an access such as:
"owner" can "delete" "resource"

So there has to be some programmatic part where you find out whether the user is indeed the owner or not. Usually, this can be done by associating each resource with, for example, an "ownerId" property. If userId == ownerId, then the role of the current user is "owner".

A: This requires support in the RBAC layer for "business rules". When such is available, it provides you the touch of dynamic decision that is needed.
Basically, the biz rule is a piece of code that is being run every time the permission is checked. This code is static but expect parameters to be handed to it. Here's an example (PHP shown):
// This code expect two given parameters: $params['owner_id'] and $params['user_id']
if ($params['owner_id'] == $params['user_id']) {
  return true;
}
return false;
// This code assumes that returning true means 'permission granted' and returning
// false means permission not granted

You didn't state your underlying technology. That could help you get more accurate answers.


text:
Q: ECMA in Datapower anybody know how to access XML data using xpath expression in ECMA Script(datapower)?
IBM infocenter doesn't have this information on how to access XML data
Please provide if you have any sample script for accessing XML data
Thanks

A: GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented.
I have however used the modules XPATH and DOM with great success.
Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:

*

*dom-parser.js

*dom.js

*sax.js

*xpath.js

To use it in DataPower GWS you first need to get the XML data from INPUT:
// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {

    if (readAsBuffersError) {
        console.error('Error on readAsBuffers: ' + readAsBuffersError);
        session.reject('Error on readAsBuffers: ' + readAsBuffersError);
    } else {

        if (data.slice(0,5).toString() === '<?xml') {

            console.log('It is XML!');
            parseXML(data);

        }
    } //end read as buffers error
}); //end read as buffer function

function parseXML(xml) {
    // Load XML Dom and XPath modules
    var select = require('local:///xpath.js');
    var dom = require('local:///dom-parser.js');

    var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
    // Get attribute
    var nodes = select(doc, "//root/element1/@protocol");
    try {
        var val = nodes[0].value.toString();
        console.log('found xml attribute as ['+val+']');
    } catch(e) {
        // throw error here
    }

    // Get an element
    nodes = select(doc, "//root/element1/child1");
    try {
        var val = nodes[0].firstChild.data;
        console.log('elemnt found as ['+val+']');
    } catch(e) {
        //throw error here
    }

}

That should be a working sample... You need to change the path for the modules if you move them.
I have a directory in store:/// where I add my GWS modules.
Hope you'll get it to fly!

A: At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:
//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
    if (error) {
    //error behaviour
  } else {
    var domTree;
    try {
      domTree = XML.parse(nodeList);
    } catch (error) {
      //error behaviour
    }

    var transform = require('transform'); //native gatewayscript module
    transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
      if(error){
        //error behaviour
      }
      //some use of result, for example putting it to output
      session.output.write(result);
    }
  });
});


text:
Q: glClearBufferfv - not declared in this scope? EDIT: If anyone has this kind of error, and is using GLEW, when using OpenGL 4.5 functions, the following will help:
glewExperimental = GL_TRUE;

after that just initialize GLEW and you'll be fine.
I´m just starting out with OpenGL. Currently I am trying to clear the whole screen with red, as seen in this code here:
#include "GLFW/glfw3.h"

#define WIDTH 1280
#define HEIGHT 720

int main(void)
{
    GLFWwindow *window;

    if(!glfwInit()) {
        return -1;
    }

    window = glfwCreateWindow(WIDTH, HEIGHT, "Test OpenGL", NULL, NULL);

    if(!window) {
        glfwTerminate();
        return -1;
    }

    glfwMakeContextCurrent(window);
    static GLfloat red[] = {1.0f, 0.0f, 0.0f, 1.0f};
    glClearBufferfv(GL_COLOR, 0, red);

    while(!glfwWindowShouldClose(window)) {
        //glEnableClientState(GL_VERTEX_ARRAY);
        //glDisableClientState(GL_VERTEX_ARRAY);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

But there is a problem. I am using g++ to compile the code written in Code::Blocks. Also, I am learning with the OpenGL SuperBible 7th edition, where I got the code for clearing the screen with red. Before I was using glClearColor(255, 0, 0, 0) and then glClear(GL_COLOR_BUFFER_BIT);
But in this book the screen is cleared with glClearBufferfv, which throws the following exception:
error: 'glClearBufferfv' was not declared in this scope
Of course I want to use the code in the book for learning purposes, so it would be great, if that would work. Sadly, it doesn´t. Any idea, why?

A: glClearBufferfv is a newer OpenGL function, which means it is technically possible that a graphics card that speaks OpenGL doesn't support it. This means that the function needs to be loaded, either by you or by an OpenGL loading library, before you can use it.
The SuperBible example code comes with the gl3w loader as part of its s7 helper library. You could either:

*

*use s7, which the other examples in the book will likely depend on as well

*skip s7 and use gl3w or any other loader, like my personal favourite libepoxy

*don't use a loader and load the functions you need by hand. This gets tedious very quick, but it does mean you get to see what's going on.

The GLFW documentation has some useful pointers as well.


text:
Q: Angular 2 datetime formatting causing incorrect time to appear So I'm returning some date times from a database in my Ionic application.
The data coming back is correct, however when I use Angular's recommended way of formatting datetimes, the time changes to something incorrect.
All I want to do is take my date time and simply display the time, leaving out the day of the day/month/year.
For example:
The time I'm getting back is this 2017-03-19T08:00:00
When I use shortTime to only return the time however, this is what is displayed in my browser 2:00 AM.
Question: What is causing this time format discrepancy to happen and what can I do to resolve the issue?
Edit: Here's a screenshot of the data i'm returning and the front end html

home.html
<ion-item text-wrap *ngFor="let item of dateEvent">

Event Start: {{item.EventStart | date:'shortTime'}}

Event End: {{item.EventEnd | date:'shortTime'}}

    </ion-item>
  </ion-item>
  <ion-item *ngIf="!hasEvent" text-wrap>

Looks like you don't have any events on {{dateTime | date: 'MM/dd/YYYY'}}!

  </ion-item>

NEXT EVENT:

  <ion-item *ngIf="hasNextEvent">
  <ion-item text-wrap *ngFor="let item of nextEvent">

Date: {{item.EventStart | date:'MM/dd'}}

Event Start: {{item.EventStart | date:'shortTime'}}

Event End: {{item.EventEnd | date:'shortTime'}}

    </ion-item>
  </ion-item>
  <ion-item *ngIf="!hasNextEvent" text-wrap>

Looks like you don't have any future events scheduled!

    </ion-item>
</ion-content>

A: It appears to be working correctly with that value. Are you sure you have the correct value?
Heres a working example of the date filter with shortTime:

(function() {

  'use strict';

  angular.module('app', []);

})();

(function() {

  'use strict';

  angular.module('app', []).controller('MainController', MainController);

  MainController.$inject = ['$filter'];

  function MainController($filter) {

    var vm = this;

    vm.date = "2017-03-19T08:00:00";

    vm.formattedDate = $filter('date')(vm.date, 'shortTime');

  }

})();

  Formatted date in HTML template binding: {{MainCtrl.date | date: 'shortTime'}}

  Formatted date from controller: {{MainCtrl.formattedDate}}

A: The Date you are getting in the object you provided is 2017-03-19T08:00:00 a UTC date which is equal to 2:00 AM (Mountain Time) on the same day. You don't need to worry about it. JavaScript always converts the Date to Local Timezone before showing it in the browser. Similarly when we input a Date it takes Local Timezone and deliver in as UTC Date to server.
I just tried with the same Date Time you have provided. It showed me Sun Mar 19 2017 13:30:00 GMT+0530 (India Standard Time).


text:
Q: ¿Cómo buscar por Objeto de Referencia en una ruta GET usando Express y Moongose? Tengo una simple base de datos "diseñada" con 3 Schemas en Moongose: examen.js,pregunta.js, y respuesta.js
examen.js:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const ExamenSchema = new Schema({
    titulo: {
        type: String,
        required: [true, 'debes escribir un titulo']
    },
    numero_preguntas: {
        type: Number
    },
    acabado: {
        type: Boolean,
        default: false
    }
})

const Examen = mongoose.model('examen', ExamenSchema)

module.exports = Examen;

pregunta.js:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const PreguntaSchema = new Schema({
    examen: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'examens'
    },
    pregunta: {
        type: String,
        required: [true, 'debes escribir una pregunta']
    }
});

const Pregunta = mongoose.model('pregunta', PreguntaSchema)

module.exports = Pregunta;

Pregunta tiene el campo examen que es donde se tiene que meter el ObjectId de un examen, para que se sepa a que examen pertenece esa pregunta. Obviamente se pueden agregar varias preguntas con el mismo ObjectId en el campo examen ya que los examenes tiene varias preguntas habitualmente.
Lo que quiero es tener una ruta GET para obtener las preguntas que pertenecen a un ObjectId (es decir, obtener las preguntas de un examen en concreto).
Actualmente sólo tengo la ruta Get para obtener una pregunta por id:

router.get('/pregunta/:preguntaId', (req,res) => {

    const id = req.params.preguntaId;
    Pregunta.findById(id)
            .exec()
            .then(doc => {
                console.log(doc)
                res.status(200).json(doc)
            }).catch(err => {
                console.log(err)
                res.status(500).json({error: err})
            })
})

Me pregunto si existe algún método como el de arriba findById que funcione para lo que yo busco:

router.get('/pregunta/:referenciaExamen', (req,res) => {

    const id_ExamenDeProgramar = req.params.referenciaExamen;
    // Pregunta.Buscar preguntas asignadas con el ObjectId(id_ExamenDeProgramar)
    //

})

Hacer lo siguiente no ha servido:
const id = req.params.referenciaExamen;
Pregunta.find({examen: id})

A: A mi punto de vista te estas metiendo en un problema de aggregate. Para lograr lo que quieres hacer vas a necesitar algo como esto:

var ObjectId = mongoose.schema.ObjectId

var arregloAggregate = [
    {
        $match: {
            examen: ObjectId(id)
        }
    },

    {
        $group: {
            _id: $examen
            // ... mas codigo
        }

    }

    // Mas codigo ....

]

PreguntaSchema.aggregate(arregloAggregate).exec()....

Yo lo resolveria con un schema de esta forma:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const ExamenSchema = new Schema({
    titulo: {
        type: String,
        required: [true, 'debes escribir un titulo']
    },

    preguntas: [

        pregunta: {
            type: String,
            required: [true, 'debes escribir una pregunta']
        },

        respuesta: String
    ]
})

const Examen = mongoose.model('examen', ExamenSchema)

module.exports = Examen;

Después si hay un alumno que deba hacerlo solo referenciamos sus respuestas correctas
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const ExamenSchema = require('./examen.model')

const AplicanteSchema = new Schema({
    examenes: [{
        examen: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'examens'
        },
        aciertos: Number,
        malas: Number,
        calificacion: Number,

    }]
})

const Aplicante = mongoose.model('examen', AplicanteSchema)

module.exports = Aplicante;


text: Q: Static transforms using tf2 I'm trying to publish a static transform using tf2. The end goal is to run turtlesim which subscribes to the static transform and moves accordingly. How do I go about doing this?


text:
Q: Devise force updating password during user profile update When I try to update my user profile Devise force to update password even if the auto-prepared form has this label: Password (leave blank if you don't want to change it). Why?
EDIT:
I want user confirm password every time he change his settings! The problem is that there are three fields:
Password (leave blank if you don't want to change it)
Password confirmation
Current password (we need your current password to confirm your changes)
I want that if user leave password (FIRST FIELD) blank devise don't give error back.

A: See this guide on how to update user profiles without changing the password:
https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password
You can also create your own Users controller with an edit form, and only update the fields you need.
EDIT
If you enter the current password field and NOT the first two fields, there will be no error. This is the default behavior of devise. If you want the current password field to be the first field for the user, move it up in the view.

A: You should NOT add this line in User Model:
validates :password, length: {minimum: 6}


text:
Q: Ajax ejecuta las validaciones pero no envía el formulario Hola que tal? Llevo varios dias tratando de enviar datos desde un formulario a mi correo electrónico. Al menos ya hice que mi función validar se ejecute dentro de la función por donde envio los datos de ajax pero ahora tengo un error con el envío de datos.
Uptedate:
Esta es la función completa que tengo actualmente en mi código fuente.
function validarform()
{
  $('.alert').remove();

  var nombre=$('#nombre').val(),
      email=$('#email').val(),
      asunto=$('#asunto').val(),
      mensaje=$('#mensaje').val();

   if(nombre=="" || nombre==null)
  {
      color("nombre");
      Alerta("Campo Nombre es obligatorio");
      return false;

    }
    else
    {
      var error =  /^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]*$/;
      if (!error.test(nombre)) {

        color("nombre");
      Alerta("No se permiten caracteres especiales, ingresar un nombre valido");
      return false;
      }
  }

    if(email=="" || email==null)
    {
      color("email");
      Alerta("Campo Email es obligatorio");
      return false;

    }
    else
    {
      var error =  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
      if (!error.test(email)) {

        color("email");
      Alerta("Por favor ingrese un Email valido");
      return false;
      }
    }

    if(asunto=="" || asunto==null)
    {
      color("asunto");
      Alerta("Campo Asunto es obligatorio");
      return false;

    }
    else
    {
      var error =  /^[,\\.\\a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]*$/;

      if (!error.test(asunto)) {

        color("asunto");
      Alerta("No se permiten caracteres especiales");
      return false;
      }
    }

    if(mensaje=="" || mensaje==null)
    {

      color("mensaje");
      Alerta("Por favor ingrese un mensaje");
      return false;

    }
    else
    {
      var error =  /^[,\\.\\a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]*$/;
      if (!error.test(mensaje)) {

        color("mensaje");
      Alerta("No se permiten caracteres especiales");
      return false;
      }
    }

    return true;

}

$('input').focus(function(){

    $('.alert').remove();
    $('.success').remove();
    colordefecto('nombre');
    colordefecto('email');
    colordefecto('asunto');
});

$('textarea').focus(function(){
    $('.success').remove();
    $('.alert').remove;
    colordefecto('mensaje');
});

function color(color)
{
    $('#' + color).css({

        border: "1px solid #f77474"
    });

    //$('#' + color).val('');
}

function colordefecto(color)
{
  $('#' + color).css({
    border: "1px solid #999"
    });

}

//alerta

function Alerta(alert){

  $('#nombre').before ('
 Alerta: '+ alert +'
');

}

//enviamos el formulario

$(function() {
    $('#btn_enviar_contacto').on('click',function(e){
        e.preventDefault();
        if( validarform() ){
            var url="Mail.php";
            var nombre=$('#nombre').val();
            var email=$('#email').val();
            var asunto=$('#asunto').val();
            var mensaje=$('#mensaje').val();
            var toPost={nombre:nombre,email:email,asunto:asunto,mensaje:mensaje};

            var request = $.ajax({
                url: url,
                method: "POST",
                data: toPost,
                cache: false,
                contentType: false,
                processData: false,
                dataType: "json"
            });

            request.done(function(respuesta) {
                   console.log("respuesta",respuesta);
                   $('.contacto')[0].reset();
                   if(respuesta){
                        $('#nombre').before ('
 Gracias '+ respuesta.success +' !!! :  en breve nos contactaremos contigo
');
                   }
            });

            request.fail(function(jqXHR, textStatus) {
                alert(`La petición falló ${textStatus}`);
            });
        }
    });
});

HTML:
 <form action="Mail.php" method="POST" class="contacto">

    Name
    <input type="text" name="nombre" id="nombre" >

    Email
    <input type="email" name="correo-e" id="email" >

    Asunto
    <input type="text" name="asunto" id="asunto" >

  Escribe un comentario
 <textarea name="mensaje" id="mensaje" cols="30" rows="10" ></textarea>

   <button type="button" id="btn_enviar_contacto">Enviar</button>

    </form>

Tendre algun error con la URL de archivos? o sera que debo aplicar otra cosa a mi función?
Funcion de validaciones:
function validarform()
{
  $('.alert').remove();

  var nombre=$('#nombre').val(),
      email=$('#email').val(),
      asunto=$('#asunto').val(),
      mensaje=$('#mensaje').val();

   if(nombre=="" || nombre==null)
  {
      color("nombre");
      Alerta("Campo Nombre es obligatorio");
      return false;

    }
    else
    {
      var error =  /^[a-zA-ZñÑáéíóúÁÉÍÓÚ ]*$/;
      if (!error.test(nombre)) {

        color("nombre");
      Alerta("No se permiten caracteres especiales, ingresar un nombre valido");
      return false;
      }
  }

    if(email=="" || email==null)
    {
      color("email");
      Alerta("Campo Email es obligatorio");
      return false;

    }
    else
    {
      var error =  /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
      if (!error.test(email)) {

        color("email");
      Alerta("Por favor ingrese un Email valido");
      return false;
      }
    }

    if(asunto=="" || asunto==null)
    {
      color("asunto");
      Alerta("Campo Asunto es obligatorio");
      return false;

    }
    else
    {
      var error =  /^[,\\.\\a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]*$/;

      if (!error.test(asunto)) {

        color("asunto");
      Alerta("No se permiten caracteres especiales");
      return false;
      }
    }

    if(mensaje=="" || mensaje==null)
    {

      color("mensaje");
      Alerta("Por favor ingrese un mensaje");
      return false;

    }
    else
    {
      var error =  /^[,\\.\\a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]*$/;
      if (!error.test(mensaje)) {

        color("mensaje");
      Alerta("No se permiten caracteres especiales");
      return false;
      }
    }

    return true;

}

PHP: Mi codig PHP actual en mi codigo fuente, debido a varias actualizaciones no he conseguido que el mail llegue a mi correo.
<?php
    #$_POST es super global, no necesitas pasarle los datos a la funcion
    function ajaxEnviarDatos(){
        #$_POST es superglobal y un array por tanto podemos referirnos a él directamente
        $nombre=$_POST['nombre'];
        $email=$_POST['email'];
        $asunto=$_POST['asunto'];
        $mensaje=$_POST['mensaje'];

        $enviar_a = 'guillermo12@gmail.com'; /*Estaba probando otros correos*/
        $asunto = $asunto;
        $mensaje_preparado = "De: $nombre \n";
        $mensaje_preparado .= "Correo: $email \n";
        $mensaje_preparado .= "Mensaje: " . $mensaje;

        #Evaluamos qué ocurre cuando usamos mail
        if ( mail($enviar_a, $asunto, $mensaje_preparado) ) {
            $respuesta=$nombre;
            $respuesta.=$email;
            $respuesta.=$asunto;
            $respuesta.=$mensaje;
            #En vez de un texto plano, creamos un array
            #tendrá la clave success si mail es exitoso
            $mData=array("success"=>$respuesta);
        }else{
            #O tendrá la clave error si hay un error
            $mData=array("error"=>"mail no ha funciona, revisa tu configuración");
        }
        return $mData;
    }

    if(isset($_POST['nombre'])){
        $mData=ajaxEnviarDatos();
    }else{
        $mData=array("error"=>"Falta el nombre", "datos"=>$_POST);
    }
    echo json_encode($mData);

?>

A: Intenta de este modo.
He corregido un poco el código, quitando elementos innecesarios o repetitivos y aplicando prácticas recomendadas como el uso de function en vez de document ready, el uso de done en vez de success, incorporando además un control de fallos de la petición Ajax mediante fail.
Atención a esto: En la petición Ajax indicaste un dataType: "json". Entonces desde el PHP deberías devolver un JSON. Si devuelves contenido plano entonces cámbialo por html.
Prueba de este modo y me dices si hay algún problema.
Javascript (cliente)
$(function() {
    $('#btn_enviar_contacto').on('click',function(e){
        e.preventDefault();
        if( validarform() ){
            var url="Mail.php";
            var nombre=$('#nombre').val();
            var email=$('#email').val();
            var asunto=$('#asunto').val();
            var mensaje=$('#mensaje').val();
            var toPost: {nombre:nombre,email:email,asunto:asunto,mensaje:mensaje};

            var request = $.ajax({
                url: url,
                method: "POST",
                data: toPost,
                cache: false,
                contentType: false,
                processData: false,
                dataType: "json"
            });

            request.done(function(respuesta) {
                   console.log("respuesta",respuesta);
                   $('.contacto')[0].reset();
                   if(respuesta.success){
                        $('#nombre').before ('
 Gracias '+ respuesta.success +' !!! :  en breve nos contactaremos contigo
');
                   } else {
                       console.log(respuesta.error); //Esto se puede mostrar en un div si quieres
                   }
            });

            request.fail(function(jqXHR, textStatus) {
                alert(`La petición falló ${textStatus}`);
            });
        }
    });
});

PHP (servidor)
Tienes un error fundamental en tu código PHP: te estás refiriendo mal a los valores que debería haber en $_POST. Como lo tienes no encontraría jamás los datos porque las claves de array en PHP son case sensitive. Si observas en el código Javascript, el objeto que estás enviando a PHP es este:
var toPost: {nombre:nombre,email:email,asunto:asunto,mensaje:mensaje};

¿Qué significa eso, que los nombres de clave serán los que hay a la izquierda de cada par, o sea, nombre, email, asunto, mensaje ... pero si en el $_POST usas Nombre, Email...empezando con mayúscula, no los encontrará nunca.
Otro error (de redundancia) es que $_POST en sí es un array, por lo tanto, no tiene sentido sacar los datos de $_POST que es ya un array, para meterlos en otro array.
Otro error es que no estabas respondiendo un JSON en sí. Para un JSON tienes que crear un array. Aquí he creado un array con una propiedad  success cuando el email se mande, o error cuando no se mande, evaluando a su vez con if la llamada a mail()
<?php
    #$_POST es super global, no necesitas pasarle los datos a la funcion
    function ajaxEnviarDatos(){
        #$_POST es superglobal y un array por tanto podemos referirnos a él directamente
        $nombre=$_POST['nombre'];
        $email=$_POST['email'];
        $asunto=$_POST['asunto'];
        $mensaje=$_POST['mensaje'];

        $enviar_a = 'guillermo@gmail.com';
        $asunto = $asunto;
        $mensaje_preparado = "De: $nombre \n";
        $mensaje_preparado .= "Correo: $email \n";
        $mensaje_preparado .= "Mensaje: " . $mensaje;
        #Evaluamos qué ocurre cuando usamos mail
        if ( mail($enviar_a, $asunto, $mensaje_preparado) ) {
            $respuesta=$nombre;
            $respuesta.=$email;
            $respuesta.=$asunto;
            $respuesta.=$mensaje;
            #En vez de un texto plano, creamos un array
            #tendrá la clave success si mail es exitoso
            $mData=array("success"=>$respuesta);
        }else{
            #O tendrá la clave error si hay un error
            $mData=array("error"=>"mail no ha funciona, revisa tu configuración");
        }
        return $mData;
    }

    if(isset($_POST['nombre'])){
        $mData=ajaxEnviarDatos();
    }else{
        $mData=array("error"=>"Falta el nombre");
    }
    echo json_encode($mData);

?>


text:
Q: When and how to use the Central Limit Theorem? I'm currently trying to solve an exercise in statistics.
I have got many hundred observations for some measured fluctations.
In a normal Q-Q plot, I have plotted all the observations and a line has been drawed. This is all done by software.
As I can see, the plotted observations do not really differ from a straight line, maybe only a little bit at the beginning of the line and at the end of line. Therefore, as I understand, I can assume that the data (the observations) follow a normal distribution.
However, in the exercise, I'm told to make use of the central limit theorem. But as I understand, this theorem should only be used if I can't assume a normal distribution (if the plotted observations differed from a straight line).
Did I misunderstand something?

A: In simple words, the Central Limit Theorem says that the sum of a sufficiently large number of weakly dependent quantities has a distribution close to normal, regardless of their initial distribution.
So

But as I understand, this theorem should only be used if I can't
  assume a normal distribution (if the plotted observations differed
  from a straight line).

you don't need any assumptions on prior distributions, and it is really the main key point of CLT.
UPDATE (Thanks to comment by Karl): You don't need any special assumptions on prior distribution while it has well-defined finite mean $\mu$ and variance $\sigma^2$. There exist examples of such distributions which don't satisfy this requirement.


text:
Q: Finding the value of $ k $. Find all real value of $ k $ such that the system of equation
\begin{align}
a^2 + ab &= kc^2 \\
b^2 + bc &= ka^2 \\
c^2 + ca &= kb^2
\end{align}
have positive real number solution for $ a $, $ b $, and $ c $.
I have already found the value of $ k $. Here is my solution.
Adding all of the equation, we found that
$$ a^2 + b^2 + c^2 + ab + bc + ca = k\left(a^2 + b^2 + c^2\right) $$
or
$$ k - 1 = \frac{ab + bc + ca}{a^2 + b^2 + c^2}. $$
Since $ ab + bc + ca \leq a^2 + b^2 + c^2 $ for $ a, b, c \in \mathbb{R^{+}} $,
$$ k - 1 \leq \frac{ab + bc + ca}{ab + bc + ca} = 1 \iff k \leq 2. $$
My question is, is my solution is wrong? Or did I missed something? Thanks.

A: You have proved that $k \le 2$ is necessary, but have not shown it is sufficient.
If $k=-1$, we have three equations like $a^2+ab=-c^2$.  This cannot be satisfied with $a,b,c$ positive.  This applies for any $k \le 0$.
Now it remains to show that there is a solution for any $k$ with $0 \lt k \le 2$
As the equations are homogeneous, for any solution $(a,b,c)$ you have $(da,db,dc)$ is also a solution, so you can choose $d=\frac 1a$ or (equivalently) set $a=1$.  That reduces you to two unknowns and gives you an easy substitution.


text:
Q: Onepage Checkout, unable to place the order getting Prototype.js error When i click on  Checkout as Guest or Register, I'm getting this error,Unable to proceed on any steps.
TypeError: e is not a function

...complete:!1,initialize:function(e,t,n){e(n),this.transport=Ajax.getTransport(),t...

How can i fix this..?
Thanks


text:
Q: Node.js - Why does my HTTP GET Request return a 404 when I know the data is there @ the URL I am using I'm still new enough with Node that HTTP requests trip me up. I have checked all the answers to similar questions but none seem to address my issue.
I have been dealt a hand in the Wild of having to go after JSON files in an API. I then parse those JSON files to separate them out into rows that populate a SQL database. The API has one JSON file with an ID of 'keys.json' that looks like this:
{
"keys":["5sM5YLnnNMN_1540338527220.json","5sM5YLnnNMN_1540389571029.json","6tN6ZMooONO_1540389269289.json"]
}

Each array element in the keys property holds the value of one of the JSON data files in the API.
I am having problems getting either type of file returned to me, but I figure if I can learn what is wrong with the way I am trying to get 'keys.json', I can leverage that knowledge to get the individual JSON data files represented in the keys array.
I am using the npm modules 'request' and 'request-promise-native' as follows:
const request   = require('request');
const rp        = require('request-promise-native');

My URL is constructed with the following elements, as follows (I have used the ... to keep my client anonymous, but other than that it is a direct copy:
let baseURL = 'http://localhost:3000/Users/doug5solas/sandbox/.../server/.quizzes/'; //  this is the development value only
let keysID = 'keys.json';

Clearly the localhost aspect will have to go away when we deploy but I am just testing now.
Here is my HTTP call:
let options = {
    method: 'GET',
    uri: baseURL + keysID,
    headers: {
        'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
};
rp(options)
    .then(function (res) {
        jsonKeysList = res.keys;
        console.log('Fetched', jsonKeysList);
    })
    .catch(function (err) {
        // API call failed
        let errMessage = err.options.uri + ' ' + err.statusCode + ' Not Found';
        console.log(errMessage);
        return errMessage;
    });

Here is my console output:
http://localhost:3000/Users/doug5solas/sandbox/.../server/.quizzes/keys.json 404 Not Found

It is clear to me that the .catch() clause is being taken and not the .then() clause. But I do not know why that is because the data is there at that spot. I know it is because I placed it there manually.

A: Thanks to @Kevin B for the tip regarding serving of static files. I revamped the logic using express.static and served the file using that capability and everything worked as expected.


text:
Q: Why is a switch case statement unable to work with properties of an Enum? I am writing a simple game in which I use an Enum, CommandManager, to store information about the possible commands and what each one does. The main purposes of this Enum is to be able to print out a menu of available commands, as well as being used to check input and performing the action related to that input. My problem lies with that second use, where I am using a switch statement to determine what the user wants to do based on their input. I'm getting a compilation error when trying to use a property of an Enum (via a getter method) as a case label. The error message provided is that case expressions must be constant expressions. Given that the properties of CommandManager are declared to be final, am I right in thinking that properties of Enums simply cannot be used in switch statements? If this is the case, why?
Simplified version of the code included below in case it's an error on my end.
Method Code:
void interpretInput()   {
    String command = input.getInput();
    if (command.length() == 2)  {
            switch (command) {
            case CommandManager.MAINMENU.getCommand(): goToMainMenu();
                    break;
            case CommandManager.NEWGAME.getCommand(): startNewGame();
                    break;
            case CommandManager.LISTGAMES.getCommand(): listSavedGames();
                    break;
            case CommandManager.EXITGAME.getCommand(): exitGame();
                    break;
            case CommandManager.HELPMENU.getCommand(): listAllCommands();
                    break;
            }
    }
}

Enum code:
public enum CommandManager {

NEWGAME("!n", "New game"),
MAINMENU("!m", "Go to main menu"),
EXITGAME("!q", "Exit Battleships"),
LISTGAMES("!g", "List saved games"),
HELPMENU("!h", "Open help menu"),
LOADGAME("!l", "Load a new game"),
SAVEGAME("!s", "Save current game");

private final String command;
private final String menuOption;

CommandManager(String aCommand, String anOption)    {
    command = aCommand;
    menuOption = anOption;
}

String getCommand() {
    return command;
}

String getMenuOption()  {
    return menuOption;
}
}

A:
Am I right in thinking that properties of Enums simply cannot be used in switch statements?

You are.

If this is the case, why?

Because the "labels" for a switch statement need to be compile time constants, and the properties of an enum do not qualify.
The reason that they need to be compile time constants is that the compiler needs to check that the switch labels are distinct.  It cannot allow something like this
switch (someValue) {
    case A.method():  doA();
    case B.method():  doB();
}

where A.method() and B.method() turn out to have the same value.  If the case expressions are not compile-time constant expressions, then the compiler cannot detect the problem.  (Method calls are never compile time constant expressions.)

A: I would do things differently by using a Map to help with an action design pattern.
First add to your CommandManager enum a method that converts a command String to a CommandManager object, something like:
public static CommandManager getCommandManager(String command) {
    for (CommandManager cManager : CommandManager.values()) {
        if (command.equals(cManager.getCommand())) {
            return cManager;
        }
    }
    throw new IllegalArgumentException(command);
}

e.g.,
public enum CommandManager {

    NEWGAME("!n", "New game"),
    MAINMENU("!m", "Go to main menu"),
    EXITGAME("!q", "Exit Battleships"),
    LISTGAMES("!g", "List saved games"),
    HELPMENU("!h", "Open help menu"),
    LOADGAME("!l", "Load a new game"),
    SAVEGAME("!s", "Save current game");

    private final String command;
    private final String menuOption;

    CommandManager(String aCommand, String anOption) {
        command = aCommand;
        menuOption = anOption;
    }

    String getCommand() {
        return command;
    }

    String getMenuOption() {
        return menuOption;
    }

    // ************ ADD THIS! *******
    public static CommandManager getCommandManager(String command) {
        for (CommandManager cManager : CommandManager.values()) {
            if (command.equals(cManager.getCommand())) {
                return cManager;
            }
        }
        throw new IllegalArgumentException(command);
    }
}

Then give your code that uses this a Map that maps each CommandManager with a Runnable, and fill the map:
public class TestEnum {
    private Map<CommandManager, Runnable> commandMap = new EnumMap<>(CommandManager.class);

    public TestEnum() {
        commandMap.put(CommandManager.MAINMENU, () -> goToMainMenu());
        commandMap.put(CommandManager.MAINMENU, () -> goToMainMenu());
        commandMap.put(CommandManager.NEWGAME, () -> startNewGame());
        commandMap.put(CommandManager.LISTGAMES, () -> listSavedGames());
        commandMap.put(CommandManager.EXITGAME, () -> exitGame());
        commandMap.put(CommandManager.HELPMENU, () -> listAllCommands());
    }

Then use it!
void interpretInput(String command) {
    CommandManager cManager = CommandManager.getCommandManager(command);
    commandMap.get(cManager).run();
}

A: You have to use a bit different approach. You can write a static method inside your enum to convert command string into CommandManager enum:
public static CommandManager fromCommand(String command) {
    for (CommandManager commandManager : values()) {
        if (commandManager.getCommand().equals(command)) {
            return commandManager;
        }
    }
    return null; // or throw exception, whatever fits best for your code
}

Then you can invoke this method to get en enum object and use a switch statement to do whatever you want:
String command = input.getInput();
CommandManager commandManager = CommandManager.fromCommand(command);
if (commandManager != null)  {
    switch (commandManager) {
        case MAINMENU:
            goToMainMenu();
            break;
        case NEWGAME:
            startNewGame();
            break;
        case LISTGAMES:
            listSavedGames();
            break;
        case EXITGAME:
            exitGame();
            break;
        case HELPMENU:
            listAllCommands();
            break;
        default:
            throw new IllegalArgumentException("Unknown command: " + commandManager);
    }
}

A: Simply "CommandManager.MAINMENU.getCommand()" is not a Constant, is a function.
Element in enum is Constant, so you have to convert String to enum element.
I used a map to store relation between command and enum element:
public enum CommandManager {

  NEWGAME("!n", "New game"),
  MAINMENU("!m", "Go to main menu"),
  EXITGAME("!q", "Exit Battleships"),
  LISTGAMES("!g", "List saved games"),
  HELPMENU("!h", "Open help menu"),
  LOADGAME("!l", "Load a new game"),
  SAVEGAME("!s", "Save current game");

  private final String command;
  private final String menuOption;
  private static class InnerClass {
    static Map<String, CommandManager> commandMap = new HashMap<>();
  }

  CommandManager(String aCommand, String anOption)    {
    command = aCommand;
    menuOption = anOption;
    InnerClass.commandMap.put(aCommand, this);
  }

  public static CommandManager parseCommand(String aCommand) {
    return InnerClass.commandMap.get(aCommand);
  }

  String getCommand() {
    return command;
  }

  String getMenuOption()  {
    return menuOption;
  }
}

Then change the switch code
public void interpretInput()   {
  String command = input.getInput();
  if (command.length() == 2)  {
    CommandManager commandManager = CommandManager.parseCommand(command);
    if (commandManager!=null) {
      switch (commandManager) {
        case MAINMENU: goToMainMenu();
          break;
        case NEWGAME: startNewGame();
          break;
        case LISTGAMES: listSavedGames();
          break;
        case EXITGAME: exitGame();
          break;
        case HELPMENU: listAllCommands();
          break;
      }
    }
  }
}


text:
Q: Bootstrap file is not readable <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>

    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" type="text/css" href="font-awesome-4.4.0/css/font-awesome.css">
    <link rel="stylesheet" type="text/css" href="font-awesome-4.4.0/css/font-awesome.min.css">
    <script src="js/jquery-1.11.3.min.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="js/map.js"></script>
    <link rel="stylesheet" type="text/css" href="css/jquery-ui.css">
    </head>

now where should i add the bootstrap files i have added above the style.css file but its showing fele not readable

A: If you're using the default Bootstrap folder structure, and if your HTML file is in the root, then you would add something like:
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="js/bootstrap.min.js"></script>

in your head section. The JavaScript file should come after the jQuery references, and the CSS file generally goes before any custom CSS file.
For example:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>

<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" type="text/css" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" type="text/css" href="font-awesome-4.4.0/css/font-awesome.min.css">
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/map.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>

(BTW, I removed one of your Font Awesome stylesheets in the above; make sure that the other one points to a valid path as it's not in the same folder as the rest of your CSS)


text:
Q: how to solve this OutOfMemoryError: Java heap space i have the following program which goes to database and gets the value, i have excuted the query also it gives me only 47 row but when i run the same program in console mode it gives me Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
package com.common;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import com.common.Query;

public class GetColumnValuesFromDifferentTypes {
@SuppressWarnings("unused")
public static void printColumns(String query){
    ABIDAO abidao = new ABIDAO();
    int numberOfColumns=0,columnType = 0;
    String columnValue = "", columnName = "";
    Map<String, String> headerMap = new LinkedHashMap<String, String>();
        Connection connection = abidao.getConnection();
        if (connection != null) {
            try {
                headerMap = getHeader(query);
                System.out.println("====================================================================");
                System.out.println("Header Map : "+headerMap);
                System.out.println("====================================================================");
                PreparedStatement reportTablePS = connection.prepareStatement(query);
                ResultSet reportTable_rst = reportTablePS.executeQuery();
                ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
                numberOfColumns = reportTable_rsmd.getColumnCount();

                    int i =0;
                    while (reportTable_rst.next()) {
                            for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
                                 columnValue = null;
                               columnName = reportTable_rsmd.getColumnName(columnIterator);
                               columnType = reportTable_rsmd.getColumnType(columnIterator);

                               if(columnType == Types.CHAR || columnType == Types.VARCHAR || columnType == Types.LONGVARCHAR)
                               {
                                   columnValue = reportTable_rst.getString(columnName);
                               }else if(columnType == Types.INTEGER || columnType == Types.BIGINT || columnType == Types.SMALLINT || columnType == Types.NUMERIC)
                               {
                                   long templong = reportTable_rst.getLong(columnName);
                                   if(!reportTable_rst.wasNull())
                                   {
                                       columnValue  = Long.toString(templong);
                                   }
                               }else if(columnType == Types.DECIMAL || columnType == Types.DOUBLE || columnType == Types.FLOAT || columnType == Types.REAL)
                               {
                                   double tempDouble1 = reportTable_rst.getDouble(columnName);
                                   if(!reportTable_rst.wasNull())
                                   {
                                       columnValue  = Double.toString(tempDouble1);
                                   }
                               } else if(columnType == Types.TIME || columnType == Types.TIMESTAMP || columnType == Types.DATE)
                               {
                                   Timestamp sqlTimeStamp = reportTable_rst.getTimestamp(columnName);
                                   if(!reportTable_rst.wasNull())
                                   {
                                       columnValue = sqlTimeStamp.toString();
                                   }
                               }
                               System.out.println("columnValue : "+columnValue);
                               System.out.println(",");

                            }
                            System.out.println("====================================================================");
                        }
            } catch (Exception ex) {
                ex.printStackTrace();
            }finally {
                try {
                    abidao.closeConnection(connection, null, null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
}
@SuppressWarnings({ "unused" })
public static  Map<String, String> getHeader(String query) {
    ABIDAO abidao = new ABIDAO();
    String columnName="";
    int numberOfColumns=0,rowCount=1;
    Map<String, String> headerNamesMap = new LinkedHashMap<String, String>();
    Connection connection = abidao.getConnection();
    if (connection != null) {
        try {
            PreparedStatement reportTablePS = connection.prepareStatement(query);
            ResultSet reportTable_rst = reportTablePS.executeQuery();
            ResultSetMetaData rsmd = reportTable_rst.getMetaData();
            numberOfColumns = rsmd.getColumnCount();
            headerNamesMap.put("SNO","SNO");
              while (reportTable_rst.next()) {
                for (int i = 1; i <= numberOfColumns; i++) {
                  columnName = rsmd.getColumnName(i).toUpperCase();
                  if(!headerNamesMap.containsKey(columnName)){
                      headerNamesMap.put(columnName, columnName);
                  }
                }
                rowCount++;
              }

        } catch (Exception ex) {
            ex.printStackTrace();
        }finally {
            try {
                abidao.closeConnection(connection, null, null);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    return headerNamesMap;
}
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    String query = "";
    Map dynamicQueryMap = new HashMap();
    Query queryObj = new Query();

    try {
        dynamicQueryMap = queryObj.getComplexReportQuery();
        if(dynamicQueryMap.containsKey("query")) query = dynamicQueryMap.get("query").toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    printColumns(query);

}
}

This is the query which is return from the Query method :
select
pi.po_number,poi.unit_cost,pi.placed_date CreateDate,
case when isnull(pi.date_closed) then pi.scheduled_arrival_date
else pi.date_closed end as ReceviedDate,
poi.order_quantity,poi.roll_number,p.product_sku product_name,
pc.product_category_name,poi.rec_vendor_quantity,pv.vendor_name,p.et_conversion_unit_quantity,pi.note
from
purchase_order as pi,
purchase_order_inventory as poi,
product_vendors as pv,
products AS p,
product_categories AS pc
where
pi.purchase_order_id=poi.purchase_order_id and
pc.product_category_id=p.product_category_id and
poi.product_id = p.product_id and
poi.product_category_id=pc.product_category_id and
pi.vendor_id=pv.product_vendor_id and
( ( pi.date_closed  >= '2012-01-01' and pi.date_closed <='2012-09-05 23:59:59' )
or ( pi.scheduled_arrival_date  >= '2012-01-01' and pi.scheduled_arrival_date <='2012-09-05 23:59:59') ) and
pi.po_type=0
and pi.status_id = 0 and  poi.transaction_type = 0
order by pi.po_number ;

what is the problem here i am facing!! please help me to find it out.

A: You need to close all your resources, not just the connection. e.g. PreparedStatement.close() and ResultSet.close() If you don't do this they are retained and become a form of a memory leak.
I suggest you confirm this yourself using jmap -histo:live {pid} or using a memory profiler like VisualVM or YourKit.

A: You should close Connection but also ResultSet and Statements to avoid memory leaks.
And don't forget to close statements and other resources before using them again.
Statement stmt = ...;
...
stmt.close();
stmt = ...

A: After avoiding programatic errors to save more memory, you can try setting a specific heap size for your application by changing the configuration of your JVM. Take a look at this post: http://informix-zone.com/node/46

A: The heap size also depends on shared buffer defined in your database configuration file
you have to increase your shared buffers size in database configuration files.
For monitoring heap you can use monitor tools:-

*

*jmap

*jmonitor


text:
Q: Football related short story: teams represent demographic groups, fans start killing each other Plot: New football league is formed to compete against the NFL. However, it quickly loses fans because it's just a copy of the NFL. First change from the owners: teams no longer represent cities but demographic groups. Then rules protecting players are eliminated, making the games more violent. Then fans start killing each other in the stands and that gets added to the scores. Read at least 30 years ago.

A: As per raisinghellyer's comment, this is probably "The National Pastime" by Norman Spinrad (ISFDB link) as answered here (by me).

In the long-winded and somewhat renowned "The National Pastime," Norman Spinrad goes into painstaking detail describing – from the point of view of the cynical and failed filmmaker who invents the game as a means of advancing his career with a television company – Combat Football.

It should be no surprise that Spinrad takes a Progressive approach in his critique of the violence inherent in sport. His over-the-top game taps the animal nature of an unthinking population. Whatever the story's politics – they take a back seat to some of the more illogical or implausible features of the new game.

For one thing, the wildly popular Combat Football includes only six nationalized teams, none of which have a home city. They tour the country for the best venues, and are organized based on demographic identity:

"This way, we got a team for the spades, a team for the frustrated Middle Americans, a team for the hippies and kids, a team for the spics, a team for the faggots, and a team for the motorcycle nuts and violence freaks."
-- From "The National Pastime," by Norman Spinrad

Even less logically, fan casualties and fatalities are included in the statistics, with numbers soaring into the hundreds per game. They are played in stadiums without security. The plays are portrayed somewhat realistically as akin to American football, but the key play consistently seems to be a punch in the mouth.


text:
Q: Filtering User table by MembershipUserCollection So, I have ASP Membership set up in my application. I also have a separate User table for managing non-membership related data.  During user management I need to make sure that my application queries both tables. I have the below Controller that returns a list of approved users, but it seems like there has to be a simpler way to accomplish this. What is a better way to do it?
        QuoteExchangeDB _db = new QuoteExchangeDB();

        [MyAuthorize(Roles = "Administrator")]
        public ActionResult Admin()
        {
            MembershipUserCollection agents = Membership.GetAllUsers();
            IEnumerable<MembershipUser> unfiltered = agents.Cast<MembershipUser>();
            var filtered = unfiltered.Where(u => u.IsApproved);
            List<User> users = new List<User>();
            foreach (var item in filtered)
            {
                if (item.IsApproved)
                {
                    Guid guid = (Guid)item.ProviderUserKey;
                    users.Add(_db.Users.Single(u => u.MembershipGuid.Equals(guid)));
                }
            }
            return View(users);
        }

A: This looks like you probably want a simple join in LINQ.
var filtered = Membership.GetAllUsers().Cast<MembershipUser>().Where(u => u.IsApproved);

var users = from f in filtered
        join u in _db.Users on ((Guid)f.ProviderUserKey) equals u.MembershipGuid
        select u;

You could probably make one statement out of that even:
var users = from f in Membership.GetAllUsers().Cast<MembershipUser>()
    join u in _db.Users on ((Guid)f.ProviderUserKey) equals u.MembershipGuid
    where f.IsApproved
    select u;

Edit:  Given that I'm not sure how joining an IEnumerable with an IQueryable might affect things/cause problems in this instance, here's a blog about doing that.


text:
Q: Is 'there' an adverb or a preposition? (Or something else entirely!?) Most dictionaries seem to describe 'there' as an adverb. Oxford online dictionary definition Is this true?
"Last year we went to Paris. We stayed there for three nights."
In sentences like this 'there' is taking the place of a preposition and a noun - in this case 'in Paris'. So why is it referred to as an adverb?
Is there a case for describing it as a preposition? It is a substitute for a prepositional phrase ('on the table'. 'in the room', 'to Paris', 'in Paris' etc), and like a preposition, and unlike an adverb, it may be modified by 'right' or 'straight'.
"We flew straight there."
"The book is right there - in front of you."
Prepositional phrases
So, is 'there' (and I suppose we could extend this to its interrogative: 'where') an adverb, a preposition or some other category of word?

A: As is well-recognised by linguists, dictionaries are not a good place to start when trying to establish parts of speech. A good reference grammar is. Of the three great grammars of the English language from the last hundred years, the most recent and up-to-date is The Cambridge Grammar of the English Language, Huddleston and Pullum, 2002. It says the following:

Locative there is an intransitive preposition contrasting with here: it has deictic and anaphoric uses ... (p. 1319)

(For a fuller account, consult pages 598-691). Part of the reason given for there and here being prepositions is that, exactly as OP has commented, they are modifiable by straight and right. Furthermore, these words  function in the same way as other prepositional phrases: they are able to function as locative complements of the verb BE, and also as spacial and temporal adjuncts.
Many phrase types have the latter function, including adverbs and adverb phrases, however adverbs don't generally function as complements of the verb BE. Furthermore adverbs are not modifiable by either right or straight:
Complements of BE

*

*The comments were erroneously. * (adverb complement)- wrong

*The comments were locally. * (adverb complement)- wrong

*The comments were out of order.

*The comments were at the bottom.

*The comments were below.

*The comments were here.

*The comments were there.

Straight and right as modifiers.

*

*He flew straight beautifully. *   (wrong)

*He flew right directly. *   (wrong)

*He flew straight to Paris.

*He flew right over the house.

*He flew straight in.

*He flew straight there.

This all goes to show that the OP is indeed correct: there does indeed seem to be a preposition.
Hope this is helpful

A: First a caveat: you cannot always reliably test what function a certain word or phrase has by replacing it with some other word or phrase. However, normal adverbs serve the same function as many prepositional phrases do, so what you said about how it can replace in Paris supports treating there as an adverb.
A preposition occurs before a nominal phrase, like a noun; but there Paris is not possible, unlike in Paris. And so it is not a preposition, unlike the preposition in.
There is often called an adverbial demonstrative pronoun. While it does normally have an adverbial function (it describes where something happens), it has an antecedent: it refers back to a place that was mentioned earlier or that the listener or reader knows is relevant. So in your example, it refers back to Paris, a place; in its capacity of referring back to an antecedent, it is pronominal, functioning like a pronoun.
It is demonstrative because you can point at something while saying it, just like the demonstrative (personal and adjectival) pronouns this, that, those and these: I see that [pointing at object], we went there [pointing at place] etc.
Note that, in certain idiomatic constructions, there has almost evolved into something more like a particle, as in there was noöne in the room.
The words straight and right in your example are a bit complicated; they could be analysed in different ways. The two most obvious ways would be to either classify them as adverbs modifying there, or as adverbs modifying the verb in parallel with there. The simplest structure of I flew straight there would be the latter: how did you fly? I flew straight, not via some other point. Where did you fly? There. Those are two adverbs, one of manner and one of place/destination.

A: There is an adverb of place, and an adverb is used to modify a verb. In the sentence— We stayed there for three nights, stay is a verb and there is modifying it. it's answering us the question— where did we stay?
To make the sentence more understandable a semi colon could have been put between both the sentences.


text:
Q: Side Scrolling a PDF in UIWebView Is there a way to get a PDF that has been loaded into a UIWebView to scroll horizontally instead of vertically?

A: No, but you could file a feature request with Apple at http://bugreporter.apple.com

A: It appears you can't do this with UIWebView but instead have to use Quartz. Hope this is helpful to anyone searching for the same functionality.