C# Displaying data when selecting row in datagridview

Question: Apologies in advance if this question has been answered elsewhere (haven't found the answer after a few hours of searching).
Anyways, my code works, I've tested it using a button.
Selecting the row then clicking the button and it displays the correct data.
But I want it to display the data when I select row , instead of selecting a row then pressing a button.
My code:
private void dgvRecipes_CellContentClick(object sender,
                                         DataGridViewCellEventArgs e)
{

  if (dgvRecipes.SelectedRows.Count > 0)
  {
     int selectedRecipe =
         int.Parse(dgvRecipes.SelectedRows[0].Cells[0].Value.ToString());

     lblRecipe.Text = dgvRecipes.SelectedRows[0].Cells[1].Value.ToString();

     string selectStr = "SELECT IngredDesc, IngredAmt, IngredComment " +
            "FROM Ingredient, RecipeIngredients
             WHERE RecipeIngredients.RecipeNo = " + selectedRecipe +
             " AND Ingredient.IngredID = RecipeIngredients.IngredID ";

     dbCmd = new SqlCommand(selectStr, dbConn);
     dbAdapter = new SqlDataAdapter(dbCmd);
     dbAdapter.Fill(ds, "RecipeIngredients");
     dgvIngredients.DataSource = ds.Tables["RecipeIngredients"];

     selectStr = "SELECT InstructionNo, Instructions FROM RecipeInstructions "
                + "WHERE RecipeInstructions.RecipeNo = " + selectedRecipe;

     dbCmd = new SqlCommand(selectStr, dbConn);
     dbAdapter = new SqlDataAdapter(dbCmd);
     dbAdapter.Fill(ds, "RecipeInstructions");
     dgvInstructions.DataSource = ds.Tables["RecipeInstructions"];

  }

}

Again, apologies if I haven't phrased my question correctly and set out the code badly.
Answer: You just need to add a Selection Change event  of Datagridview:
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    ......
}

To explain TaW usefull comment you will have to go in DatagridView's properties (from VS desgin) select the Events tab and Double click on the SelectionChange Event
Comment: This should work; have you actually __hooked up__ the event or just added the code??
Comment: I tried this and it didnt help. Thanks for the reply though.
Comment: Thanks!, using the Events tab to change it worked.

I was just trying to change the code.
Answer: You normally do this by a binding, so the textboxes display the same values without any extra code behind.
But: you can also change the property called "selectionmode" of a datagrid; you should set in to selectRow. Then you can find the appropriate event and move the code you have under your button to that event
Answer: Use SelectionChanged event of DataGridView.
SelectionChanged event occurs whenever cells are selected or the selection is canceled, whether programmatically or by user action.
Comment: second mention of SelectionChanged, maybe im missing something, because it hasnt changed anything .

it should be something like this right :
private void dgvRecipes_SelectionChanged(object sender, EventArgs e)
{ code here }


Android values-small isnt used

Question: I've created a new Android Resource Directory to Support different Screen sizes. I outsourced every hard coded size and TextSize in dimens.xml. But my values-small directory is not picked by Android. The dimensions are used in the layouts and in the activities.
Why is default picked instead of the small one?
The packages hierarchy looks like this:
Answer: current size, that is mostly current used, is normal (reference)
small is practically not used by most devices
Comment: Well, i works at large devices. but the Emulator says that the Screen size of this Emulator is small that's why i am wondering. I would like to Support every device obviously
Comment: If you want in code some resource(for example `large` screen), it looks first in `values-large`. If no resource found, then it looks in `values`. In `values-small`, `values-large` etc folders you should only define values, that are different to values in `values` folder
Answer: You have to provide dimensions according to device screen density
values-sw720dp          10.1" tablet 1280x800 mdpi

values-sw600dp          7.0"  tablet 1024x600 mdpi

values-sw480dp          5.4"  480x854 mdpi

values-sw480dp          5.1"  480x800 mdpi

values-xxhdpi           5.5"  1080x1920 xxhdpi

values-xxxhdpi          5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7"   1280x720 xhdpi

values-xhdpi            4.65"  720x1280 xhdpi

values-hdpi             4.0" 480x800 hdpi

values-hdpi             3.7" 480x854 hdpi

values-mdpi             3.2" 320x480 mdpi

values-ldpi             3.4" 240x432 ldpi

values-ldpi             3.3" 240x400 ldpi

values-ldpi             2.7" 240x320 ldpi

See answer https://stackoverflow.com/a/32861248/771098 for more details

Android values-small isnt used


Android dragging unlimited images from the sources

Question: I am trying to implement a drag and drop function in Android.I have choosed to implement it using motion event because I think it is easy to understand.I want to make that image I move to remain in the same position and move a duplication. I don't really know how to explain, I want an image on the corner and when I move it the image still remain there but I move another one that is the same, and If I want to move another one from the same position again I move another position.It's like I am trying to get 10 balls from a basket but in this case the basket and the balls are the same image.
My code so far is this:
public class MainActivity extends ActionBarActivity {

    private View selected_item = null;
    private int offset_x = 0;
    private int offset_y = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         ViewGroup vg = (ViewGroup)findViewById(R.id.container);
            vg.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    switch(event.getActionMasked())
                    {
                            case MotionEvent.ACTION_MOVE:
                                    int x = (int)event.getX() - offset_x;
                                    int y = (int)event.getY() - offset_y;

            int w = getWindowManager().getDefaultDisplay().getWidth() - 100;
            int h = getWindowManager().getDefaultDisplay().getHeight() - 100;
            if(x > w)
                x = w;
            if(y > h)
                y = h;
                             LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                            new ViewGroup.MarginLayoutParams(
                                            LinearLayout.LayoutParams.WRAP_CONTENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                             lp.setMargins(x, y, 0, 0);

                                    selected_item.setLayoutParams(lp);

                                    break;
                            default:
                                    break;
                    }
                    return true;
            }
       });
           ImageView img = (ImageView)findViewById(R.id.newwall);

            img.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                    switch(event.getActionMasked())
                    {
                            case MotionEvent.ACTION_DOWN:
                                    offset_x = (int)event.getX();
                                    offset_y = (int)event.getY();
                                    selected_item = v;
                                    break;
                            default:
                                    break;
                    }

                    return false;
            }
    });

Also, I am using a ViewGroup and I have a touchListener attached on it.When I am pressing the Layout I am getting the image where I press, I would like when I drop the image to remain there if I touch somewhere else on the screen.I have tried to set selected_item back to null when I end the drag but I didn't make it good I guess because I was getting error and app crashes.
Please help me solve these 2 problems.
Answer: Here is what I have used for similar purpose
ImageView snapshot = (ImageView)findViewById(R.id.nonFullScreenSnapshot);
vg.buildDrawingCache();
cache = Bitmap.createBitmap(vg.getDrawingCache());
Drawable drawableShot = new BitmapDrawable(getResources(), cache);
snapshot.setImageDrawable(drawableShot);
snapshot.setVisibility(View.VISIBLE);

In this case I have an ImageView already available from my xml layout, which should be at least as big as the image you want to duplicate.
So when the user touches your ViewGroup you should make a duplicate of it and then position it on the new location.
But be careful with the number of duplicates, because you can easily run out of memory and you will get OutOfMemory exception.


When did Euler find his formula for $\zeta(2n)$

Question: Does anybody know when Euler found his famous formula $$\zeta(2n)=\frac{(-1)^{n-1}(2\pi)^{2n}B_{2n}}{2(2n)!}?$$
Comment: This might be useful https://goo.gl/NFlx6R
Answer: Looks like 1734, according to this article.  But he didn't prove it completely until a few years later.
http://www.math.wvu.edu/~mays/745/Euler%20and%20the%20zeta%20function.pdf


What happens after a car finishes an F1 race

Question: After crossing the finishing line in F1, how much further ahead do drivers go?  Obviously they can't stop right at the finishing line.  Are there any regulations here? How do they exit the track? is it standard across all circuits? Do they go for another round?  It's never been clear to me.  The video  is always cut after they cross the line and/or the perspective does not make it clear.
Answer: The finish procedure is covered by Article 43 of the Formula One Sporting Regulations (found on page 48).
Articles 43.1 and 43.3 state, in part:

A chequered flag will be the end-of-race signal and will be shown at the [finish] line as soon as the leading car has covered the full race distance [...] After receiving the end-of-race signal all cars must proceed on the circuit directly to the post-race parc fermé ... without any assistance (except that of the marshals if necessary).

Parc fermé is a secure area of the pit complex where the cars are lined up after the race, so they can be inspected to ensure that they comply with the regulations. My understanding is that after crossing the finish line, the cars make their way around the circuit for a cooldown lap/lap of honour, and then enter parc fermé via the usual pit lane entrance. Should they break down or run out of fuel before they get there, the marshals will help tow it back to the pits.
Comment: *"the cars make their way around the circuit"* There are exceptions, like Spa (or Nurburgring in the old days).


Probability Question Not Replaced Question

Question: I'm stuck behind the logic of this probability question -

In an experiment, 6 bulbs were planted in a row. 3 produced red flowers and 3 produced yellow flowers.
  If the bulbs were planted in a random order, what is the probability that the colours will alternate along the whole row?
   [A] 1/60
 [B] 1/48
 [C] 1/32
 [D] 1/20
 [E] 1/10

I thought based on the first evidence, the probability of blue and yellow are $\frac{3}{6} = \frac{1}{2}$ respectively,
so I did the following:
Knowing that the only possiblities are RYRYRY and YRYRYR in a line,
I did the calculation
$$2 \times (\frac{1}{2})^6 = \frac{1}{32}$$
but this is apparently incorrect. The answer is $\frac{1}{10}$ given by the calculation
$$2 \times \frac{3}{6} \times \frac{3}{5} \times \frac{2}{4} \times \frac{2}{3} \times \frac{1}{2} \times \frac{1}{1} = \frac{1}{10}$$
I'm slightly puzzled. How is this possible?
Answer: There are
$$
\binom{6}{3} = 20
$$
ways to arrange three red and three yellow flowers in a row - choose the $3$ places for the red ones. In just $2$ of those the colors alternate.
Answer: For the answer you have quoted, consider the ordering RYRYRY.  The probability the first flower is red is 3/6, because there are 6 flowers of which 3 are red.  Then the probability the second flower is yellow is 3/5, because there are 5 flowers left, out of which 3 are yellow.  Then the probability that the third flower is red is 2/4, because there are 4 flowers left of which 2 are red.  Etc.
Finally, multiply by 2 to account for the two equally likely orderings, RYRYRY and YRYRYR.


How to find panoID in a new Google maps?

Question: PanoID use to be easy to find in the URL in classic maps for a photosphere/Google Business View shot. Unfortunately, they are not available anymore.
Does anyone know how to find that stupid panoid?
Answer: The pano ID is no longer a 22 character string. The ID now consists of multiple strings separated by a slash. For example:
https://email@example.com,23.7257492,3a,75y,5.43h,104.71t/data=!3m8!1e1!3m6!1s-wBhdou4p2Mk%2FVoC0geL2n8I%2FAAAAAAAAZ80%2FeRVCXmFDXBg!2e4!3e11!6s%2F%2Flh5.googleusercontent.com%2F-wBhdou4p2Mk%2FVoC0geL2n8I%2FAAAAAAAAZ80%2FeRVCXmFDXBg%2Fw203-h101-n-k-no%2F!7i9068!8i4534!4m6!1m3!3m2!1s0x0:0x5c97c042f5eb0df6!2sAcropolis+of+Athens!3m1!1s0x0:0x5c97c042f5eb0df6!6m1!1e1
The pano ID for the above is between the !1s and !2e:
-wBhdou4p2Mk%2FVoC0geL2n8I%2FAAAAAAAAZ80%2FeRVCXmFDXBg
And url decoded is:
-wBhdou4p2Mk/VoC0geL2n8I/AAAAAAAAZ80/eRVCXmFDXBg
There is currently a known bug which is documented here https://code.google.com/p/gmaps-api-issues/issues/detail?id=7452#c51. This bug is preventing new panos from being embedded. Google states they are currently working on the issue and have pushed out a temporary method to enable using the new render method. Apparently this isn't ready for prime time yet which is why it is only available through an undocumented option:
google.maps.streetViewViewer = 'photosphere';

Note: It in order for this to work for us we had to prepend F: to the front of the pano ID (as per comment 80 https://code.google.com/p/gmaps-api-issues/issues/detail?id=7452#c80).


How to solve this seemingly simple triple integral?

Question: $$\iiint_D x^2+y^2+z^2\,dxdydz$$ $D$ is bound by $x=0, y=0,z=0$ and $x+y+z=a$, calculated by rote, I got $\frac{a^5}{20}$, is there any simpler way to do this? I tried using spherical coordinates, but the problem doesn't seem to be simplified.
Answer: Here's at least one simplification. Since the integrand $f(x,y,z)=x^2+y^2+z^2$ and the region of integration $D$ are symmetric with respect to interchanging any of pair $x,y,z$, the integral simplifies to any of the following three choices:
$$\begin{align}
\iiint_{D}(x^2+y^2+z^2)\,\mathrm{d}x\mathrm{d}y\mathrm{d}z
&=3\iiint_{D}x^2\,\mathrm{d}x\mathrm{d}y\mathrm{d}z\\
&=3\iiint_{D}y^2\,\mathrm{d}x\mathrm{d}y\mathrm{d}z\\
&=3\iiint_{D}z^2\,\mathrm{d}x\mathrm{d}y\mathrm{d}z.
\end{align}$$
The easiest of the three choices to integrate depends on the chosen order of integration. If you choose to integrate first over $z$, then over $y$, and last over $x$, then you probably want to choose the first option, because this leaves the first two integrations fairly trivial:
$$\begin{align}
\iiint_{D}f(x,y,z)\,\mathrm{d}V
&=3\int_{0}^{a}\mathrm{d}x\int_{0}^{a-x}\mathrm{d}y\int_{0}^{a-x-y}\mathrm{d}z\,\color{blue}{x^2}\\
&=3\int_{0}^{a}\mathrm{d}x\,\color{blue}{x^2}\int_{0}^{a-x}\mathrm{d}y\int_{0}^{a-x-y}\mathrm{d}z.
\end{align}$$


PHP not interpreted using PHP5.4 + Apache2.2

Question: Does anyone here know why my PHP code is not being interpreted? Apache is running smoothly with localhost, but when I try to execute localhost/info.php containing
(<?php
phpinfo();
?>) ...

It's not interpreted.
Here is my httpd.conf
Listen 80

LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule authn_alias_module modules/mod_authn_alias.so
#LoadModule authn_anon_module modules/mod_authn_anon.so
#LoadModule authn_dbd_module modules/mod_authn_dbd.so
#LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authn_file_module modules/mod_authn_file.so
#LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
#LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
#LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
#LoadModule cache_module modules/mod_cache.so
#LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
#LoadModule charset_lite_module modules/mod_charset_lite.so
#LoadModule dav_module modules/mod_dav.so
#LoadModule dav_fs_module modules/mod_dav_fs.so
#LoadModule dav_lock_module modules/mod_dav_lock.so
#LoadModule dbd_module modules/mod_dbd.so
#LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
#LoadModule disk_cache_module modules/mod_disk_cache.so
#LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
#LoadModule expires_module modules/mod_expires.so
#LoadModule ext_filter_module modules/mod_ext_filter.so
#LoadModule file_cache_module modules/mod_file_cache.so
#LoadModule filter_module modules/mod_filter.so
#LoadModule headers_module modules/mod_headers.so
#LoadModule ident_module modules/mod_ident.so
#LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
#LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
#LoadModule ldap_module modules/mod_ldap.so
#LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
#LoadModule log_forensic_module modules/mod_log_forensic.so
#LoadModule mem_cache_module modules/mod_mem_cache.so
LoadModule mime_module modules/mod_mime.so
#LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
#LoadModule proxy_module modules/mod_proxy.so
#LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
#LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
#LoadModule proxy_connect_module modules/mod_proxy_connect.so
#LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#LoadModule proxy_http_module modules/mod_proxy_http.so
#LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
#LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule setenvif_module modules/mod_setenvif.so
#LoadModule speling_module modules/mod_speling.so
#LoadModule ssl_module modules/mod_ssl.so
#LoadModule status_module modules/mod_status.so
#LoadModule substitute_module modules/mod_substitute.so
#LoadModule unique_id_module modules/mod_unique_id.so
#LoadModule userdir_module modules/mod_userdir.so
#LoadModule usertrack_module modules/mod_usertrack.so
#LoadModule version_module modules/mod_version.so
#LoadModule vhost_alias_module modules/mod_vhost_alias.so

<IfModule !mpm_netware_module>
<IfModule !mpm_winnt_module>

User daemon
Group daemon

</IfModule>
</IfModule>

ServerAdmin firstname.lastname@example.com

DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"

 <Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

 <Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">

    Options Indexes FollowSymLinks

    AllowOverride None

    Order allow,deny
    Allow from all

</Directory>

<IfModule dir_module>
   DirectoryIndex index.html index.htm index.php
</IfModule>

<FilesMatch "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</FilesMatch>

ErrorLog "logs/error.log"

LogLevel warn

<IfModule log_config_module>

    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    CustomLog "logs/access.log" common

</IfModule>

<IfModule alias_module>

    ScriptAlias /cgi-bin/ "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin/"

</IfModule>

<IfModule cgid_module>

</IfModule>

<Directory "C:/Program Files/Apache Software Foundation/Apache2.2/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

DefaultType text/plain

<IfModule mime_module>

    TypesConfig conf/mime.types

    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

</IfModule>

<IfModule ssl_module>
SSLRandomSeed startup builtin
SSLRandomSeed connect builtin
</IfModule>

Thank you all !
Comment: check your error_log of apache
Comment: You really should read [the PHP manual](http://www.php.net/manual/en/install.php), it explains everything.
Answer: You'll need to add directives to configure the php module. This is what the configuration directives look like on CentOS 6.x. Your system may be slightly different.
#
# PHP is an HTML-embedded scripting language which attempts to make it
# easy for developers to write dynamically generated webpages.
#
<IfModule prefork.c>
  LoadModule php5_module modules/libphp5.so
</IfModule>
<IfModule worker.c>
  LoadModule php5_module modules/libphp5-zts.so
</IfModule>

#
# Cause the PHP interpreter to handle files with a .php extension.
#
AddHandler php5-script .php
AddType text/html .php


data can not be inserted in the database table

Question: //This PHP code is trying to insert some values in the database table "transaction_db".An insert query is run with the data to be inserted.
//HTML form is designed to test the PHP code.But after submitting the HTML form,no new inserted row is shown,and also no error anywhere.
//PHP code below
<?PHP
include_once("connection.php");

session_start();

if(isset($_POST['event_date']) && isset($_POST['event_location']) && isset ($_POST['organisation_name']) && isset ($_POST['client_name']) && isset ($_POST['client_type']) )
{

$client_name= mysqli_real_escape_string($con,$_POST['client_name']);
$client_type= mysqli_real_escape_string($con,$_POST['client_type']);
$event_date= mysqli_real_escape_string($con,$_POST['event_date']);
$organisation_name= mysqli_real_escape_string($con,$_POST['organisation_name']);
$event_location= mysqli_real_escape_string($con,$_POST['event_location']);

$score1= mysqli_real_escape_string($con,$_POST['score1']);
$score2= mysqli_real_escape_string($con,$_POST['score2']);
$score3= mysqli_real_escape_string($con,$_POST['score3']);
$score4= mysqli_real_escape_string($con,$_POST['score4']);
$score5= mysqli_real_escape_string($con,$_POST['score5']);
$score6= mysqli_real_escape_string($con,$_POST['score6']);
$score7= mysqli_real_escape_string($con,$_POST['score7']);
$score8= mysqli_real_escape_string($con,$_POST['score8']);
$score9= mysqli_real_escape_string($con,$_POST['score9']);
$score10= mysqli_real_escape_string($con,$_POST['score10']);
$answer1= mysqli_real_escape_string($con,$_POST['answer1']);
$answer2= mysqli_real_escape_string($con,$_POST['answer2']);
$answer3= mysqli_real_escape_string($con,$_POST['answer3']);
$answer4= mysqli_real_escape_string($con,$_POST['answer4']);
$answer5= mysqli_real_escape_string($con,$_POST['answer5']);
$comments= mysqli_real_escape_string($con,$_POST['comments']);

$login_id= mysqli_real_escape_string($con,$_POST['login_id']);
$lid = (int)$login_id;

$query = "INSERT INTO transaction_db (client_name,client_type,event_date,organisation_name,event_location,,login_id,score1,score2,score3,score4,score5,score6,score7,score8,score9,score10,answer1,answer2,answer3,answer4,answer5,comments) VALUES ('$client_name','$client_type','$event_date','$organisation_name','$event_location','$login_id','$score1','$score2','$score3','$score4','$score5','$score6','$score7','$score8','$score9','$score10','$answer1','$answer2','$answer3','$answer4','$answer5','$comments')";

if(mysqli_query($con,$query)){
     $data['success'] = 1;
     echo json_encode($data);
     }
    else{
        $data['success'] = 0;
    echo json_encode($data);
    }
}
mysqli_close($con);
?>

//HTML FORM CREATION

      <title>client welcome Page</title>

Login

               <form action = "" method = "post">
                  name  :<input type = "text" name = "name" class = "box"/>

                  type  :<input type = "text" name = "type" class = "box" />

                  date  :<input type = "text" name = "date" class = "box" />

                  org name  :<input type = "text" name = "org name" class = "box" />

                  location  :<input type = "text" name = "location" class = "box" />

                  <input type = "submit" value = " Submit "/>

               </form>

Comment: $ins_query  = mysqli_query("INSERT INTO transaction_db (client_name,client_type,event_date,organisation_name,event_location,,login_id,score1,score2,score3,score4,score5,score6,score7,score8,score9,score10,answer1,answer2,answer3,answer4,answer5,comments) VALUES ('$client_name','$client_type','$event_date','$organisation_name','$event_location',,$login_id','$score1','$score2','$score3','$score4','$score5','$score6','$score7','$score8','$score9','$score10','$answer1','$answer2','$answer3','$answer4','$answer5','$comments')";
Comment: @Caius $ does work with ' .As I have one more php file,which works fine and contains $ with ' .
Comment: action = "php_file_name.php" to trigger you php script.....

or add name="submit" attribute to your button tag then trigger with this name (submit) to tigger php fucction
Comment: You have an error in your sql. Look at this part: 'event_location,,login_id'. Seems you missed column name.
Comment: @Alex hey corrected it,but still no new row insertion.
Comment: try to print your sql and execute it in a phpmyadmin or every db administrator.
You'll get the error ;)
Comment: That would be very helpful if you posted dump of $_POST.
Comment: and i'm quite sure $ dose work only between " and not ' (simple comma)
Comment: @SumanKalyan Tried your query also,but the same result,no new row inserted.
Comment: @AhsanAzizAbbasi that didnt help.
Comment: "and i'm quite sure $ dose work only between " and not ' (simple comma)" - all single quotes wrapped with double quotes, so it should work (I'd rather say there is no need to use single quotes at all).
Comment: @SomyaArora ok than that's not the error.

Could you print the `$query` and try to execute ti in some data base admin?
Comment: Number of columns and number of data items you're trying to insert mismatch. Number of columns is 23 (including missing one), and number of data items is 22. If you added some column name in empty place, that might cause the problem. If you removed one extra comma that should be ok.
Comment: in your form correct the name your have put.
Comment: @Alex that extra column is a foreign key,so that should not create a problem as it will be auto filled.
Comment: @Caius    INSERT INTO transaction_db (client_name,client_type,event_date,organisation_name,event_location) VALUES ('s','s','2016-04-04','s','s'){"success":0}                                              This is the printed query,they are not allowing me to post a screenshot of it.
Comment: @SumanKalyan corrected them too.but didnt help
Answer: You should use blind query for security but since you are not using it yet try to do this mysql instead.
It's easyer to debug of where it's the error.
INSERT INTO transaction_db SET
client_name = '$client_name'
,client_type = '$client_type'
,event_date = '$event_date'
,organisation_name = '$organisation_name'
,event_location = '$event_location'
,login_id = '$login_id'
,score1 = '$score1'
,score2 = '$score2'
,score3 = '$score3'
,score4 = '$score4'
,score5 = '$score5'
,score6 = '$score6'
,score7 = '$score7'
,score8 = '$score8'
,score9 = '$score9'
,score10 ='$score10'
,answer1 = '$answer1'
,answer2 = '$answer2'
,answer3 = '$answer3'
,answer4 = '$answer4'
,answer5 = '$answer5'
,comments = '$comments'

Comment: lol yes,it was completely offtopic.But fyi its just an American and British English spelling differences :p
Comment: @Somya Arora also i think it's organization instead of organisation this could be a offtopic or to solve your error. :D


If the product of two homotopy equivalences is a homotopy equivalence are the factors homotopy equivalences?

Question: The question says it all:
Given two maps $f\colon A\rightarrow B$ and $f'\colon A'\rightarrow B'$, such that their product $$f\times f'\colon A\times A'\rightarrow B\times B'$$ is a homotopy equivalence, must $f$ and $f'$ be homotopy equivalences?
This certainly holds for weak equivalences and therefore for spaces of the homotopy type of CW complexes, but what about the general situation?
Bonus question: What about the case of infinite products?
Comment: Each factor is a retract of the product, and the respective maps are retracts as well. That's all you need.
Comment: Try $A = B = \varnothing$.
Comment: What about nonempty spaces?
Comment: @JustinYoung, yes, this short statement is that i mean in my long answer. Necessary that projection on factor is retraction (i.e. has a section), in such category as $\mathcal{Rings}^{opp}$ similar statement will be false: if we take $\mathbb Z/2\mathbb Z\otimes\mathbb Z/2\mathbb Z\leftarrow\mathbb Z/2\mathbb Z\otimes\mathbb Z$, this is equivalence, but the map $\mathbb Z/2\mathbb Z\leftarrow\mathbb Z$ actually isn't.
Answer: I think, in general situation $f$ and $f'$ will be homotopy equivalences too.
Denote $f\times f':A\times A'\to B\times B'$ by $F$ and let $G:B\times B'\to A\times A'$ be the map such that $G\circ F\sim Id_{A\times A'}$ and $F\circ G\sim Id_{B\times B'}$. Choose one point $a'\in A'$. Then let $g:B\to A$ be the composition $p\circ G\circ \iota_B:B\times f'(a')\to B\times B'\to A\times A'\to A$, where $p$ is projection of a product and $\iota_B$ is just inclusion.
Let's check that $g\circ f\sim Id_A$. Note that $g\circ f$ can be written as the composition $p\circ G\circ F\circ \iota_A:A\times a'\to A\times A'\to B\times B'\to A\times A'\to A$, and here $G\circ F\sim Id_{A\times A'}$, so the first half of desired statement is proven. Here $\iota_A$ is obviously includion.
Let's check that $f\circ g\sim Id_B$. Note that $f\circ g$ can be written as the composition $q\circ F\circ G\circ \iota_B:B\times f(a')\to B\times B'\to A\times A'\to B\times B'\to B$, and here $F\circ G\sim Id_{B\times B'}$, so the second half of desired statement is proven. Here $q$ is a projection of a product.
(sorry for this notation, but I cannot draw diagrams here)


Função não retorna valor

Question: Colegas...
tenho um método do qual traz os resultados de uma tabela. Até aqui tudo bem. O que está me intrigando é que depois que mudei de servidor, a estrutura desse método é a mesma para outros dois resultados e funcionam perfeitamente, porém ao criar outro método com a mesma estrutura, não retorna valor, a não ser quando só tem um só valor no banco. Já copiei e colei a estrutura do método funcional, substituindo somente o nome do método e nada. Porém quando dou echo em vez do return, aparece o resultado. Diante disso, isolei o código em um outro arquivo e em um exemplo simples, o erro aparece. Vejam em uma função simples:
function teste(){
        for($i = 0; $i < 10; $i++){
            $c = $i;
        }
  return $c;
}
echo teste();

O resultado aparece apenas o 9. Porém quando dou um echo. Retorna os valores corretamente:
function teste(){
    for($i = 0; $i < 10; $i++){
        $c = $i;
        echo $c;
    }
}
echo teste();

Alguém sabe o porque isso acontece?
Comment: Algumas das respostas lhe foi útil? se não poste o que não funcionou poste o que ainda esta acontecendo se sim valide uma resposta.
Answer: Tem em conta que o return só vai ser chamado depois de o for ter corrido.
Ou seja, o ciclo for vai correr na integra, o valor de $c vai sendo re-escrito até o ciclo acabar. Aí, quando o ciclo acaba, o ultimo valor que $c tem é 9 e é esse valor que vai ser passado ao return.
Quando juntas um echo dentro do ciclo for estás a registar (fazer echo) de cada valor que o $i toma e que passa ao $c, daí a diferênça. O resultado final é o mesmo, o retornado pelo return é o mesmo. Repara que na versão com o echo dentro do ciclo for tens de certeza 2 vezes o numero 9, a segunda o return da função.
Comment: Obrigado Sérgio
Answer: Nesta função esta retornando somente o ultimo valor do vetor. pois o for ficara atribuindo até chegar ao fim do vetor, e quando chegar irá retornar o ultimo valor atribuído a $c
function teste(){
        for($i = 0; $i < 10; $i++){
            $c = $i;
        }
  return $c;
}
echo teste();

Nesta outra esta imprimindo o valor de $c a cada novo ciclo do for.
function teste(){
    for($i = 0; $i < 10; $i++){
        $c = $i;
        echo $c;
    }
}
echo teste();

Nesta esta a atribuir a um array e imprimindo todo o conteúdo:
function teste(){
    $c = array();
    for($i = 0; $i < 10; $i++){
        $c[] = $i;
    }
    return $c;
}
var_dump(teste());

Comment: Obrigado Ricardo.
Answer: Para retornar todos os valores concatene uma string usando o operador .=, dessa forma a cada iteração do for a variável $c recebera o valor já contido mais o atual. Caso você necessite fazer algum calculo ou formatação nesses valores é melhor guarda isso em um array.
Versão com string:
function teste(){
   $c = '';
   for($i=0;$i<10;$i++){
      $c .= $i .' ';
   }
   return $c;
}

Versão com array:
<?php
    function teste(){
       $c = array();
       for($i=0;$i<10;$i++){
          $c[] = $i;
       }
       return $c;
    }

    echo '
';
    print_r(teste());

Função não retorna valor


How to best select a single entity from an aggregate root's child collection using NHibernate?

Question: I am wondering about what's considered the better or more correct practise in the following scenario:
I've mapped the following business entities with NHibernate:

Wall
WallPost
WallPostComment

A Wall has zero-to-many WallPosts. A WallPost has zero-to-many WallPostComments. The aggregate root is Wall.
I'm writing a task to add a WallPostComment to a WallPost. The application is an MVC application, and the request to add the new WallPostComment contains the id of the WallPost to which the comment belongs. In order to add the comment I need to retrieve the post that it should be added to. My question is: what's the best/most correct way of doing this?
I've tried two approaches so far and one feels more 'correct', though it's inefficient. Another, more efficient, approach feels a 'wrong.'
1) I load the Wall aggregate root from the session and select FirstOrDefault from its Posts collection. This feels 'correct' in that I'm accessing the wall post via the aggregate root, but doing this results in all wall posts being fetched from the database (unbounded result set).
2) I load the wall post directly from the session using the wallPostId passed to me by the request. This feels 'wrong' because I'm going around the aggregate root - but it's a single hit on the database for a single row of data.
Which is the better or preferred approach? What other suggestions do you have?
Answer: It seems that WallPost is a candidate to be an aggregate root itself,
this way it has its own repository and you can fetch it separately and operate on it and its comments. and there is no problem when an aggregate root (WallPost) can reference another aggregate root (Wall).
If you comes into situation that you can't fix the design to make WallPost an aggregate root you can utilize the concept of Role Interface and Fetching Strategy do distinguish repository fetching to be limited on some aspects of the aggregate root instead of fetching it entirely this way you can fetch Wall aggregate root without fetching all its wall posts, and fetch the needed wall post to update.
Worst case scenario when you cant make WallPost aggregate root and you dont want to apply Role Interface and/or fetching strategy you can create a command called CommentWallPostCommand(Comment) with command handler which will fetch the exact needed wallpost (projection of the aggregate root) and update it, at least having explicit command will make the design more clear and explicit.
Comment: thanks! I just had one of those 'aaah!' moments - it's a bit obvious now that you say it! Indeed, WallPost might be a good candidate for an aggregate root. I'll explore this a bit further, but I think you are right. And I put it down to a combination of inexperience and coding at 2am that I didn't think of this before :-) Thanks!
Comment: OK - I've had a long hard think about this and decided to choose the other answer as the answer to my question - but that is only because it matches my domain better. I think this answer is equally correct, though - it just depends on the domain (and I've decided to change mine slightly)... sorry!
Answer: Is there really a Wall?  What is the relationship between a Wall and other actors in your domain?  I would guess that a Wall is connected with a user and that a user has a single wall.  Is that correct?  In which case a wall is simply a collection of WallPosts and related comments.  In which case your WallPost is your aggregate root and there is no Wall at all.
Comment: That's a good point. I've always thought of a wall as an entity and an aggregate root - but as I read your answer I had another one of those 'a-ha!' moments. I'll have to ponder this a little bit more but this may very well be the case. In fact, this answer is as correct as Mohammed's answer - it just depends on the domain, doesn't it!


How can I play a solo when there is no chord progression?

Question: Ok I'll explain the situation.
I have to play a guitar solo during one section of a song. The problem is that during that section the other guitar only plays the D5 chord in an irregular pattern with considerable time between strummings.
The song is in the F#m scale and I already had a solo where I played over that scale and I thought it was good, but after recording it I felt that it didn't sound quite right and decided to change it, but I don't know how to make something that sounds good.
There is a lot of tutorials about soloing over a chord progression, but I haven't found anything about soloing over just a chord repeating over and over.
I don't know if I should create a chord progression for that part of the song and play over that or play over D lydian or if the time between the strummings of the other guitar is messing me up.
So I ask you some advice on how to play a solo over the same chord over and over.
Answer: Improvisation is live composing, and composing is slow improvisation. If you haven't been given instructions on what to do, you have to make it up yourself. Whatever you don't have, you make up. If you don't have a rhythm, you imagine a rhythm. If you don't have chords, you imagine chords.
But you think you do have chords?

... over just a chord repeating over and over.

You said it's just a "D5". That's not much of a chord. There's any number of things you could add to that and make it something completely different. You can play a Dm and it turns into a Dm. Play an F and it turns into a Dm7. Play an Am and it's almost a D9. You can play an E and it turns to a D lydian feeling. You can play a C#m and it turns into a Dmaj11'ish sort of thing. You can play a G and whoah you even introduced a bit of a key change! How about F#, what does the chord become? What will an Eb make it? Try a progression D - Eb - E - F - F# - G over the D5! How about descending, A - Ab - G - F# - F - E - Eb - D? Try cadences like D - G - A - D. Or D - G - C - D.
There's literally any number of chords and chord progressions you could imagine on top of a "D5", and you can even change the key if you like. Playing only a D5 for a long time is like handing you the keys and the steering wheel. Everything is totally in your control. I challenge you to find something that could not be played over the D5.
And of course you don't have to play actual chords, it's enough to just imagine them and solo over it as if the chords were there.
Try it. Have a looper play that D5 indefinitely and play different things over it.
Comment: The OP indicates that "after recording it I felt that it didn't sound quite right", so s/he could very well have already found something that could *not* be played over the D5.
Comment: @Dekkadeci It would be very interesting to hear what it was.
Answer: Chords are meant to support melody rather than dictate melody.  This is something that many musicians get backwards when they first start improv.
Joe Pass, for example, would play beautiful melodic lines that defined chords progressions.  It takes time to learn but there isn't a lot of variety in western music.  For some musicians a drone chord or vamp is great because it does NOT dictate too much in the way of movement and you can create your own.  For others, the more chords the better since they provide the improv ideas.
That said here are a few ideas.

You are in a unique position to play around with multiple styles.  If the song is in F#m you could play off any minor mode (though the one in key would be F# natural minor).  You could also use F# phygian, dorian, or the blues scale.
Try something with an ethnic style.  Playing over drones is common in Indian music.  Indian music is all Improv and Sitar players will play off exotic scales while other instruments play simple 2 note drone chords.  Using ideas from Indian music became popular in classic rock.  You hear it in Zeppelin and other bands.  I'm referring to the use of a Sitar like in Beatles tunes, but the style of playing.  You could also do this with the blues scale, or F# Phygian would sound Spanish.
Use ideas from the song!  This is probably your best bet.  Before the solo part comes there is something being played by other instruments, or a singer.  Get your hands on their music or figure out a few lines by ear.  As long as the solo chord matches the key you're in you should be able to make that work.  I don't suggest just playing the main theme straight, but taking highlights and embellishing them, turning them into something new.  This is a solid approach as it complements the song rather than becoming something completely incongruent.

If you're new to improv don't shy away form composing a solo.  Many great players do this.  Even though the idea is to be spontaneous we really use ideas we are familiar with and string them together when we solo.
I hope that helps.
Answer: The concept here is Modal. I think it came into jazz with Ahmad Jamal, but Miles Davis made it the center of his Kind Of Blue album. It entered rock with the Butterfield Blues Band's East/West.
Compare a standard chord progression as an obstacle course: the chord changes, the challenge changes, and you as an improviser must adapt. The toughest chordal obstacle course I know it's "Giant Steps" by John Coltrane, where the key center moves as far as possible as fast as possible, and in the original recording, the piano player falls off the changes.
Playing over one chord is like floor exercises in gymnastics: it's a wide open space for you to play with, and what you do with it is up to you. If it is D5, than you can easily switch between all the modes except Locrian, which uses a flat fifth. Here we get into later Coltrane, like A Love Supreme and "My Favorite Things", and the challenge is on your ability to play melodically and lyrically, not getting in a chord tone before the chord changes.
So, play in major. Switch to minor. Try harmonic minor. It all relies on you, so it's your time to shine.


Funny behaviour of Array.splice()

Question: I was experimenting with the splice() method in jconsole
a = [1,2,3,4,5,6,7,8,9,10]
1,2,3,4,5,6,7,8,9,10

Here, a is a simple array from 1 to 10.
b = ['a','b','c']
a,b,c

And this is b
a.splice(0, 2, b)
1,2
a
a,b,c,3,4,5,6,7,8,9,10

When I pass the array b to the third argument of splice, I mean "remove the first two arguments of a from index zero, and replace them with the b array". I've never seen passing an array as splice()'s third argument (all the guide pages I read talk about a list of arguments), but, well, it seems to do the trick. [1,2] are removed and now a is [a,b,c,3,4,5,6,7,8,9,10]. Then I build another array, which I call c:
c = ['one','two','three']
one,two,three

And try to do the same:
a.splice(0, 2, c)
a,b,c,3
a
one,two,three,4,5,6,7,8,9,10

This time, 4 (instead of 2) elements are removed [a,b,c,3] and the c array is added at the beginning. Someone knows why? I'm sure the solution is trivial, but I don't get it right now.
Answer: Array.splice does not support an array as the third parameter.
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice
Using Firebug (or Chrome's Console), one sees what really happens:
a.splice(0, 2, b)
> [1, 2]
a
> [["a", "b", "c"], 3, 4, 5, 6, 7, 8, 9, 10]

Problem here is jconsole, which just uses toString() to print out the arrays, but Array.toString() does not print any [].
Comment: Great. I was misleaded by the "flat" jconsole answers (where everything seemed to be a single array, not the b array as the first member of the first one, a). All is clear now.

Funny behaviour of Array.splice()


What would make all content of a certain type return a 404 on the node page?

Question: When trying to view/edit nodes of Content Type X, drupal returns a 404 - Not Found. All other content on the site (content of other node types) seems unaffected.
To eliminate other issues with clean URLs, path or path auto, I'm using the q param to access the nodes (example.com?q=node/123, example.com?q=node/123/edit), so it's not something silly like that (not likely anyway since all of the other site content renders fine at the expected URLS).
To be clear, drupal seems completely unaware of these nodes. Filtering by this content type on the admin/content/node page returns "No posts available". However, I happen to have a Views Bulk Operation view that modifies a CCK field for these nodes and that page does show all of them with the proper titles and everything. Trying to modify that CCK field with the VBO has no effect though (the field is not updated).
What I was doing before this happened:
I recently installed a new theme. Unfortunately, I can't confirm or deny that this started happening as a direct result of the theme. I would expect any error caused by this to result in 500 errors anyway. Or possibly 403 errors because I do use drupal_access_denied() in some custom modules - but not drupal_not_found().
What I have looked into while troubleshooting:

The node table looks fine. The rows referring to these nodes remain and appear unchanged.
All of the CCK tables (content_type_x, content_node_field, content_field_abc, etc) look fine.
The menu_router table rows for node/%, and node/%/edit are fine (but like I said, this is just one content type and I would think that something wrong with those rows would break all content types). (All of these database checks seem unlikely anyway since I haven't touched the DB directly or modified much of anything recently.)
I have rebuilt the permissions on site content (/admin/content/node-settings/rebuild).
The watchdog table records the 404, but nothing else.
The Status Report page is all green.

I realize that this is a pretty esoteric question, but I'm hoping something in the above rings a bell with someone.
This site is (still) running on Drupal 6.
Comment: What user roles are getting the 404?  Does the superadmin (uid==1)?
Comment: Yeah. User1 (and everyone else).
Comment: If you switch to Garland, do you have the problem?
Comment: Don't know why I didn't try that before, but yes, the problem still exists with Garland.
Comment: do you have custom display or template for the content type?
Comment: @MohammedShameem I have the theme switched to Garland - so no custom template. And I'm not using Display Suite or any custom display modes.
Comment: Thanks MPD and Mohammed for helping troubleshoot and isolate.
Answer: The author of the nodes in question (just happened to be the same author for all of the nodes in this content type) was missing from the user table. To be clear, the user was not properly deleted - the row was simply removed from the database.
I'm guessing that this caused the db_fetch_object() function to fail within node_load() when it tried to JOIN the user table on the nonexistant uid:
$node = db_fetch_object(db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE ' . $cond, $arguments));

But it failed completely silently - I that's guess because this scenario would never happen if the user had been deleted properly (Drupal 6 automatically sets the Author of all content created by a deleted user to Anonymous (uid == 0).
Lot's of red herrings while troubleshooting, but maybe this will help someone in the future that doesn't realize they're using a half-sanitized database.


How do I deploy a local site?

Question: I've been getting mixed messages and there is practically no solid up-to-date documentation, I just want to know the standard procedure for moving a locally developed Drupal 8 site to an online server.
Some say it's as easy as FTP'ing your files over and exporting your local database SQL code over and then connecting to the db via the settings.php, others say to put a fresh installation of Drupal 8 online and then move certain files over while exporting the database using the backup module and then importing it online, others still say I also need to export the local configuration and import it online, still others say I need to update the URL's in some parts of the SQL or configuration exports, etc.
I'm developing with the latest Drupal 8.4 with a custom theme in Windows 10 on XAMPP (I have drush) and migrating to a server subdirectory that my domain points to with php 5.6+ (no drush options online because there's no SSH access).
TLDR: What are the steps to move a locally developed Drupal 8.4 site and database to an online server and get it configured, up and running normally?
Comment: There is no "solid up-to-date documentation" because there's a million ways to deploy a site. It's also nothing Drupal-specific. Every site/app faces the same problem at some point. So it's totally up to you what you find convenient for your needs. I'd recommend to automate as much as possible (as demonstrated in https://github.com/leymannx/drupal-circleci-behat), but this is just another opinionated way of doing things. Maybe most of us at least would agree, that Git is a must.
Comment: You can either commit the entire directory with git, and push that to a remote, or you can use Drupal Composer or Acquia BLT to control the 'build' via best practices + composer.json and let that deploy to the server. But with no SSH access, or Drush, its probably going to feel tedious at best. I suppose you could also ftp the entire directory, but thats going to take a decent amount of time.
Comment: I'm sorry to be the bearer of bad news but Drupal 8.4 requires PHP 7.0 and for the moment there is a bug concerning a core dependency, Doctrine, that requires PHP 7.1. For more information you could consult the Drupal 8 System requirements (https://www.drupal.org/docs/8/system-requirements/php) section. As for Doctrine, there is an [open issue](https://www.drupal.org/node/2898119) with status "Needs work".
Comment: That's actually good to know, fortunately after tooling around a lot in my hosts settings I found out I could actually update the PHP version to 7.0/7.1.  Still, I'd really appreciate it if someone could explain what the step-by-step procedure is for moving over and configuring a locally developed Drupal 8.4 site to an online host.
Comment: I don't just want to move the files over, I've already FTP'ed the files over using FileZilla, I mean moving it over and configuring the database and system so it functions perfectly online just as it did on localhost.
Answer: There are many ways to migrate a local site to a server. Here are a few of the most common.

SFTP/FTP is one way, you can "manually" move all the files up to the
server and use PHPMyAdmin to import the database. Many hosts will
also have automatic Drupal installs, in which case you can use that,
only upload your theme, files, and modules, and then import database. If you upload via FTP you will need to update settings.php to include the servers SQL log/pass as well as domain url
Set up a git repo which you can pull/push to from your local machine
and the server is likely a better solution if you plan on making
changes. This allows you to more easily manage the files and is a
"safer" solution. Set settings.php to .gitignore
There are also managed solutions such as Acquia Dev Desktop which
will allow you to push/pull files, code, and database simultaneously
using a UI.

How do I deploy a local site?


How to implement save/load functionality of Java application data/state?

Question: I have an application of POJOs (plain old java objects) representing my data.
While running, the application manipulates and remembers data as desired.
Now I want to implement a save/load feature.

I am NOT asking about basic file I/O.
I am NOT asking whether ObjectOutputStream exists.

Options I have found are those such as:
1) JSON/XML/YAML libraries such as Gson, Jackson
2) Roll your own binary file format marking everything as Serializable with a Serialization Proxy pattern.
Option 1 is unsuitable because my data model can feature cyclic references. Gson resulted in a stack overflow.
Option 2 is unsuitable because the files should be cross platform and independent of JVM; it should work on desktop and android java.
A properties file is also obviously unsuitable due to the complexity of the model.

Please do not attack my use case; my data model is perfectly well designed. The example may not be.
I will now give example code of the kind of structure that needs to be saved.
class Application {

    //This College is my top level object. It could correspond to an individual save file.
    College college = new College();

    //I would love to be able to just throw this guy into a file.
    SomeLibrary.writeToFile(college);
    //And read another back.
    College college2 = SomeLibrary.readFromFile(anotherCollege);
}

class College {
    //The trees are implemented recursively, so this is actually just the root of each tree.
    Tree<Course> artCourseTree;
    Tree<Course> engineeringCourseTree;
    Tree<Course> businessCourseTree;

    List<Student> maleStudents;
    List<Student> femaleStudents;
}

class Course {
    //Each course only has 2 students in this example. Ignore.
    Student student1;
    Student student2;

    List<Exam> examsInCourse;
    LocalDate courseStartDate;
    Period duration;
}

class Student {
    String name;
    List<Exam> listOfExamsTaken;
}

class Exam {
    Student studentTakingIt;
    LocalDate dateTaken;
    BigDecimal score;
}

As you can see, Exams are intended to be the atomic object in this model at the bottom of the hierarchy. However, not only are they referenced by both Students and Courses, but they also refer back up to a Student and contain nonprimitives such as LocalDate and BigDecimal. The model is given meaning by referencing different subsets of Exams in different Courses and Students.
I need to save the relationships, the arrangement of these things, an arbitrary number of these things, as well as the data they hold.
What hope do I have of saving and loading such a model?
What options are there to implement a save/load feature on such a model, with such constraints?

Is it really industry standard for every java program to roll its own binary file format and create a monstrous apparatus to serialize and deserialize everything? It's that or JSON? What am I missing here? Do I have to just snapshot the VM somehow? Why is there not a standard practice for this?
Comment: The "hard" way, might be to store the "data" with a generated "key" (doesn't matter so long it's valid for the file), then store the relationships using those keys as a seperate section...Have you looked at [JAXP](https://docs.oracle.com/javase/tutorial/jaxp/index.html)?
Comment: I didn't look at JAXP in detail because I understand it to be an XML utility, which I assumed would be subject to the same limitations as JSON regarding cyclic references. Is that wrong?
Comment: I can't be sure for your implementation, but it's annotation based, so you might get more control over how the parsing gets done
Comment: I, too, was formulating some solution where I reduced references to some unique object identifier--like toString() or something--and stored the objects and their relationships separately. I will hold out for a simpler solution.
Comment: Having "mucked" around with ms office, they tend to do something similar
Answer: Circular references is a common use case and can be handled by providing @JsonManagedReference or @JsonBackReference. Check out this SO answer for more details. Another option is to implement custom serializer and solve circular references by yourself. Here is the example for the same.
However, do consider the following aspects before going ahead with using files as database

You will have to manage concurrent writes by yourself. If not correctly handled might result in corruption/loss of the data because files are not ACID compliant by nature.
The solution is not scalable as file size will grow. Time to serialize and deserialize will increase proportionately.
You won't be able to query easily on the data stored in the file. You will always have to deserialize data first and then query on POJOs.

I'll highly recommend checking SQLite which is small, fast, self-contained, high-reliability, full-featured, SQL database engine.
Comment: I see now that Jackson does not have the same limitation as gson, and can handle circular references. You also included another option involving a custom serializer. For those reasons I will mark this as the answer after some testing.
Comment: Notes on using files as a database are appreciated, though I don't know where that intention was signaled.
Comment: So am I correct to conclude that in general, everyone either uses a custom serialization or goes with a json/xml library?
Comment: Yes, for circular references above are solutions. Regarding the comment on files as db, the state is a data and dumping it to a file and reading back from file is kind of doing DB thing, no? :)


TclError: image doesn't exist - Tkinter multi-windows python

Question: Before I am asked to look over other topics, I just want to say that I have and all of the solutions either involve calling a tk.Toplevel() instead of tk.TK() or are within the same .py file.  I have tried it (perhaps done wrongly by substituting HAS(tk.Tk) for HAS(tk.Toplevel).
I am getting an error of TclError: image "brand_logo.png" doesn't exist within my code. I  am developing a Tkinter software with some windows to the user to navigate through. Each window will have a set of questions to be answered. For easiness of maintenance, I developed each window in a different file so I can track back easier errors and changes to the windows themselves.
The code for my window creation class is:
import tkinter as tk, Questions1 as q1, Questions2 as q2
class HAS(tk.Tk):
def __init__(self, *args, **kwargs):
    tk.Tk.__init__(self, *args, *kwargs)
    #Page configure
    tk.Tk.wm_title(self, "Checklist")
    container = tk.Frame(self)
    container.pack(side="top", fill="both", expand=True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)
    container.configure(background = "white")

    #Adding overhead menu
    menubar = tk.Menu(container)
    filemenu = tk.Menu(menubar, tearoff = 0)
    filemenu.add_command(label = "Save", command = self.saveList)
    filemenu.add_command(label = "Exit", command= self.destroy)
    menubar.add_cascade(label="File", menu=filemenu)
    tk.Tk.config(self, menu=menubar)

    #Defining the page_frames
    self.frames = {}
    for F in (q1.Q1, q2.Q2):
        frame = F(container, self)
        self.frames[F] = frame
        frame.grid(row=0, column=0, sticky="nsew")
    self.show_frame(q1.Q1)

#showing the selected frame
def show_frame(self, cont):
    frame = self.frames[cont]
    frame.tkraise()

# Function accessing the list of answers
def saveList(self):
    dict_answers={'Answers 1': self.frames[q1.Q1].list_answers, "Answers 2": self.frames[q2.Q2].list_answers}
    print(dict_answers)

app = HAS()
app.geometry("530x700")
app.mainloop()

and each of my questionnaires follow the same structure, just changing the text and questions:
class Q1(tk.Frame):
def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.columnconfigure(0, minsize=100)
    self.columnconfigure(1, minsize=150)
    self.columnconfigure(2, minsize=50)
    Logo = tk.PhotoImage("brand_logo.png")
    #Header Config
    tk.Frame.configure(self, background = "white")
    ttk.Label(self, image=Logo, background="white").grid(row=0, column=0, padx=100, columnspan=3, pady=10, sticky="W")
    ttk.Label(self, text="1st Checklist", font = FONT, background = "white").grid(row=1, column=0, columnspan=3, pady = 10)
    ttk.Label(self, text="Questions: ", background="white").grid(row=2, column=0,columnspan=2, padx=10, pady = 10, sticky="W")

    #Questions
    global qt
    qt = [tk.StringVar(self) for i in range(len(Questionlist_a))]
    for r in range(len(Questionlist_a)):
        ttk.Label(self, text=Questionlist_a[r], background = "white").grid(row= r+3, column=0, columnspan=2, padx=10, pady = 10, sticky="W")
        ttk.OptionMenu(self, qt[r], *choices_y_n).grid(row = r+3, column=2, padx=10, sticky="WE")
        r=+1

    #Buttons
    ttk.Button(self, text="Save values", command = self.save_values, width=18).grid(row=16, column=0, padx=10, pady=15, sticky="W")
    ttk.Button(self, text="Questions 2", command = lambda: controller.show_frame(__import__('Questions2').Q2),width=18).grid(row=17, column=0, padx=10, pady=15, sticky="W")

    # List of answers
    self.list_answers=[]

def save_values(self):
    self.list_answers = list(map(lambda x: x.get(), qt))

The full traceback error is:
Traceback (most recent call last):
File "<ipython-input-3-69ca257aaadd>", line 1, in <module>
runfile('C:/Users/nlcaste9/Desktop/New folder/Main.py', wdir='C:/Users/nlcaste9/Desktop/New folder')

File "\WPy-3662\python-3.6.6.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
execfile(filename, namespace)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/nlcaste9/Desktop/New folder/Main.py", line 49, in <module>
app = HAS()

File "C:/Users/nlcaste9/Desktop/New folder/Main.py", line 33, in __init__
frame = F(container, self)

File "C:\Users\nlcaste9\Desktop\New folder\Questions1.py", line 25, in __init__
ttk.Label(self, image=Logo, background="white").grid(row=0, column=0, padx=100, columnspan=3, pady=10, sticky="W")

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\ttk.py", line 761, in __init__
Widget.__init__(self, master, "ttk::label", kw)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\ttk.py", line 559, in __init__
tkinter.Widget.__init__(self, master, widgetname, kw=kw)

File "C:\Users\nlcaste9\Downloads\WPy-3662\python-3.6.6.amd64\lib\tkinter\__init__.py", line 2296, in __init__
(widgetName, self._w) + extra + self._options(cnf))

TclError: image "brand_logo.png" doesn't exist

Does anyone can help me?
Thanks!
Comment: Put this `print(os.Path.cwd())` before `Logo = tk.PhotoImage(...` and compare the output with Path where `"brand_logo.png"` is saved.
Answer: I actually can't reproduce the error, your code just doesn't show any image for me, but I do see two problems with the code you have.
The PhotoImage class __init__ method is defined as
class PhotoImage(Image):
    """Widget which can display colored images in GIF, PPM/PGM format."""
    def __init__(self, name=None, cnf={}, master=None, **kw):
        """Create an image with NAME.

        Valid resource names: data, format, file, gamma, height, palette,
        width."""
        Image.__init__(self, 'photo', name, cnf, master, **kw)

This means that the first argument is name. So when you call Logo = tk.PhotoImage("brand_logo.png"), you create an image with the name brand_logo.png, but without actually specifying which image file should be used. To specify the image file use the file keyword argument:
Logo = tk.PhotoImage(file="brand_logo.png")

With that out of the way, Logo is still a local variable to the __init__ function, so after that returns, Logo will be garbage collected. To prevent this, make it an instance variable by renaming it to self.Logo everywhere.


Android LocalServerSocket

Question: In android, there are two classes LocalServerSocket and LocalSocket. I think they are something like AF_LOCAL in unix socket (I am not sure it is correct or not).
My question is that :
Is it possible to create LocalServerSocket in Java and use a normal unix socket client to connect to it in native or other process ?
If it is possible, what the  "sockaddr_un.sun_path"  I should set in native ?
I have written a sample project to test it, and I try to set the .sun_path as same as string name used in LocalServerSocket, but it failed, the native could not connect to the Java LocalServerSocket.
My Java code :
package test.socket;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class TestSocketActivity extends Activity {

    public static String SOCKET_ADDRESS = "my.local.socket.address";
    public String TAG = "Socket_Test";

    static{System.loadLibrary("testSocket");}
    private native void clientSocketThreadNative();
    private native void setStopThreadNative();
    localServerSocket mLocalServerSocket;
    localClientSocket mLocalClientSocket;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mLocalServerSocket = new localServerSocket();

        mLocalClientSocket = new localClientSocket();
    }

    /* LocalServerSocket */
    public class localServerSocket extends Thread {

        int bufferSize = 32;
        byte[] buffer;
        int bytesRead;
        int totalBytesRead;
        int posOffset;
        LocalServerSocket server;
        LocalSocket receiver;
        InputStream input;
        private volatile boolean stopThread;

        public localServerSocket() {
            Log.d(TAG, " +++ Begin of localServerSocket() +++ ");
            buffer = new byte[bufferSize];
            bytesRead = 0;
            totalBytesRead = 0;
            posOffset = 0;

            try {
                server = new LocalServerSocket(SOCKET_ADDRESS);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "The LocalServerSocket created failed !!!");
                e.printStackTrace();
            }

            stopThread = false;
        }

        public void run() {
            Log.d(TAG, " +++ Begin of run() +++ ");
                while (!stopThread) {

                    if (null == server){
                        Log.d(TAG, "The LocalServerSocket is NULL !!!");
                        stopThread = true;
                        break;
                    }

                    try {
                        Log.d(TAG, "LocalServerSocket begins to accept()");
                        receiver = server.accept();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG, "LocalServerSocket accept() failed !!!");
                        e.printStackTrace();
                        continue;
                    }

                    try {
                        input = receiver.getInputStream();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG, "getInputStream() failed !!!");
                        e.printStackTrace();
                        continue;
                    }

                    Log.d(TAG, "The client connect to LocalServerSocket");

                    while (receiver != null) {

                        try {
                            bytesRead = input.read(buffer, posOffset,
                                    (bufferSize - totalBytesRead));
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Log.d(TAG, "There is an exception when reading socket");
                            e.printStackTrace();
                            break;
                        }

                        if (bytesRead >= 0) {
                            Log.d(TAG, "Receive data from socket, bytesRead = "
                                    + bytesRead);
                            posOffset += bytesRead;
                            totalBytesRead += bytesRead;
                        }

                        if (totalBytesRead == bufferSize) {
                            Log.d(TAG, "The buffer is full !!!");
                            String str = new String(buffer);
                            Log.d(TAG, "The context of buffer is : " + str);

                            bytesRead = 0;
                            totalBytesRead = 0;
                            posOffset = 0;
                        }

                    }
                    Log.d(TAG, "The client socket is NULL !!!");
                }
                Log.d(TAG, "The LocalSocketServer thread is going to stop !!!");
                if (receiver != null){
                    try {
                        receiver.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (server != null){
                    try {
                        server.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
        }

        public void setStopThread(boolean value){
            stopThread = value;
            Thread.currentThread().interrupt(); // TODO : Check
        }

    }

    /* Client native socket */
    public class localClientSocket extends Thread {

        private volatile boolean stopThread;

        public localClientSocket(){
            Log.d(TAG, " +++ Begin of localClientSocket() +++ ");
            stopThread = false;
        }

        public void run(){
            Log.d(TAG, " +++ Begin of run() +++ ");
            while(!stopThread){
                clientSocketThreadNative();
            }
        }

        public void setStopThread(boolean value){
            stopThread = value;
            setStopThreadNative();
            Thread.currentThread().interrupt(); // TODO : Check
        }
    }

    public void bt_startServerOnClick(View v) {
        mLocalServerSocket.start();
    }

    public void bt_startClientOnClick(View v) {
        mLocalClientSocket.start();
    }

    public void bt_stopOnClick(View v) {
        mLocalClientSocket.setStopThread(true);
        mLocalServerSocket.setStopThread(true);
    }

}

My Native code :
#define SOCKET_NAME "my.local.socket.address"

JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_clientSocketThreadNative
  (JNIEnv *env, jobject object){

    LOGD("In clientSocketThreadNative() : Begin");

    stopThread = 1;

    int sk, result;
    int count = 1;
    int err;

    char *buffer = malloc(8);

    int i;
    for(i = 0; i<8; i++){
        buffer[i] = (i+1);
    }

    /*
    struct sockaddr_un addr;

    bzero((char *)&addr,sizeof(addr);
    addr.sun_family = AF_UNIX;
    addr.sun_path = SOCKET_NAME;
    */

    struct sockaddr_un addr = {
        AF_UNIX, SOCKET_NAME
    };

    LOGD("In clientSocketThreadNative() : Before creating socket");
    sk = socket(PF_LOCAL, SOCK_STREAM, 0);

    if (sk < 0) {
        err = errno;
        LOGD("%s: Cannot open socket: %s (%d)\n",
            __FUNCTION__, strerror(err), err);
        errno = err;
        return;
    }

    LOGD("In clientSocketThreadNative() : Before connecting to Java LocalSocketServer");
    if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
        err = errno;
        LOGD("%s: connect() failed: %s (%d)\n",
            __FUNCTION__, strerror(err), err);
        close(sk);
        errno = err;
        return;
    }

    LOGD("In clientSocketThreadNative() : Connecting to Java LocalSocketServer succeed");

    while(!stopThread){
        result = write(sk, buffer, 8);
        LOGD("In clientSocketThreadNative() : Total write = %d", result);
        count++;
        if(4 == count){
            sleep(1);
            count = 0;
        }
    }

    LOGD("In clientSocketThreadNative() : End");
}

Any suggestion would be greatly appreciated !!!
Comment: I read the developer website again, and I found that what I did might be doomed to fail. Because the LocalServerSocket uses the Linux abstract namespace, instead of on the filesystem, native client socket would not find the server to connect to. However, that's just what I realized... Any suggestion please.
Comment: My previous comment might not be correct !

According to the Android doc, the default namespace of LocalServerSocket is ABSTRACT, and if the system has "HAVE_LINUX_LOCAL_SOCKET_NAMESPACE" defined, the "0" would add to the begin of sun_path. The final sun_path would be "0" + "original name". This part could be found in source code : /system/core/libcutils/socket_local_server.c

However, even if I add "0" to my sun_path in native code, the native client still could not connect to the Java LocalServerSocket !!!
Answer: The following code might not be perfect but it works !!! Thanks for Mike.
Java part (Socket Server) :
package test.socket;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class TestSocketActivity extends Activity {

    public static String SOCKET_ADDRESS = "/test/socket/localServer";
    public String TAG = "Socket_Test";

    static{System.loadLibrary("testSocket");}
    private native void clientSocketThreadNative();
    private native void setStopThreadNative();
    localSocketServer mLocalSocketServer;
    localSocketClient mLocalSocketClient;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mLocalSocketServer = new localSocketServer();

        mLocalSocketClient = new localSocketClient();
    }

    /* LocalSocketServer */
    public class localSocketServer extends Thread {

        int bufferSize = 32;
        byte[] buffer;
        int bytesRead;
        int totalBytesRead;
        int posOffset;
        LocalServerSocket server;
        LocalSocket receiver;
        InputStream input;
        private volatile boolean stopThread;

        public localSocketServer() {
            Log.d(TAG, " +++ Begin of localSocketServer() +++ ");
            buffer = new byte[bufferSize];
            bytesRead = 0;
            totalBytesRead = 0;
            posOffset = 0;

            try {
                server = new LocalServerSocket(SOCKET_ADDRESS);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                Log.d(TAG, "The localSocketServer created failed !!!");
                e.printStackTrace();
            }

             LocalSocketAddress localSocketAddress;
             localSocketAddress = server.getLocalSocketAddress();
             String str = localSocketAddress.getName();

             Log.d(TAG, "The LocalSocketAddress = " + str);

            stopThread = false;
        }

        public void run() {
            Log.d(TAG, " +++ Begin of run() +++ ");
                while (!stopThread) {

                    if (null == server){
                        Log.d(TAG, "The localSocketServer is NULL !!!");
                        stopThread = true;
                        break;
                    }

                    try {
                        Log.d(TAG, "localSocketServer begins to accept()");
                        receiver = server.accept();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG, "localSocketServer accept() failed !!!");
                        e.printStackTrace();
                        continue;
                    }

                    try {
                        input = receiver.getInputStream();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Log.d(TAG, "getInputStream() failed !!!");
                        e.printStackTrace();
                        continue;
                    }

                    Log.d(TAG, "The client connect to LocalServerSocket");

                    while (receiver != null) {

                        try {
                            bytesRead = input.read(buffer, posOffset,
                                    (bufferSize - totalBytesRead));
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            Log.d(TAG, "There is an exception when reading socket");
                            e.printStackTrace();
                            break;
                        }

                        if (bytesRead >= 0) {
                            Log.d(TAG, "Receive data from socket, bytesRead = "
                                    + bytesRead);
                            posOffset += bytesRead;
                            totalBytesRead += bytesRead;
                        }

                        if (totalBytesRead == bufferSize) {
                            Log.d(TAG, "The buffer is full !!!");
                            String str = new String(buffer);
                            Log.d(TAG, "The context of buffer is : " + str);

                            bytesRead = 0;
                            totalBytesRead = 0;
                            posOffset = 0;
                        }

                    }
                    Log.d(TAG, "The client socket is NULL !!!");
                }
                Log.d(TAG, "The LocalSocketServer thread is going to stop !!!");
                if (receiver != null){
                    try {
                        receiver.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (server != null){
                    try {
                        server.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
        }

        public void setStopThread(boolean value){
            stopThread = value;
            Thread.currentThread().interrupt(); // TODO : Check
        }

    }

    /* Client native socket */
    public class localSocketClient extends Thread {

        private volatile boolean stopThread;

        public localSocketClient(){
            Log.d(TAG, " +++ Begin of localSocketClient() +++ ");
            stopThread = false;
        }

        public void run(){
            Log.d(TAG, " +++ Begin of run() +++ ");
            while(!stopThread){
                clientSocketThreadNative();
            }
        }

        public void setStopThread(boolean value){
            stopThread = value;
            setStopThreadNative();
            Thread.currentThread().interrupt(); // TODO : Check
        }
    }

    public void bt_startServerOnClick(View v) {
        mLocalSocketServer.start();
    }

    public void bt_startClientOnClick(View v) {
        mLocalSocketClient.start();
    }

    public void bt_stopOnClick(View v) {
        mLocalSocketClient.setStopThread(true);
        mLocalSocketServer.setStopThread(true);
    }

}

Native C part (Client)
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/un.h>

#include "test_socket_TestSocketActivity.h"

#define LOCAL_SOCKET_SERVER_NAME "/test/socket/localServer"

volatile int stopThread;

#ifndef __JNILOGGER_H_
#define __JNILOGGER_H_
#include <android/log.h>
#ifdef __cplusplus
extern "C" {
#endif
#ifndef LOG_TAG
#define LOG_TAG "NativeSocket"
#endif
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,LOG_TAG,__VA_ARGS__)
#define LOGS(...) __android_log_print(ANDROID_LOG_SILENT,LOG_TAG,__VA_ARGS__)
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
#ifdef __cplusplus
}
#endif
#endif /* __JNILOGGER_H_ */

JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_clientSocketThreadNative
  (JNIEnv *env, jobject object){

    LOGD("In clientSocketThreadNative() : Begin");

    stopThread = 0;

    int sk, result;
    int count = 1;
    int err;

    char *buffer = malloc(8);

    int i;
    for(i = 0; i<8; i++){
        buffer[i] = (i+1);
    }

    struct sockaddr_un addr;
    socklen_t len;
    addr.sun_family = AF_LOCAL;
    /* use abstract namespace for socket path */
    addr.sun_path[0] = '\0';
    strcpy(&addr.sun_path[1], LOCAL_SOCKET_SERVER_NAME );
    len = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(&addr.sun_path[1]);

    LOGD("In clientSocketThreadNative() : Before creating socket");
    sk = socket(PF_LOCAL, SOCK_STREAM, 0);
    if (sk < 0) {
        err = errno;
        LOGD("%s: Cannot open socket: %s (%d)\n",
            __FUNCTION__, strerror(err), err);
        errno = err;
        return;
    }

    LOGD("In clientSocketThreadNative() : Before connecting to Java LocalSocketServer");
    if (connect(sk, (struct sockaddr *) &addr, len) < 0) {
        err = errno;
        LOGD("%s: connect() failed: %s (%d)\n",
            __FUNCTION__, strerror(err), err);
        close(sk);
        errno = err;
        return;
    }

    LOGD("In clientSocketThreadNative() : Connecting to Java LocalSocketServer succeed");
    while(!stopThread){
        result = write(sk, buffer, 8);
        LOGD("In clientSocketThreadNative() : Total write = %d", result);
        count++;
        if(4 == count){
            sleep(1);
            count = 0;
        }
    }

    LOGD("In clientSocketThreadNative() : End");
}

JNIEXPORT void JNICALL Java_test_socket_TestSocketActivity_setStopThreadNative
  (JNIEnv *env, jobject object){

    stopThread = 1;

}

Comment: Your example is in the same process.
Answer: Looking at local_socket_client.c in the Android source, it looks like they do this:
int socket_make_sockaddr_un(const char *name, int namespaceId,
        struct sockaddr_un *p_addr, socklen_t *alen)
{
    memset (p_addr, 0, sizeof (*p_addr));
    size_t namelen;

    switch (namespaceId) {
        case ANDROID_SOCKET_NAMESPACE_ABSTRACT:
            namelen  = strlen(name);

            // Test with length +1 for the *initial* '\0'.
            if ((namelen + 1) > sizeof(p_addr->sun_path)) {
                goto error;
            }

            /*
             * Note: The path in this case is *not* supposed to be
             * '\0'-terminated. ("man 7 unix" for the gory details.)
             */

            p_addr->sun_path[0] = 0;
            memcpy(p_addr->sun_path + 1, name, namelen);

            ...
    p_addr->sun_family = AF_LOCAL;
    *alen = namelen + offsetof(struct sockaddr_un, sun_path) + 1;

It seems like the memset() is important because the entire sun_path is relevant. (looks like you cover that part with your structure initialization, though.) And it's not "0" plus the original name, it's an actual zero byte! (its value is all binary zeroes, not an ascii '0')
Try following more closely what they're doing, including the leading '\0' byte and the AF_LOCAL family.
If you have updated code (whether it works or not) please post it! I'm interested in your results. Did you ever get this to work?
If it doesn't work, find out what errno is and either call perror() to print it to stderr, or call strerror() and log the output. Let us know what error you get.

Edit
I recently solved this problem in a project of my own. I found that the key was to specify the correct length when calling connect() and bind(). In the code I posted above, it calculates the length by using the offset of the sun_path in the structure, plus the length of the name, plus one for the leading '\0' byte. If you specify any other length, Java code might not be able to connect to the socket.
Comment: OK, thanks for your suggestion, Mike. After some tests, I think I have got the idea about it. I will try it again and post the result ASAP.
Comment: @Bohan, see my recent edit. I got this to work. I can open local sockets in Java code and connect to them in native code, and vice versa. The key is to get the 'length' field correct. This didn't match what `man 7 unix` on my Linux system said. `sizeof(sockaddr_un)` didn't work. The length of the socket must be the offset into the socket of the `sun_path`, plus the number of characters in the socket name, plus 1 for the leading zero byte in the name. (ugh)
Comment: thanks for your comment, I am now struggling with another problem of my project, but I will test what you suggest and post the modified Java and native code again, ASAP...
Answer: Confirmed that the above works properly.  The following examples will not only work together, but will work with the corresponding Android LocalSocket and LocalServerSocket classes:
Client side (Android is server using LocalServerSocket):
#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <sys/un.h>     /* struct sockaddr_un */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
#include <errno.h>
#include <stddef.h>

#define RCVBUFSIZE 2048   /* Size of receive buffer */

void DieWithError(char *errorMessage)  /* Error handling function */
{
    fprintf(stderr, "Error: %s - %s\n", errorMessage, strerror(errno));
    exit(errno);
}

int main(int argc, char *argv[])
{
    int sock;                        /* Socket descriptor */
    struct sockaddr_un echoServAddr; /* Echo server address */
    unsigned char *localSocketName = "MyTestSocket";
    static unsigned char echoString[] = {0x80, 0x00, 0x0e, 0x10, 0x00, 0x9c, 0x40, 0xc9, 0x20, 0x20, 0x20, 0x32, 0x00, 0x00};
    static unsigned int echoStringLen = sizeof(echoString); /* Length of string to echo */
    unsigned char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
    int bytesRcvd, totalBytesRcvd;   /* Bytes read in single recv()
                                    and total bytes read */
    int size;
    int i;

    /* Create a reliable, stream socket using Local Sockets */
    if ((sock = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
        DieWithError("socket() failed");

    /* Construct the server address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */
    echoServAddr.sun_family      = AF_LOCAL;            /* Local socket address family */
    /**
     * Tricky and obscure! For a local socket to be in the "Android name space":
     * - The name of the socket must have a 0-byte value as the first character
     * - The linux man page is right in that 0 bytes are NOT treated as a null terminator.
     * - The man page is not clear in its meaning when it states that "the rest of the bytes in
     *        sunpath" are used. "Rest of bytes" is determined by the length passed in for
     *        sockaddr_len and Android sets this per the recommended file-system sockets of
     *        sizeof(sa_family_t) + strlen(sun_path) + 1. This is important when making calls
     *        to bind, connect, etc!
     * We have initialized the struct sockaddr_un to zero already, so all that is needed is to
     * begin the name copy at sun_path[1] and restrict its length to sizeof(echoServAddr.sun_path)-2
     **/
    strncpy(echoServAddr.sun_path + 1, localSocketName, sizeof(echoServAddr.sun_path) - 2);
    size = sizeof(echoServAddr) - sizeof(echoServAddr.sun_path) + strlen(echoServAddr.sun_path+1) + 1;

    /* Establish the connection to the echo server */
    if (connect(sock, (struct sockaddr *) &echoServAddr, size) < 0)
        DieWithError("connect() failed");

    /* Send the string to the server */
    if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
        DieWithError("send() sent a different number of bytes than expected");

    /* Receive the same string back from the server */
    totalBytesRcvd = 0;
    printf("Sent:     ");
    for (i = 0; i < echoStringLen; i++)
        printf("%02X ", echoString[i]);
    printf("\n");    /* Print a final linefeed */

    printf("Received: ");                /* Setup to print the echoed string */
    if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
        DieWithError("recv() failed or connection closed prematurely");
    for (i = 0; i < bytesRcvd; i++)
        printf("%02X ", echoBuffer[i]);
    printf("\n");    /* Print a final linefeed */

    close(sock);
    exit(0);
}

Server side (Android is client using LocalSocket):
#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <sys/un.h>     /* struct sockaddr_un */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
#include <errno.h>
#include <stddef.h>

#define RCVBUFSIZE 2048   /* Size of receive buffer */

void DieWithError(char *errorMessage)  /* Error handling function */
{
    fprintf(stderr, "Error: %s - %s\n", errorMessage, strerror(errno));
    exit(errno);
}

void HandleLocalClient(int clntSocket)
{
    char echoBuffer[RCVBUFSIZE];        /* Buffer for echo string */
    int recvMsgSize;                    /* Size of received message */

    /* Receive message from client */
    if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
        DieWithError("recv() failed");

    /* Send received string and receive again until end of transmission */
    while (recvMsgSize > 0)      /* zero indicates end of transmission */
    {
        /* Echo message back to client */
        if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
            DieWithError("send() failed");

        /* See if there is more data to receive */
        if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
            DieWithError("recv() failed");
    }

    close(clntSocket);    /* Close client socket */
}

#define MAXPENDING 5    /* Maximum outstanding connection requests */

void DieWithError(char *errorMessage);  /* Error handling function */
void HandleLocalClient(int clntSocket);   /* TCP client handling function */

int main(int argc, char *argv[])
{
    int servSock;                    /* Socket descriptor for server */
    int clntSock;                    /* Socket descriptor for client */
    struct sockaddr_un echoClntAddr; /* Client address */
    unsigned int clntLen;            /* Length of client address data structure */
    struct sockaddr_un echoServAddr; /* Echo server address */
    unsigned char *localSocketName = "MyTestSocket";
    static unsigned int echoStringLen = 14;      /* Length of string to echo */
    unsigned char echoBuffer[RCVBUFSIZE];     /* Buffer for echo string */
    int bytesRcvd, totalBytesRcvd;   /* Bytes read in single recv()
                                    and total bytes read */
    int size;
    int i;

    /* Create a reliable, stream socket using Local Sockets */
    if ((servSock = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0)
        DieWithError("socket() failed");

    /* Construct the server address structure */
    memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */
    echoServAddr.sun_family      = AF_LOCAL;            /* Local socket address family */
    /**
     * Tricky and obscure! For a local socket to be in the "Android name space":
     * - The name of the socket must have a 0-byte value as the first character
     * - The linux man page is right in that 0 bytes are NOT treated as a null terminator.
     * - The man page is not clear in its meaning when it states that "the rest of the bytes in
     *        sunpath" are used. "Rest of bytes" is determined by the length passed in for
     *        sockaddr_len and Android sets this per the recommended file-system sockets of
     *        sizeof(sa_family_t) + strlen(sun_path) + 1. This is important when making calls
     *        to bind, connect, etc!
     * We have initialized the struct sockaddr_un to zero already, so all that is needed is to
     * begin the name copy at sun_path[1] and restrict its length to sizeof(echoServAddr.sun_path)-2
     **/
    strncpy(echoServAddr.sun_path + 1, localSocketName, sizeof(echoServAddr.sun_path) - 2);
    size = sizeof(echoServAddr) - sizeof(echoServAddr.sun_path) + strlen(echoServAddr.sun_path+1) + 1;

    /* Bind to the local address */
    if (bind(servSock, (struct sockaddr *) &echoServAddr, size) < 0)
        DieWithError("bind() failed");

    /* Mark the socket so it will listen for incoming connections */
    if (listen(servSock, MAXPENDING) < 0)
        DieWithError("listen() failed");

    for (;;) /* Run forever */
    {
        /* Set the size of the in-out parameter */
        clntLen = sizeof(echoClntAddr);

        /* Wait for a client to connect */
        if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0)
            DieWithError("accept() failed");

        /* clntSock is connected to a client! */

        printf("Handling client\n");

        HandleLocalClient(clntSock);
    }
    /* NOT REACHED */
    return 0;
}

Tested with Android 4.0.3 ICS 03/15
Answer: Thanks for the answers here.  Piecing people's responses together, the things to be careful about are
On the native side:

the name of the socket must have a 0-byte value as the first character
The linux man page is right in that 0 bytes are NOT treated as a null terminator.
The man page is not clear in its meaning when it states that "the rest of the bytes in sunpath" are used.  "Rest of bytes" is determined by the length passed in for sockaddr_len and Android sets this per the recommended file-system sockets of  sizeof(sa_family_t) + strlen(sun_path) + 1.  This is important when making calls to bind, connect, etc!

On the Java side:
Android defines the conventions it uses under the covers but are consistent with above.

Android LocalServerSocket


How do I install HTTP Live Streaming Tools on 10.7 Lion?

Question: Lion has been out for a couple of months, but the HTTP Live Streaming Tools installer reports that "This package can only be installed on Mac OSX Version 10.6.X."
Is there a way to install the tools on 10.7 Lion?
Answer: You could try this workaround to extract the package files manually.
Comment: I get this error when using mediastreamvalidator after installing using that method:
Comment: mediastreamvalidator: ERROR: Failed to impot msvlib or one of its dependencies.
Please check that msvlib is reachable from your PYTHONPATH.

Traceback (most recent call last):
  File "./mediastreamvalidator", line 23, in
    import msvlib
Answer: Just had this issue.

Use UnPKG to unpack the Streaming Tools Beta.pkg file. See: http://www.timdoug.com/unpkg/
Go to "Streaming Tools Beta" on your desktop. cd ~/Desktop/Streaming\ Tools\ Beta
Copy all files in /. sudo cp -r * /
Edit "/usr/bin/mediastreamvalidator" and change the first line to point to python v2.6: "#!/usr/bin/python2.6"

Known issues:

mediafilesegmenter fails with "Symbol not found: _kFigFormatDescriptionExtension_SampleDescriptionExtensionAtoms"
Answer: I filed a Bugreport with Apple about this issue.
If you have a developer account I'd advise you to do the same at bugreport.apple.com
Comment: UPDATE: Apple just released a new version and I just successfully installed on Lion!