text:
Q: What happens when you cast a char * address to int * in C when the address is not word-aligned? I'm running this bit of code to understand pointers a little better.
void foo(void)
{
    int a[4] = {0, 1, 2, 3};

    printf("a[0]:%d, a[1]:%d, a[2]:%d, a[3]:%d\n", a[0], a[1], a[2], a[3]);

    int *c;

    c = a + 1;
    c = (int *)((char*) c + 1);
    *c = 10;

    printf("c:%p, c+1:%p\n", c, c+1);
    printf("a:%p, a1:%p, a2:%p, a3:%p\n", a, a+1, a+2, a+3);

    printf("a[0]:%d, a[1]:%d, a[2]:%d, a[3]:%d\n", a[0], a[1], a[2], a[3]);

    printf("c[0]:%d, c[1]:%d\n", *c, *(c+1));

}

The output I get is:
a[0]:0, a[1]:1, a[2]:2, a[3]:3
c:0xbfca1515, c+1:0xbfca1519
a:0xbfca1510, a1:0xbfca1514, a2:0xbfca1518, a3:0xbfca151c
a[0]:0, a[1]:2561, a[2]:0, a[3]:3
c[0]:10, c[1]:50331648

Could someone please explain how a[1] is now 2561?
I understand that when we do this:
c = (int *) ((char *) c + 1);

c is now pointing to the 4 bytes following the first byte of a[1].
But how did a[1] end up with 2561?
I'm guessing this has to do with endianness?

A: c = a + 1;

now c points on 1 (second element of a)
c = (int *)((char*) c + 1);

You "cheated" with pointer arithmetic, adding 1 to the address, regardless of the size of the int (note that it is illegal on old machines like 68000 which don't tolerate multi-byte access to odd addresses, or will do the job, albeit a lot slower, which is kind of worse since you're not noticing it for instance it works on a 68020 but slower).
now c points on the 3 last bytes of a[1] and overflows on the first byte of a[2], so when you do:
*c = 10;

since your machine is little endian, you're leaving the leading 1 value, write 10 in the next location, and zeroes afterwards, clobbering the leading 2 byte of a[2]
So now:
 a[1] = 1 + (10<<8) = 2561
 a[2] = 0

the result is different on a big endian machine:
PowerPC big endian (if int is 32 bit, else it's a different result):
a[1] = 10485760
a[2] = 2   // first byte is overwritten, but with zero

68000/68010:
bus error (coredump) / guru meditation

to sum it up: Don't violate the strict aliasing rule


text:
Q: Capturing Return response from Stored Procedure using python module jaydebeapi I am trying to get the stored procedure response when i make a call to Sqlserver using jaydebeapi.
I am creating the connection and cursor and doing as below:
res = cursor.execute('''exec schema.sp_name ''')
print(res)
None

I am unable to get any response from it. Do i need to change anything on how to achieve this.
Please let me know if there is any other way. I have used pymssql and it does works but i am trying to find why this is not working.
Using JayDeBeApi==1.2.3 and Microsoft Sql Server 2016 Data Center 10.0 X64 13.0.7016.1 KB5015371 SP3-CU1-GDR

redpajama_set_name: RedPajamaStackExchange


text:
Q: VBA: Copy entire row with the condition TRUE to TempSheet2 Can someone help me with an VBA script that copy entire rows with the condition TRUE from column U in TempSheet over to TempSheet2.

A: use something like this:
Sub test()
    Dim i&, z&, oCell As Range
    Application.ScreenUpdating = 0
    z = 1: i = Sheets("TempSheet").Cells(Rows.Count, "U").End(xlUp).Row
    For Each oCell In Sheets("TempSheet").Range("U1:U" & i)
        If oCell.Value = True Then
            oCell.EntireRow.Copy Sheets("TempSheet2").Rows(z)
            z = z + 1
        End If
    Next
    Application.ScreenUpdating = 1
End Sub

A: This macro checks each row for the value "True" in the U column.
The columns with true value in column U as then copied to the other sheet.
Option Explicit

Sub CopyRow()
    Dim Row As Integer
    Dim sRow As String
    Dim i As Long

    Application.ScreenUpdating = False

    i = 1 'To ensure each time the macro is run it starts at row 1

    For i = 1 To 1048576 'for each row in the sheet

        If Range("U" & i).Value = True Then 'If the U value is true then copy it

            Row = i
            sRow = CStr(Row) 'convert row number to string
            Rows(sRow & ":" & sRow).Select
            Selection.Copy
            Sheets("Sheet2").Select
            Rows(sRow & ":" & sRow).Select
            ActiveSheet.Paste
            Sheets("Sheet1").Select
            Application.CutCopyMode = False

        End If
    Next i

    Range("A1").Select
    Application.ScreenUpdating = True
End Sub

I am uncertain as to how you want the macro triggered but a worksheet change may suit.
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' trigger the macro if they are changed
    Set KeyCells = Range("U:U")
    Call CopyRow
    End If
End Sub

Note: Worksheet_Change goes in the code for sheet1 and the macro goes in a module


text:
Q: Extract text from pdf ignoring cropped content I'm trying to extract text from a pdf file that has been cropped. I.e it has a defined cropbox which only displays a portion of the page.
The problem is that the cropped part still exists in pdf files, its just not visible.
I've tried PyPDF2, pdfquery and pdfminer. They all read the entire content including the cropped portion.
PyPDF2 lets me access the dimensions of the cropbox using:
pdfFileObj=open(path,'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pdfReader.getPage(0).cropBox

But I'm not sure what I can do with it. The files are being cropped in java using apache pdfBOX. I'd prefer to only read the uncropped part of the files in python but I can also make changes to the java code cropping the files if that's the only solution.
Any help is appreciated.


text:
Q: How to specify different .dockerignore files for different builds in the same project? I used to list the tests directory in .dockerignore so that it wouldn't get included in the image, which I used to run a web service.
Now I'm trying to use Docker to run my unit tests, and in this case I want the tests directory included.
I've checked docker build -h and found no option related.
How can I do this?

A: Adding the cleaned tests as a volume mount to the container could be an option here. After you build the image, if running it for testing, mount the source code containing the tests on top of the cleaned up code.
services:
   tests:
      image: my-clean-image
      volumes:
         - '../app:/opt/app' # Add removed tests

A: I've tried activating the DOCKER_BUILDKIT as suggested by @thisismydesign, but I ran into other problems (outside the scope of this question).
As an alternative, I'm creating an intermediary tar by using the -T flag which takes a txt file containing the files to be included in my tar, so it's not so different than a whitelist .dockerignore.
I export this tar and pipe it to the docker build command, and specify my docker file, which can live anywhere in my file hierarchy. In the end it looks like this:
tar -czh -T files-to-include.txt | docker build -f path/to/Dockerfile -

A: At the moment, there is no way to do this. There is a lengthy discussion about adding an --ignore flag to Docker to provide the ignore file to use - please see here.
The options you have at the moment are mostly ugly:

*

*Split your project into subdirectories that each have their own Dockerfile and .dockerignore, which might not work in your case.

*Create a script that copies the relevant files into a temporary directory and run the Docker build there.

A: Docker 19.03 shipped a solution for this.

The Docker client tries to load <dockerfile-name>.dockerignore first and then falls back to .dockerignore if it can't be found. So docker build -f Dockerfile.foo . first tries to load Dockerfile.foo.dockerignore.

Setting the DOCKER_BUILDKIT=1 environment variable is currently required to use this feature. This flag can be used with docker compose since 1.25.0-rc3 by also specifying COMPOSE_DOCKER_CLI_BUILD=1.
See also comment0, comment1, comment2

from Mugen comment, please note

the custom dockerignore should be in the same directory as the Dockerfile and not in root context directory like the original .dockerignore

i.e.
when calling

DOCKER_BUILDKIT=1
docker build -f /path/to/custom.Dockerfile ...

your .dockerignore file should be at

/path/to/custom.Dockerfile.dockerignore

A: Another option is to have a further build process that includes the tests. The way I do it is this:
If the tests are unit tests then I create a new Docker image that is derived from the main project image; I just stick a FROM at the top, and then ADD the tests, plus any required tools (in my case, mocha, chai and so on). This new 'testing' image now contains both the tests and the original source to be tested. It can then simply be run as is or it can be run in 'watch mode' with volumes mapped to your source and test directories on the host.
If the tests are integration tests--for example the primary image might be a GraphQL server--then the image I create is self-contained, i.e., is not derived from the primary image (it still contains the tests and tools, of course). My tests use environment variables to tell them where to find the endpoint that needs testing, and it's easy enough to get Docker Compose to bring up both a container using the primary image, and another container using the integration testing image, and set the environment variables so that the test suite knows what to test.

A: Sadly it isn't currently possible to point to a specific file to use for .dockerignore, so we generate it in our build script based on the target/platform/image. As a docker enthusiast it's a sad and embarrassing workaround.


text:
Q: Searching Map by value field I have a Map implementation where I have to create a query whereby using value name field I need to return Key to that object.
One way is to use an iterator through the KeySet and check every Value, but it's not very efficient.
Time is an important factor.
Are there any interesting solutions/ libraries doing this?

A: You can use BiMap from the Guava framework:
https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap

A: yes.
using the Bidi Map :- Bidi Map
Download jar
How to use.
Example:-
BidiMap bidiMap = new DualHashBidiMap( );
bidiMap.put( "il", "Illinois" );
bidiMap.put( "az", "Arizona" );
bidiMap.put( "va", "Virginia" );
// Retrieve the key with a value via the inverse map
String vaAbbreviation = bidiMap.inverseBidiMap( ).get( "Virginia" );

// Retrieve the value from the key
String illinoisName = bidiMap.get( "il" );

Using the same approach you just need to implement the hascode() and equals() contract of a Map.
Solution :-

*

*we know that HashCode is used to Store in Bucket. Assume hashcode as row number in 2-D matrix and each Row has the linked List of entry[key,value].

*implement the hashcode() such that for each entry[key,value] you will get different `bucket no(row no).

*Implement equals() method to check the equality in each bucket's entry[key,value].

*Complexity :- if you assign each entry[key, value] to the different bucket then SEARCHING and ADDING complexity will be o(1).

*please refer the below documents for better understanding of solution:-doc1 doc2


text:
Q: The procedure entry point QueryFullProcessImageNameA could not be locatedin the dynamic link library KERNEL32.dll I am trying to run a program on Visual Studio on a XP computer and i am getting the error in the heading. I have all the service packs for XP and VS. Never seen anything like this before so i really dont have a clue. Anyone seen this problem before or know what might be going wrong?

A: This API is aviable since Vista see also the MSDN chapter requirements:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684919(v=vs.85).aspx
So far that API is simply not aviable. Try to search something equal for XP.


text:
Q: How to tick based on external time in C#? There is this API that when called gives me the time of a remote server. This is the response JSON of that API:
{
    hour: 12,
    minute: 2,
    second: 20,
    msFormat: "/Date(1590478340707)/"
}

This time is not in sync with the server my code runs on. And I need milliseconds precision for my code according to time of the remote server.
I want to call another API of that server, exactly based on some time relative to that server. Thus I can't use DateTime.Now of my own server, because they are not in sync. My server and the remote server have the same year, same month, same day, but they might sometimes even be off by hours.
I saw this question, but answers assume that I have access to JavaScript code on that server to get time. I don't. I also saw this question, but it's about sending my own client's time to my server. And as I said, I don't have access to creation of JavaScript's datetime. I only have access to data shown above.
Now I need to:

*

*Parse this time, exactly as it is, down to milliseconds precision

*Tick based on this time, so that I can do something precisely at some point in time, relative to it

I wanted to try new DateTime(year, month, day, hour, minute, second, millisecond), but I don't have the number of milliseconds (it's in the last parameter called msFormat and I don't know it until I extract it, which is what I don't know).
I tried new DateTime(1970, 01, 01).AddMilliseconds(1590478340707) which gives me a wrong time, because I know it's off even based on the remote server's time.
I also tried new System.Timers.Timer(1).Elapsed += HandleTimeBasedOnRemoteServerTime;. But now I have no idea how to know the time of that server, because I can't use DateTime.Now.
Could you please help?

A: The best solution is to ensure both servers are synchronising their clocks via ntp or similar protocol, making this someone else's problem, so you can simply assume the clock is correct.
If you can't do that for some reason, it should be possible to re-use ntp's source code as a library and construct fake messages from the data you have available. But with so many layers of abstraction, the accuracy of your time estimate may never reach 1ms.

My server and the remote server have the same year, same month, same day, but they might sometimes even be off by hours.

Are you sure the servers aren't just in different timezones? Always ensure that you are calculating times as UTC, even if you have to display / edit values in local timezones. For this, DateTimeOffset is a much better datatype as it can correctly preserve the source timezone information.
Back to your failed examples;
new DateTime(1970, 01, 01)

That constructor will leave the Kind unspecified, when you should be explicit about using UTC. It would be simpler to use the ticks constructor;
new DateTime(1590478340707 * 1000, DateTimeKind.Utc);


text:
Q: I want a selected item in combobox on formlogin to be automatically changed in Main form I have 2 forms:

*

*first the loginform, which contains combobox1 that user will select

*and then the Main form, which will be display the selected item in combobox1 on  the label1 in loginform.

I tried :
label1.Text = "welcome, "+ (new formlogin()).comboBox1.selectedItems.ToString();

,but I've got an error with message:
Unhandled exception has occurred in your application.

A: There are so many ways to do this... but this is the simplest way that I can think of:
Add this property into your FormMain:
public string UserName { get; set; }

Then, in your FormMain's load event:
label1.Text = this.UserName;

Then, from your FormLogin when you show the MainForm:
FormMain form = new FormMain();
form.UserName = combobox1.selectedItems.ToString();
form.Show();

A: Okay, the error message in the screenshot said

object reference not set to an instance of an object.

That means that you're trying to use an unsubstantiated object

It is most likely is that your formlogin constructor doesn't actually instantiate combobox1.selectedItems, thus causing the error.
But what i think you might be trying to do is the following
label1.Text = "welcome, "+ this.comboBox1.selectedItems.ToString();

A: This is how I did it:
In your Main Form you first declare loginForm and show it:
formlogin logForm = new formlogin();
logForm.FormClosing += loginFormClosing;
logForm.ShowDialog();

Then declare a new Method
public void loginFormClosing()
{
  //This method will be called when the loginform is closing
  //declare a variable in your loginform class and call it here like:

  label1.Text =  "welcome, "+ logForm.selectedItem.ToString();
}

I'm sure there is a better and smarter way to do this. But this is how I do it.


text:
Q: echo php function in HTML, will it work? I have a drop shadow function in PHP.
In my php page, I have HTML set up like this:
 <img src="<?php echo drpShadow($img_path[$i]);?>" />

The php function is like this:
     function drpShadow($pic_url){ echo "Hello";
    list($width, $height)=getimagesize($pic_url);
    $pic_display="

";
    for ($i=0; $i<($height-4); $i++){
        $pic_display.="
";
    }
    $pic_display.="

";
    for ($i=0; $i<=($width-6); $i++){
        $pic_display.="";
    }
    $pic_display.="

";
    return $pic_display;
}

This function doesn't get called because the echo "hello" doesn't show up.
How should I solve this?
Thanks

A: Because you are putting function output into src tag?
You would have something like this:
img src="Hello table border..."
Check in page source, you should see hello there ;)


text:
Q: Passing Html string to div innerhtml and its causing errors I'm running into an error when I try put this is in a textbox like this,
tbGameTitle.Text = "<iframe id = 'ForIframe' src='http://e.gamesalad.com/play/117208' allowTransparency='true' scrolling='no'></iframe>";

when I click on my button
myThing.InnerHtml = tbGameTitle.Text;

it throws this error
A potentially dangerous Request.Form value was detected from the client (tbGameTitle="<iframe id = 'ForIfr...").

If I have this load on the pageload event then its fine. But as soon as I enter this in the textbox and click on my button, it throws that error. I had it working in another project from way back and it never threw this error.

A: ASP.Net form content is checked for dangerous content when it is submitted (things like HTML and javascript are flagged as being potentially dangerous and are rejected). There are a few ways of allowing this content to be submitted, HTML encoding your text before it is send to the server or disabling request validation using a tag in the top of your page (potentially unsafe!):
<@ Page validateRequest="false" %>

More information on request validation can be found at this link

A: You need to escape characters like "<".
Read a little about: XSS
This post must be helpful.

the main code you want from that page is:
// The event to escape the data and store in our HiddenField
jQuery('.allow_html textarea').blur(function () {
    jQuery(jQuery(this).parent()).find('input[type="hidden"]').val(escape(jQuery(this).val()));
});

// The code to unescape the code and set it in our textbox
jQuery('.allow_html textarea').each(function(idx, item) {
    var value = jQuery(jQuery(item).parent()).find('input[type="hidden"]').val();
    jQuery(item).val(unescape(value));
});

that will escape HTML code in the input.
and, at the server side you need to unescape it:
// encode the data
HtmlCodeHiddenField.Value = Uri.EscapeDataString(EscapedHtml);
// decode the data
string myHtml = Uri.UnescapeDataString(HtmlCodeHiddenField.Value);


text:
Q: Different Meanings of "In The Way" For these two sentences:

*

*"People affect the law in the way it affects people."

*"People discuss the law in the way it affects people."

, could "in the way" have different meanings in the two sentences?
EDIT ADDITION:
But "in the way" appears to be often suggested as a definition for "as" when "as" is used in my original sentences like this:

1a. "People affect the law as it affects people."
  2a. "People discuss the law as it affects people."

What do the "as" in 1a and 2a mean?  Are the as's in 1a and 2a different?

A: Yes, it can... but I think the second one is an error.

People affect the law in the way it affects people.

This sense of in the way means "the very same way that" or "identically to".  So this sentence is saying that people and the law mutually affect one another in just the same way.

People discuss the law in the way it affects people.

I think this is a common English usage mistake, arising from mishearing and the way and mistaking it for the previous idiom.  So what this sentence is saying is that people discuss two topics, first being the law itself, and second being the way the law affect people.

A: No, the meanings of in the way in these two sentences are the same. In the way means "...in the same way that...".The second sentence is a bit confusing, you usually use the same verb if you use in the way. The first sentence mean(you might want the opposite of this meaning) that:

*

*People see how the law affects people

*People copy the way the law affects people and apply that way to the law itself

If you want to say the people affects the law first, just reverse it:

The law affects people in the way people affect the law.

To the edit:
1a can be understood in two ways.

*

*People affect the law while it affects people.

*People affect the law in the same way that it affects people.

2a can be understood like:

People discuss the law while it affects people.


text:
Q: How to show 3 fields in a single textbox in an asp.net GridView I need 3 Fields. Two fields in first line last fields in another line. My code is below.
Text='<%#Eval("FirstName")+" - "+ Eval("Lastname")+""+ Eval("Designation")%>'

A: Text='<%# Eval("FirstName")+" - "+ Eval("Lastname")+"\n" + Eval("Lastname")%>'
The Above code working


text:
Q: How to set up node-gyp correctly and simply on windows ( or avoid it all together ) Has anyone got a clear simple path for installing node-gyp correctly.
I am moving away from C# etc to node development - and while I am a newbie with node.js - I am quite disappointed that the major issues I have had have been with a Microsoft related tool.
I need node-gyp ( I think ) to be able to use printers and connect to serial ports & barcode scanners - so I need to be able to get it going consistently or somehow avoid it all together.
I have successfully compiled on 2 different machines.. but it seems that anytime I have to do something on a new machine ( for something like electron or windows server )  - then I seem to spend hours trying to get it going.
The following line is supposed to work:
npm install --global --production windows-build-tools

And then when adding a package than needs node-gyp - I get the following error
The Windows SDK version 8.1 was not found.

That SDK is installed already ( and tried reinstaling ) . I can't believe how horrible this is to configure and I have read may posts online that don't help.
It seems utterly ridiculous to install packages and complete development environments that are many GBs to get this going.
help!

A:
I think you have not installed Windows SDK 8.1 correctly. Here is the download link:

https://developer.microsoft.com/en-us/windows/downloads/sdk-archive

When the download has finish, restart your computer and adding package ;)

~XeCrafT


text:
Q: Display literal text in HTML I need to display some literal text in my HTML page (it's automatically generated by an application. I wrote in C#.)

    398
    Name:  ' an image.jpg

The " ' " character causes the problem, because it's a HTML escape character. (There are also other escape characters used in file names.) I can't change the file names. So how can I display the literal text in my HTML page?

A: EDIT: in case of Windows Forms, you can use:
System.Web.HttpUtility.HtmlEncode(yourString);

It is necessary to add a reference to System.Web.dll in your project. Remember that in HTML the attributes should be enclosed with the quote char " and not with apex, '.

You can simply use the
HttpServerUtility.HtmlEncode

method; moreover, the ' is not the problem, maybe it can be the quote, ", or < and > characters.
The following example encodes a string for transmission by HTTP. It encodes the string named TestString, which contains the text "This is a <Test String>.", and copies it into the string named EncodedString as "This is a <Test String>.".
C#:
String TestString = "This is a <Test String>.";
String EncodedString = Server.HtmlEncode(TestString);

A: Use
'

instead.
Here is reference to HTML Entities and Codings (http://www.zytrax.com/tech/web/entities.html)


text:
Q: Production Server for React Redux Starter Kit I am using the React Redux Starter Kit from DaveZuko, and am stuck on how to create production server to serve the compile client side code.Ideally I would just like to use the Koa server and move it to production, but can't find out how to do that.
All relevant code is unchanged from the repository here: https://github.com/davezuko/react-redux-starter-kit
Does anybody know how to compile a product server for this?

A: I did try to use davezuko's starter kit, but it was really hard to follow what those configuration files really did and messed them up when trying to install packages that were missing.
I also tried facebook's create-react-app, but that was really complex too when you run the eject command, so I gave up and created my own starter kit http://redux-minimal.js.org/ . I has the minimum amount of packages that lets you build rich real-word apps, but doesn't have the cluttered configuration boilerplate that other starter kits have.
Now, answering your question, with redux minimal, you just do "npm run build-prod" and it compiles the css and js files for the production environment, minified and ready to go. Then you just copy the public folder which contains the html file too, paste to what ever server you want, and then call the index.html url and it works.


text:
Q: extjs4 - DataView with remote(ajax) store not working I've been trying to get a DataView (aka Ext.view.View) to work with a remote store for a while but I can't get it to work.
So I went back to the drawing board and tried to build a simple one based on the Sencha doc's dataview component (from this page).
When I run the code with the default sample non-remote store it works fine. As soon as I turn the store to an ajax data store it stops working.
Here's the code I have:
Ext.define("Admin.TestDataView",{

    extend : 'Ext.DataView'

    ,initComponent: function()
    {

        Ext.regModel('Image', {
            Fields: [
                {name:'src', type:'string'},
                {name:'caption', type:'string'}
            ]
        });

        this.thestore = Ext.create('Ext.data.Store', {
            id:'imagesStore',
            model: 'Image',

            // data commented out and replaced with a proxy:
            /*
            data: [
                {src:'http://www.sencha.com/img/20110215-feat-drawing.png', caption:'Drawing & Charts'},
                {src:'http://www.sencha.com/img/20110215-feat-data.png', caption:'Advanced Data'},
                {src:'http://www.sencha.com/img/20110215-feat-html5.png', caption:'Overhauled Theme'},
                {src:'http://www.sencha.com/img/20110215-feat-perf.png', caption:'Performance Tuned'}
            ],
            */
            proxy: {
                type: 'ajax',
                url : '/test/somedata',
                reader: {
                    type: 'json',
                    root: 'results'
                }
            },
            autoLoad:true
        });

        var imageTpl = new Ext.XTemplate(
            '<tpl for=".">',
                '
',
                  '',
                  '
{caption}',
                '
',
            '</tpl>'
        );

        Ext.apply(this, {
            store: Ext.data.StoreManager.lookup('imagesStore'),
            tpl: imageTpl,
            itemSelector: 'div.thumb-wrap',
            emptyText: 'No images available',
            renderTo: Ext.getBody()
        });

        this.callParent(arguments);

    }
});

As you can see this essentially the sample code from the doc, with a remote store instead of the inline data.
The /test/somedata url is a simple codeiginiter controller method like this:
function somedata()
{
    $data =array(
        'success'=>true,
        'results'=> array(
                array('src'=>'http://www.sencha.com/img/20110215-feat-drawing.png', 'caption'=>'Drawing & Charts'),
                array('src'=>'http://www.sencha.com/img/20110215-feat-data.png', 'caption'=>'Advanced Data'),
                array('src'=>'http://www.sencha.com/img/20110215-feat-html5.png', 'caption'=>'Overhauled Theme'),
                array('src'=>'http://www.sencha.com/img/20110215-feat-perf.png', 'caption'=>'Performance Tuned')
        ));
    echo(json_encode($data));

}

All seems fine. The Firebug console shows the correct request and the data is returned correctly (i've got plenty of other controller returning data for other things and they work fine)..
Except the view is empty.
Where it gets interesting is, if I add a prepareData method to the dataview subclass like so:
,prepareData: function(data)
{
    console.log("prepareData(%o)",data);
    return data;
}

With the inline data, firebug shows this:

With the ajax store, firebugs shows this:

One interesting point is that the prepareData method is called 4 times, which indicates that in both cases, 4 records are loaded, but with the remote store the record data is empty..
Any idea? What am I doing wrong?

A: After digging up in the different objects created with firebug, something looked odd with the model.
Turns out there's a typo in the Ext doc..
In the model, the doc has Fields [...], that should be fields
    Ext.regModel('Image', {
        fields: [  // <-- here
            {name:'src', type:'string'},
            {name:'caption', type:'string'}
        ]
    });

I guess when using the inline data, the model isn't used in the same fashion as with the remote store (The model is still needed with the inline data as taking it out will throw an error on the reader).


text:
Q: QnA Maker gives different scores on each Training I am using QnA Maker with nodejs.
Steps to reproduce, In the created KB
Add a file -> Save and Train
Test with random text
remove file -> Save and Train

Again add the same file -> Save and Train

Test same chars _
Is there anything I can do to get same score, or is this expected one ?

A: QnA results are non-deterministic. What this means is the returned result can and will vary by small degrees following every API call with the same query. If you need to improve confidence scores, look over this document for suggestions.


text:
Q: The subspace of complex sequences $V_{\sigma}$ is closed under what topology? Let $C^\mathbb{N}$ be the vector space of complex sequences.  Let $V_{\sigma}$ be the vector subspace of $C^\mathbb{N}$ such that $(a_i) \in V_{\sigma}$ iff $\sum_{i=1}^{\infty} a_{\sigma(i)} \text{ converges }$.   If I want to show that any converging limits of sequences in $V_{\sigma}$ are contained in $V_{\sigma}$, i.e. it's closed, what topology would I need to work with?  $\sigma$ is a permutation of the indices.

A: We should probably use the sup norm: Wikipedia
I want to show that $V_{\sigma}$ is closed under the topology generated by the sup norm.
Let $(a_i^n)$ be a sequence of sequences in $V_{\sigma}$, i.e. $(a_i^1), (a_i^2), \dots$
Suppose it converges to a limit $(b_i) \in C^{\mathbb{N}}$, under the sup norm.  I want to show that $(b_i)$ is actually in $V_{\sigma}$.
For all $\epsilon \gt 0$ there's $N$ such that for all $n \gt N$, $\sup_{i\geq 1} |a^n_i - b_i| = \sup_{i\geq 1} |a_{\sigma(i)}^n - b_{\sigma(i)}| \lt \epsilon$ is given.
Maybe if a sequence of summable sequences converges to a sequence, then that sequence is also summable.


text:
Q: JavaFX "move" nodes I'am new new to JavaFX, and I got a problem. I'm trying to move Nodes with UP,DOWN,LEFT,RIGHT, if I just move my "Player" node, it's work perfectly, but I wanna make a game like sokoban, so my Player node can move "Crate" node, the problem is if I press the RIGHT next to the Crate, it swap the places, but not working correctly here is the moving method :
private void lepes(int i, int j, int target_i, int target_j){
      int ai, aj;
      int bi, bj;

      ai = i;
      aj = j;

      bi = target_i;
      bj = target_j;

      MyNode nodeA = playfield[ai][aj];
      nodeA.toFront();

      MyNode nodeB = playfield[bi][bj];
      nodeB.toFront();

      playfield[ai][aj] = nodeB;
      playfield[bi][bj] = nodeA;

      Path pathA = new Path();
      pathA.getElements().add (new MoveTo ( nodeA.getTranslateX() + nodeA.getBoundsInParent().getWidth() / 2.0, nodeA.getTranslateY() + nodeA.getBoundsInParent().getHeight() / 2.0));
      pathA.getElements().add (new LineTo( nodeB.getTranslateX() + nodeB.getBoundsInParent().getWidth() / 2.0, nodeB.getTranslateY() + nodeB.getBoundsInParent().getHeight() / 2.0));

      PathTransition pathTransitionA = new PathTransition();
      pathTransitionA.setDuration(Duration.millis(1));
      pathTransitionA.setNode( nodeA);
      pathTransitionA.setPath(pathA);

      pathTransitionA.play();

      Path pathB = new Path();
      pathB.getElements().add (new MoveTo ( nodeB.getTranslateX() + nodeB.getBoundsInParent().getWidth() / 2.0, nodeB.getTranslateY() + nodeB.getBoundsInParent().getHeight() / 2.0));
      pathB.getElements().add (new LineTo( nodeA.getTranslateX() + nodeA.getBoundsInParent().getWidth() / 2.0, nodeA.getTranslateY() + nodeA.getBoundsInParent().getHeight() / 2.0));

      PathTransition pathTransitionB = new PathTransition();
      pathTransitionB.setDuration(Duration.millis(1));
      pathTransitionB.setNode( nodeB);
      pathTransitionB.setPath(pathB);

      pathTransitionB.play();

      pathTransitionA.setOnFinished( new EventHandler<ActionEvent>() {

          @Override
          public void handle(ActionEvent event) {

              if( (pathTransitionB.getStatus() == Status.RUNNING))
                  return;
          }
      });

       pathTransitionB.setOnFinished( new EventHandler<ActionEvent>() {

          @Override
          public void handle(ActionEvent event) {

              if( (pathTransitionA.getStatus() == Status.RUNNING))
                  return;
          }
      });

}

and here is the eventHandler
        scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
          @Override
          public void handle(KeyEvent event) {
            if (event.getCode()==KeyCode.RIGHT) {

                if(jatekosX < 8 && playfield[jatekosX+1][jatekosY].getHisNumber() == 2){
                    lepes(jatekosX, jatekosY, jatekosX+1, jatekosY);
                    jatekosX++;
                    lepesek++;
                }
                else if(jatekosX < 8 && playfield[jatekosX+1][jatekosY].getHisNumber() == 1 ){

                    lepes(jatekosX+1, jatekosY, jatekosX+2, jatekosY);
                    lepes(jatekosX, jatekosY, jatekosX+1, jatekosY);
                    jatekosX++;
                    lepesek++;

                }

                System.out.println("Jobbra");
                System.out.println("X: " + jatekosX + "Y: " + jatekosY + " lépés: " + lepesek + "\n");
            }
          }
        });

Here is the picture next to crate node, https://postimg.org/image/7qkqxnxs5/
And here is after a Right step, https://postimg.org/image/t1ib1xfwl/
I Don't know what causes this.


text:
Q: IIS, Application Pools and Event Logs Running IIS 6 on a handful of Windows 2003 Web Ed. servers. Each has some App Pools configured with "Idle Timeout" of x minutes. No recycling, just the idle timeout from the Properties Performance tab.

I'd like to see when these guys shutdown from idle in the Event Viewer logs. So far haven't managed to make that happen. I know they're shutting down based on the reduction of w3p.exe processes in the evening and the fact that each day starts with those processes using less memory than at the end of the prev. day.
What I've Done So Far
I started at the TechNet article Logging Worker Process Recycling Events in IIS 6.0. For each App Pool I ran the following:
cscript adsutil.vbs set w3svc/AppPools/AppPoolName/EventName true

For EventName I used both AppPoolRecycleTime and AppPoolRecycleSchedule.
Next I found the How to modify Application Pool Recycling events in IIS 6.0 support article. For each App Pool I ran the following:
cscript adsutil.vbs Set w3svc/AppPools/DefaultAppPool/LogEventOnRecycle 255

Still no luck. I suspect in either case I'm not finding the right metabase property to set on or enable.
Does anyone know what I should enable to get logging for App Pool Idle timeouts?

A: Awww snap. I just found this nugget:

Important The metabase property
  IdleTimeout does not have an
  associated LogEventOnRecycle property
  flag. Therefore, when an application
  pool is shut down because the
  IdleTimeout value is reached, an Event
  log entry will not be logged.

at How to modify Application Pool Recycling events in IIS 6.0 right below the data table. I missed it the first time around.
Apparently what I want to log can't be done.


text:
Q: Updating image via Dispatcher still gives "different thread owns it" error I'm trying to update an Image in my UI from an event in a different thread. I'm using a Dispatcher (based on this question: Fire events from different thread) to do so, but still get the "The calling thread cannot access this object because a different thread owns it"-Error Message at i.Source = s;. What's the proper way of doing this?
void OnEvent(object sender, EventArgs e)
{
    ImageSource s = e.Image;
    Dispatcher.BeginInvoke((Action)(
        () => UpdateUI(myImage, s)
    ));
}

void UpdateUI(Image i, ImageSource s)
{
    i.Source = s;
}

Thanks a lot for any suggestions!

A: ImageSource created in background thread can't be assigned as source to UI control.
And you can access myImage.Dispatcher to get actual dispatcher associated with image control:
myImage.Dispatcher.BeginInvoke((Action)delegate
  {
     ImageSource s = e.Image;
     UpdateUI(myImage, s);
  });

OR
call Freeze() on ImageSource before assignment. Freeze objects can be accessed across thread.

A: You're getting this error because you ImageSource has been created on different thread then the one you want to use it on. You can fix it by calling Freeze() on your ImageSource
ImageSource s = e.Image;
s.Freeze();

A: You are dispatching on your current thread, not the UI thread. You first need to gain access to the UI Thread dispatcher. Use
Application.Current.Dispatcher.BeginInvoke(...)

instead.
Also see this question: How do I get the UI thread Dispatcher?


text:
Q: Does it take some time to start and stop Stopwatch? I have a very specific question that I need answered for a very specific performance test. I will simplify the code, to make it easier understandable.
I do many calculations (a few ten million), all done in loops that are themselves not too long and I need the total calculation time. However, all the calculations are not done directly one after another and some extra code "comes inbetween" every loop.
What I need, is quite exactly the total time of all loops (including declaring and initializing i, incrementing it, and comparison with 100 in exmaple). To measure the time I start a Stopwatch directly before every loop and stop it directly after the loop. But do those two actions need some time that might be relevant?
Example:
Stopwatch sw = new Stopwatch();

sw.Start();
//how long does it now take until for loop is reached?
for(int i = 0; i < 100; i++)
{
    //some calculations
}
//how much time does it take to stop sw?
sw.Stop();

Of course it wouldn't really matter if all the loops were done directly one after another, I could just start at the beginning of the first loop and stop at the end of the last one, but that is not possible here.
I know the question is very specific, but I hope someone can help me here, as a significant time coming from around fifty million loops, could in a way affect my results.

A:
What I need, is quite exactly the total time of all loops. To measure the time I start a StopWatch directly before every loop and stop it directly after the loop. But do those two actions need some time that might be relevant?

They take some time - as does the initialization of i, and the increment, and the comparison with 100 in each loop iteration. Almost nothing is instantaneous in computing.
Whether it's relevant or not is another matter. Unless your calculation is utterly trivial, it's unlikely that this will be significant in your timing. You could try timing an empty loop, but it's possible that the JIT compiler will get rid of the loop itself entirely.

A: Well, you could try this and check it on your own, on my (lousy performing ) computer it's about 0.0006 milliseconds for the first execution and 0.0001 milliseconds for next executions. Try it yourself:
Stopwatch sw = new Stopwatch();
sw.Start();
sw.Stop();
TimeSpan ts = TimeSpan.FromTicks(sw.ElapsedTicks);
string elapsed = ts.TotalMilliseconds.ToString();


text:
Q: Sort mapped list with Lodash on ReactJS I have an array:
people = [
  {
    name: "Kyle",
    _id: "2"
  },
  {
    name: Susan,
    _id: "1"
  }
]

I have a mapped list as such:
return (

    {people.map( (person) => {
      return (

          {person.name}
          {person.id}

       )
    })}

)

This is all working well, but how can I sort them, say based on "name"? I tried to use the [_.sortBy][1] but couldn't figure out how it would fit to the context of React and map function.  Using lodash, or underscore's _.sortBy would be appreciated.
Thanks!

A: In _.sortBy you can pass the name of the field that will be used for sorting your collection, read more about _.sortBy
var Component = React.createClass({
    getInitialState() {
        return {
            people: _.sortBy([
                { name: "Kyle", _id: 2},
                { name: "Susan", _id: 1}
            ], '_id')
        }
    },

    sortBy(field) {
        this.setState({
            people: _.sortBy(this.state.people, field)
        });
    },

    render: function() {
        var peopleList = this.state.people.map( (person, index) => {
            return (

                {person.name}
                {person.id}

);
        })

        return

            Sort By Id |
            Sort By Name

{peopleList}

;
    }
});

Example

A: You can use the sortBy like this:
_.sortBy(<array name here>, '<key here>')

Try
return (

        {_.sortBy(people, 'name').map( (person) => {
            return (

                    {person.name}
                    {person.id}

            )
        })}

)

A: You need to import it first
import sortBy from "lodash/sortBy";

And then you can use it like
const arr = [{id: 2}, {id: 0}];
sortBy(arr, "id");


text:
Q: How much lead is really on my hands when soldering? We have an electronic lab where we test and solder. There is a computer in the room as well. I have been wondering how much of that room is really contaminated with lead. We solder, go touch the oscilloscope or spectrum analyzer, google something here and there, open up all the drawers and what not etc. In my mind if were to visually see the lead in room I always think everything would be red. I rarely touch my phone while soldering or in the electronic lab but I've recently been doing so. When I follow what I touch when then going to the bathroom to wash my hands and then to my office, I think that lead is everywhere. I'm not talking crazy amounts just that it could be there. Sometimes I touch my keys etc. etc. etc.
So when one is dealing with lead solder, how much is really being transferred to other things when one touches their phone, a doorknob, the computer mouse/keyboard etc.? Or is it such a small amount that one shouldn't necessarily worry about it?
We use 60/40 solder.

A: This fear of lead is largely mis-guided. Yes, there have been reports of children falling ill from eating paint chips with lead in them. But this was made into a big deal because it happened to a child, whose quality of life suffered. But where are the reports of adults with lead-poisoning? Do any of those involve routes other than consuming lead? Why don't people whom are shot with lead bullets get lead poisoning?
The answer is the "consume-ability" of lead (and other metals) by the body. Half of the population has an amalgam of various metals (including mercury) in their mouths in the form of dental fillings. Mercury is extremely toxic; perhaps you've heard of the recent concern over mercury content of fish. Mercury doesn't seem to make anyone sick when it is in fillings however - but it does when eaten. And gold in fact, is even more toxic - but that is also a common tooth filling. However you can eat gold and it won't hurt you... what is going on here?
The process of eating metals is where the problem lies. In our stomachs lies very strong (hydrochloric) digestive acid. This acid breaks down most metals into a "metal salt" form, which IS absorb-able by the body. Once in the metal salt form, the trouble begins. Lead for example, is treated like calcium in the body, so it is stored in the bones.
Gold however, is not dissolve-able by hydrochloric acid, so remains inert.
There is a process to "rid" of the body of some metal contaminants, called chelation therapy. So if you know you have eaten lead, chelation will remove it from your bones. If it has been 20 years since you ate the lead however, the damage has already been done and chelation will help little.
So unless you've eaten lead, there really is no cause for concern. That said, you should be careful when eating after being near lead. Namely, wash your hands and avoid contaminating your food. Wipe down surfaces (do not use anything acidic) and consider them cleaned.
With toxic mercury in our mouths and deadly gold in our fillings, touching lead should now seem a lot less scary.
P.S. Note that modern solder is lead-free. So-called ROHS solder does not contain any lead at all. Still, eating it is a very bad idea so the same cleanliness guidelines apply. Standard 60/40 rosin-core solder is what this is referring to. Also note that acid-core lead solder, while rare today, may be potentially more hazardous due to the intrinsic acid content.

A: If you happen to be working with older equipment, or you are trying to exhaust a supply of old solder or old components, then there may indeed be a significant amount of lead in your environment. Note that I did not say a "dangerous" amount, nor did I say a "negligible" amount.
A common problem with older homes is that lead was also used in paint, so there are lead test kits on the market that you can use to look for lead in the environment. If you are worried, I suggest that you start with one of these.

A: Phones are everywhere, follow you home, and are difficult to wet clean so I keep mine in a PVC phone bag meant to be waterproof and I wash it down if it gets dirty with dish soap. Also helps when working around grease and gunk and stuff.
I've heard that people who cast bullets for long periods of time end up with visible, grey, lead residue on their hands. They are working with alloys of much higher lead content (>90%). Inkless pens also use lead (real Pb, not graphite) to make their marks but I don't know what alloy that is but that does give you an idea.
The Brinell hardness, which is indicative of how easily a material is rubbed off and leave residue, of the following materials is:

*

*100% Pb is 5 BHN

*63/37 solder is 17 BHN

*HB pencil lead is 14-15 BHN (obtained from bullet casters who use art/drafting pencils as gauges for the alloys they cast)

*F pencil lead is 16-18 (obtained from bullet casters who use art/drafting pencils as gauges for the alloys they cast)

*6B pencil lead is supposed to be the same as pure lead, 5 BHN (obtained from bullet casters who use art/drafting pencils as gauges for the alloys they cast)

*softwood is 1.6 BHN

*hardwood is 2.6-7 BHN

And just for real world reference:

*

*Pure Cu is 35 BHN

*Pure Al is 15 BHN (the closest you probably see to this is aluminum foil)

*6061 Al is 95 BHN (the kind you probably see if it is a chunk of aluminum)

*6063 Al is 75 BHN (the other kind you probably see if it is a chunk of aluminum)

*mild steel is 120 BHN

*18-8 stainless steel is 200 BHN (cutlery)

Plus larger particles produced from soldering which aren't as insidious because more difficult to spread
Buy a set of artist pencils and scribe them on some solder and find the pencil before and after it will no longer leave a mark on the solder. Then play around with those two pencils by lightly heading a piece of paper to get an idea of how easily the solder rubs off.


text:
Q: R: barplot inconsistent width I have two sets of data
Co1 Col2
1    10
2    12
3    13
4    14
5    15
6    16
7    17
8    18
9    19

I put these two data into two variables Num and Leaf respectively
and I tried to plot them with barplot(Leaf,Num, space=0.5,col="red")
Everything is fine, besides that some bars have larger width than the others. While some other bars have no width and literablly became a line.
Why is that?
I know i can fix it by doing barplot(Leaf,Num, space=0.5,col="red", width=0.5)
But I am wondering why the default behavior of such function gives you inconsistent bar width

A: In base R you can do
barplot(df$Col2, names.arg = df$Co1)

Or using ggplot
library(ggplot2)
ggplot(df, aes(as.factor(Co1), Col2)) + geom_col() + xlab("Co1")

A: dataset = data.frame(Leaf,Num)
barplot(dataset$Leaf,dataset$Num,space=0.5,col="red")

or
barplot(Leaf,Num,space=0.5,col="red")


text:
Q: How to prove that LDA has a similar form to Logistic Regression for the binary classification example? I was studying the book "An Introduction to Statistical Learning" by Gareth James, Daniela Witten, et al. and saw the following line on page 151:

In the LDA framework, we can see from (4.12) to (4.13) (and a bit of
simple algebra) that the log odds is given by:

$$ log \left(\frac{p_1(x)}{1-p_1(x)}\right) = log \left(\frac{p_1(x)}{p_2(x)}\right) = c_0 + c_1(x) $$
How can this proved?

A: Its just algebra.
In the first edition of the book, equation 4.12 states that the posterior probability for each class can be written using Bayes rule as
$$ p_k = \dfrac{\pi_k f(x, \mu_k)}{\sum_k \pi_k f(x, \mu_k)} $$
Here, $\pi_k$ is the prior probability of class $k$ and $f(x, \mu_k)$ is a gaussian density with mean $\mu_k$.  The density of $x$ for each class is assumed to have the same variance.
Now comes the algebra.  Note
$$ \log \left( \dfrac{p_1}{p_2} \right) = \log\left( \dfrac{\pi_1 f(x, \mu_1)}{\pi_2 f(x, \mu_2)} \right) $$
Leveraging some properties of logs
$$ = \underbrace{\log(\pi_1/\pi_2)}_{c_0} + \underbrace{\log(f(x, \mu_1)/f(x, \mu_2))}_{c_1(x)}$$
EDIT: Gordon Smyth correctly notes that a much stronger statement can be made about $c(x)$, namely that it is linear in $x$.  This is also rather straight forward to show.
Since LDA makes the assumption of homogeneity in the variance term between classes, $\log(f(x, \mu_1) / f(x, \mu_2))$ simplifies to
$$ \log(f(x, \mu_1) / f(x, \mu_2)) = -\dfrac{1}{2\sigma^2} \Big( (x-\mu_1)^2 - (x- \mu_2)^2\Big)$$
More algebra shows the $x^2$ term cancels out, yielding
$$ = - \dfrac{1}{2\sigma^2} ( -2 \mu_1 x + \mu_1^2 + 2\mu_2x - \mu_2^2) = \dfrac{1}{\sigma^2} \Big( (\mu_1 - \mu_2)\cdot x + 2(\mu_2^2 - \mu_1^2) \Big)$$
which is clearly a linear function in $x$.  You could do some re-arranging so that $c_0$ has all the constant terms and $c(x)$ has only terms involving $x$, but it largely doesn't matter.

A: You can view the logistic function as originating from two normal distributed samples.
Say $U \sim N(\mu_U , \sigma)$ and $V \sim N(\mu_Y, \sigma)$ then the relative density of $U$ and $V$ as function of the position is
$$\frac{f_U(x)}{f_V(x)} = \frac{e^{\frac{(x-\mu_U)^2}{2\sigma^2}}}{e^{\frac{(x-\mu_V)^2}{2\sigma^2}}} = e^{\frac{(x-\mu_U)^2 - (x-\mu_V)^2}{2\sigma^2}} = e^{\frac{\mu_U^2+\mu_V^2 - 2x(\mu_U-\mu_V)}{2\sigma^2}} = e^{a+bx}$$
with $a= \frac{\mu_U^2+\mu_V^2}{2\sigma}$ and $b= \frac{\mu_U-\mu_V}{\sigma}$

With LDA you get these two normal distributed samples. LDA assumes that the samples are normal distributed and with the same covariance matrix. In the multidimensional picture you need an extra step but you get that the density ratio along the factor/component (the linear combination found with LDA) is just like the one dimensional picture above. I'll have to make a good illustration of this but you can see this by the points with equal odds ratios being on straight lines/planes (in particular the classifier for odds ratio equal to one is known).


text:
Q: Does a DNS A record redirect slow down load speeds? (with example) I have a website hosted on my server that is taking longer to load than our other websites despite the fact that it's built the same. To test further, I made an exact copy of the website and put it on a sub-domain.
I noticed that the sub-domain copy load anywhere from 10%-70% faster every time. The only difference I can think of is that the live site's DNS is pointed elsewhere, and just uses an A record to redirect to our servers.
Is this the reason why? If so, is there any ways to avoid this?
You can see the website and it's clone and test their speeds at whichloadsfaster.com
http://tinyurl.com/9vmebl9 vs. http://tinyurl.com/8dg6evt

A: Difference in DNSrequest is minor. Changes from 0.1 to 0.2 seconds each time.
I checked your links and now I can actually see differences. It seem likt the subdomain loads faster. This could be a server configuration issue. However there are several linked files (internal and external) that are missing (reset.css,uclass.css,body-bg.gif,museoslab-500-webfont.ttf etcetera) also FB links load on very different times.
I also notice the HTTP GET for /british-columbia/ is 23.7 KB on the subdomain but 23.9 KB on the main domain (I haven't checked why but it seem the documents are different?)
My few tips in optimizing for speed is:

*

*use gzip compression

*use clever caching for different content

*put as much javascript as possible just before </body>

A: Load times are only affected by DNS resolution at extreme levels. This doesn't appear to be the case for you.
It's far more likely to be a configuration issue on your host, and how traffic is directed within the web server's network.


text:
Q: Removing the bottom border from the active tab How can the html code be modified below so as to get rid or hide the bottom border from the active and/or selected tab? I can't seem to figure this out and it doesn't make any sense to me.
<style type="text/css">
      ul#tabs { list-style-type: none; margin: 30px 0 0 0; padding: 0 0 0.3em 0; }
      ul#tabs li { display: inline; }
      ul#tabs li a { color: #42454a; background-color: #dedbde; border: 1px solid #c9c3ba; border-bottom: none; padding: 0.3em; text-decoration: none; }
      ul#tabs li a:hover { background-color: #f1f0ee; }
      ul#tabs li a.selected { color: #000; background-color: #f1f0ee; font-weight: bold; padding: 0.3em 0.3em 0.38em 0.3em; }
      div.tabContent { width: 1000px; border: 1px solid #c9c3ba; padding: 0.5em; background-color: #f1f0ee; }
      div.tabContent.hide { display: none; }
    </style>

Here is the fiddle: http://jsfiddle.net/EnfxC/

A: if you want to hide the bottom border, then you can write the code in css: (add another class for this)
bottom-border:none !important;
Please tell me the html code...then i could help you


text:
Q: Best Practice: Multiple branches for different API versions or single branch We are still designing how the API versioning should be managed. As of now we have 2 options:

*

*All the versions in the same branch

*

*Disadvantage: All versions might be using the same core libraries which might be affected by a new commit. There is no code freeze on the older versions.

*Different branches for each version

*

*Disadvantage: Manging lot of branches might be a nightmare when it comes to maintanence

Is there any other option to do it in a better way or should I have to proceed with one of the above?

A: I would suggest separate release branches for each API. You can do bug fixes to old versions off of the release branches.
You shouldn't have lots of versions of your API. If this is a web API, then non-breaking changes don't need a new version. If this is a programming language API, then each major release should be a branch, with minor releases as tags or sub-branches off of the release.


text:
Q: AJAX RSS JS responseXML returning null {
 xmlHttp=GetXmlHttpObject();
 if (xmlHttp==null)
  {
  alert ("Browser does not support HTTP Request");
  return;
  }
 var url="http://www.galatasaray.org/_ajax/dinamik_fikstur.php?no=6";
 xmlHttp.onreadystatechange=stateChanged;
 xmlHttp.open('GET',url,true);
 xmlHttp.setRequestHeader('Content-type', "text/xml");
 xmlHttp.send(null);
 }
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
 xmlDoc=xmlHttp.responseXML;
 alert(xmlHttp.responseXML);
 document.getElementById("myDiv").innerHTML=xmlHttp.responseXML;
 document.getElementById("takim2").innerHTML=
 xmlDoc.getElementsByTagName("owner")[0].childNodes[0].nodeValue;
 document.getElementById("takim1").innerHTML=
 xmlDoc.getElementsByTagName("guest")[0].childNodes[0].nodeValue;
 }
}
function GetXmlHttpObject()
 {
 var objXMLHttp=null;
 if (window.XMLHttpRequest)
  {
  objXMLHttp=new XMLHttpRequest();
  }
 else if (window.ActiveXObject)
  {
  objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 return objXMLHttp;
 }

Im new for ajax programming and I have a problem. responseXML returning null. How can I fix the problem? I tried responseText and returned empty. I searched a lot of source But I cant find a solution


text:
Q: Centering elements in kivy: using root vs self.parent I'm reading the kivy documentations. In it, there's an example on how to make your own pong game.
In general, the tutorial is very clear. However, at some point there was something subtle I wasn't sure about.
They make a ball in the .kv file:
<PongBall>:
    size: 50,50
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

Then, they add an instance of a PongBall to a previously defined PongGame class:
<PongGame>:
    canvas:
        Rectangle:
            pos:self.center_x - 5 , 0
            size : 10, self.height
    Label:
        font_size : 70
        center_x : root.width / 4
        top : root.top - 50
        text : "0"
    Label:
        font_size : 70
        center_x : root.width / 4 * 3
        top : root.top - 50
        text: "0"
    PongBall:
        center: self.parent.center

In the PongGame labels they added, the set the location using root, which references the PongGame
For the PongBall they set the location using self.parent.center, where self.parent appears to reference the PongGame. I am assuming there is a reason they used:
<PongBall>:
    PongBall:
        center: self.parent.center

instead of
<PongBall>:
    PongBall:
        center: root.center

Why did they not use root.center as they did for the labels? Is there a reason for picking one over the other? Is there a difference?

A: They do this, because the ball should be relative to the position of the game widget. The labels on the other hand are "dead". They just have to "exist" at the point they got in the beginning of the game, but the ball has to "live"


text:
Q: WCF Byte Array - The maximum array length quota error I am getting following error while returning byte array with WCF Service
"The maximum array length quota (16384) has been exceeded while reading XML data.
This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 23626."
I even tried to increase the
  <wsHttpBinding>
    <binding name="EnrollmentSoapBinding" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647">
      <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647" />
    </binding>
  </wsHttpBinding>

Also,
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>

still no luck. Any other ideas?

A: Both your client and service have to have the maxArrayLength property set in their configurations.
You're obviously not setting it in one of them. As the default is 16384 for maxArrayLength.

A: In addition to Derek's answer, there are a couple of other possibilities the new value for maxArrayLength is not being picked up.
One is that the binding configuration has not been assigned to the endpoint.  For example, if the endpoint looks like this:
<endpoint address="" binding="wsHttpBinding" contract="MyService.IMyService1" />

Then the default values for wsHttpBinding will be used, regardless of what may be specified elsewhere in the config file.  To assign the defined binding configuration, use the bindingConfiguration attribute:
<endpoint address="" binding="wsHttpBinding"
          bindingCongifuration="EnrollmentSoapBinding"
          contract="MyService.IMyService1" />

Another possibility is if there is no endpoint defined (in the service, at least).  In this case, the framework (in .NET 4.0 and later) will provide a default endpoint.  That default endpoint will use basicHttpBinding by default and have default values for it.
There are a few things that can be done in that scenario.  An endpoint can be explicitly declared and have the binding assigned to it (as shown in the first part of my answer).
The binding can be declared and set as the default by omitting the name attribute, like this:
<wsHttpBinding>
  <binding maxReceivedMessageSize="2147483647"
           maxBufferPoolSize="2147483647">
    <readerQuotas maxArrayLength="2147483647"
                  maxStringContentLength="2147483647"
                  maxBytesPerRead="2147483647" />
  </binding>
</wsHttpBinding>

In this case, if there's no endpoint defined, you'd also need to change the protocol mapping for http:
<protocolMapping>
  <add binding="wsHttpBinding" scheme="http"/>
</protocolMapping>

This would then set wsHttpBinding to be the default binding for http, and the "custom" default binding settings defined above would be used.
Without seeing both the service and client config, it's hard to say what the real issue is.


text:
Q: How to render a texture on moving circles with SDL2 and OpenGL in C++? This is my current code :
All the include
#define GLEW_STATIC
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <math.h>
#include <stdio.h>
#include <iostream>
#include<conio.h>
#include<dos.h>
#include <GL/glew.h>
#include "SceneOpenGL.h"
#include <SDL2/SDL_image.h>

using namespace std;

#ifdef WIN32
#include <GL/glew.h>

#else
#define GL3_PROTOTYPES 1
#include <GL3/gl3.h>

#endif

#include <SDL2/SDL.h>
#include <iostream>

Voiding my function
void DrawCircle(float cx, float cy, float r, int num_segments);
void DrawEllipse(float cx, float cy, float a, float b, int num_segments);
void Rotation(float a,float b,float r, float g_theta );

The main function
int main(int argc, char **argv)
{
SDL_Window* fenetre(0);
SDL_GLContext contexteOpenGL(0);

SDL_Event evenements;
bool terminer(false);

if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
    std::cout << "Erreur lors de l'initialisation de la SDL : " << SDL_GetError() << std::endl;
    SDL_Quit();

    return -1;
}

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

fenetre = SDL_CreateWindow("Test SDL 2.0", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);

if(fenetre == 0)
{
    std::cout << "Erreur lors de la creation de la fenetre : " << SDL_GetError() << std::endl;
    SDL_Quit();

    return -1;
}

contexteOpenGL = SDL_GL_CreateContext(fenetre);

if(contexteOpenGL == 0)
{
    std::cout << SDL_GetError() << std::endl;
    SDL_DestroyWindow(fenetre);
    SDL_Quit();

    return -1;
}

#ifdef WIN32

    GLenum initialisationGLEW( glewInit() );

    if(initialisationGLEW != GLEW_OK)
    {

        std::cout << "Erreur d'initialisation de GLEW : " << glewGetErrorString(initialisationGLEW) << std::endl;

        SDL_GL_DeleteContext(contexteOpenGL);
        SDL_DestroyWindow(fenetre);
        SDL_Quit();

        return -1;
    }

#endif

Main loop with the display of the circle and the ellipse
 while(!terminer)
{
    SDL_WaitEvent(&evenements);

    if(evenements.window.event == SDL_WINDOWEVENT_CLOSE)
        terminer = true;

glClear(GL_COLOR_BUFFER_BIT);

float g_theta = 0.0f;

while (g_theta<360)
{
glClear(GL_COLOR_BUFFER_BIT);
g_theta += 1.0f;
DrawCircle(0, 0, 0.3, 50);
Rotation(0.8,0.65,0.1,g_theta);
Rotation(0.5,0.5,0.2,g_theta);
Rotation(0.1,0.1,0.01,g_theta);

    glDisableVertexAttribArray(0);
    SDL_GL_SwapWindow(fenetre);
}
}
SDL_GL_DeleteContext(contexteOpenGL);
SDL_DestroyWindow(fenetre);
SDL_Quit();

return 0;

}

Function creating the circle
void DrawCircle(float cx, float cy, float r, int num_segments)
{
    glBegin(GL_LINE_LOOP);
for(int ii = 0; ii < num_segments; ii++)
{
    float theta = 2.0 * M_PI * float(ii) / float(num_segments);

    float x_c = r * cosf(theta);//calculate the x component
    float y_c = r * sinf(theta);//calculate the y component
    glColor3f(1.0f,0.0f,0.0f);
    glVertex2f(x_c + cx, y_c + cy);//output vertex
}
glEnd();
}

Function creating the ellipse
    void DrawEllipse(float cx, float cy, float a, float b, int num_segments)
{
        glBegin(GL_LINE_LOOP);
    for(int ii = 0; ii < num_segments; ii++)
    {
        float theta = 2.0 * M_PI * float(ii) / float(num_segments);

        float x_e = a * cosf(theta);//calculate the x component
        float y_e = b * sinf(theta);//calculate the y component
        glColor3f(0.0f,0.0f,1.0f);
        glVertex2f(x_e + cx, y_e + cy);//output vertex
    }
    glEnd();
}

Function that links the circle and the ellispe
    void Rotation(float a,float b,float r, float g_theta )
{

float x = a * cosf(g_theta * M_PI / 180.0f);
float y = b * sinf(g_theta * M_PI / 180.0f);
float d = sqrtf( x*x + y*y );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();

glPushMatrix();
glRotatef( g_theta, 0, 0, 1 );  // rotation around the z axis
glTranslatef( d, 0, 0 );        // translation by the distance

DrawCircle(0, 0, r, 50);
glPopMatrix();

DrawEllipse(0, 0, a, b, 50);

}

Its result is :
compilation's result : the red cricles are actually moving  on their own blue ellispes

I would like that each circle has its own texture.
I already donwloaded SDL2_image and tried this code :
  IMG_Init(IMG_INIT_JPG);
  SDL_Surface * image = IMG_Load("PICT3159.JPG");
  IMG_Quit();

But nothing happend.
How can I render textures on this moving circles?
(PS : My final goal is to create a 2D representation of our solar system.)
EDIT :
I know how to display an image.
I do it like this :
    SDL_Renderer *pRenderer =
    SDL_CreateRenderer(fenetre,-1,SDL_RENDERER_ACCELERATED); // Création d'un
    SDL_Renderer utilisant l'accélération matérielle

    if ( pRenderer )
{
        SDL_Surface* pSprite = SDL_LoadBMP("earth.bmp");
        if ( pSprite )
    {
            SDL_Texture* pTexture =
SDL_CreateTextureFromSurface(pRenderer,pSprite); // Préparation du sprite
        if ( pTexture )
        {
            SDL_Rect dest = { 640/2 - pSprite->w/2,480/2 - pSprite->h/2, pSprite->w, pSprite->h};
            SDL_RenderCopy(pRenderer,pTexture,NULL,&dest); // Copie du sprite grâce au SDL_Renderer

            SDL_RenderPresent(pRenderer); // Affichage
           SDL_Delay(3000); /* Attendre trois secondes, que l'utilisateur voit la fenêtre */

          //  SDL_DestroyTexture(pTexture); // Libération de la mémoire associée à la texture
        }
        else
        {
            fprintf(stdout,"Échec de création de la texture (%s)\n",SDL_GetError());
        }

        SDL_FreeSurface(pSprite); // Libération de la ressource occupée par le sprite
    }
    else
    {
        fprintf(stdout,"Échec de chargement du sprite (%s)\n",SDL_GetError());
    }

    SDL_DestroyRenderer(pRenderer); // Libération de la mémoire du SDL_Renderer
}
else
{
    fprintf(stdout,"Échec de création du renderer (%s)\n",SDL_GetError());
}

Perhaps it would be easier to resize the image, cut it into a round shape and rotate it on the ellipse?
(But I do not know how to do it either)


text:
Q: Significant amount of RAM missing I have an Ubuntu server that is using bitcoind to download the blockchain and some other tasks. The blockchain is fully synced. I know that it can be a memory hog which is why I've tried to limit the amount of RAM it uses, but it seems that it is not successful.
The arguments I am using to reduce memory usage are:
-dbcache=20
-maxsigcachesize=4
-maxconnections=4
-rpcthreads=1
-par=2

cat /proc/meminfo Information:
MemTotal:        4194304 kB
MemFree:          282108 kB
Cached:          3634908 kB
Buffers:               0 kB
Active:           820684 kB
Inactive:        3077500 kB
Active(anon):     133488 kB
Inactive(anon):   132396 kB
Active(file):     687196 kB
Inactive(file):  2945104 kB
Unevictable:          64 kB
Mlocked:              64 kB
SwapTotal:             0 kB
SwapFree:              0 kB
Dirty:                 0 kB
Writeback:             0 kB
AnonPages:        265884 kB
Shmem:              2608 kB
Slab:              13920 kB
SReclaimable:       8096 kB
SUnreclaim:         5824 kB

Executing ps aux  | awk '{print $6/1024 " MB\t\t" $11}'  | sort -n gives me the following information:
0 MB        COMMAND
0 MB        [khelper/270]
0 MB        [kthreadd/270]
0.664062 MB     sh
0.753906 MB     sort
0.777344 MB     upstart-file-bridge
0.808594 MB     upstart-udev-bridge
0.828125 MB     /sbin/getty
0.832031 MB     /sbin/getty
0.972656 MB     awk
0.972656 MB     upstart-socket-bridge
1.10938 MB      ps
1.39844 MB      /lib/systemd/systemd-udevd
1.39844 MB      su
1.48047 MB      rsyslogd
1.70703 MB      tmux
2.04297 MB      -bash
2.06641 MB      -bash
2.54688 MB      init
3 MB        /usr/sbin/sshd
3.86328 MB      sshd:
29.4609 MB      /usr/lib/erlang/erts-5.10.4/bin/beam.smp
285.316 MB      ./bin/bitcoind

If bitcoind is only taking 285MB then why do I only have less than 300MB of RAM left out of 4GB? The bitcoind is ran inside a tmux session and after being killed I do not get any more RAM back.

A: Cached:          3634908 kB
This is your HDD read/write cache. Linux and most other OSs will use all available memory for drive cache. This cache size is not fixed. If your programs need  more memory then some it will be flushed to disk to make room for the running program.


text:
Q: Using javascript to set cookie in IE
document.cookie= "cookiename=cookievalue;
  expires=Mon,12Jun2015:00:00:00; path=/;"

I run this script on my Internet Explorer 10 but it doesn't share cookie between 2 IE tab. But when i remove the "expires" properties so it seem to working :
document.cookie= "cookiename=cookievalue ;path=/;"

But i don't want to remove the "expires" properties. So how to resolve this problem ?

A: 2021 update: If you do NOT need to pass information to the server, use localStorage or sessionStorage
I have used this code since mid '90s - it has worked in all browsers on all platforms so far
Include the file and use
setCookie("name","value",expiryDate,"/"); // the last two are optional

// cookie.js file
var cookieToday = new Date();
var expiryDate = new Date(cookieToday.getTime() + (365 * 86400000)); // a year

/* Cookie functions originally by Bill Dortsch */

function setCookie (name,value,expires,path,theDomain,secure) {
   value = escape(value);
   var theCookie = name + "=" + value +
   ((expires)    ? "; expires=" + expires.toGMTString() : "") +
   ((path)       ? "; path="    + path   : "") +
   ((theDomain)  ? "; domain="  + theDomain : "") +
   ((secure)     ? "; secure"            : "");
   document.cookie = theCookie;
}

function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      var offset = document.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
         offset += search.length
         // set index of beginning of value
         var end = document.cookie.indexOf(";", offset)
         // set index of end of cookie value
         if (end == -1) end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      }
   }
}
function delCookie(name,path,domain) {
   if (getCookie(name)) document.cookie = name + "=" +
      ((path)   ? ";path="   + path   : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}

A: The following sample code will demonstrate setting a cookie of your choosing directly, without requiring input from the user. To store a cookie from your site, simply put a call to the javascript function in your HTML page, like this:
<script type="text/javascript">cookieSet();</script>

The real work is done by the cookieSet() javascript function, which can be either in the  area of your HTML page, or in a separate javascript file:
var cookieText = "Put your desired cookie value here";
var cookiePrefix = "";
var myPage = location.href;
var wwwFlag = myPage.indexOf('www');
if (wwwFlag > 0) {
cookiePrefix = "www";
}
var cookieName = cookiePrefix + "cbCookie";
function cookieSet() {
if (document.cookie != document.cookie) {
index = document.cookie.indexOf(cookieName);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookieName+"="+cookieText+"cbEndCookie; expires=Monday, 04-Apr-2020 05:00:00 GMT";
}
}


text:
Q: get solana transaction-history for a given address - based on date range I want to use Rust or Python to retrieve historical Solana transactions for a given wallet - in a specific date range.
There is the get_confirmed_signature_for_address2() which returns signatures for a given address, with an option to get signatures before a given signature.
But how can I find historical transactions using a specific timestamp?

A: getBlockTime will give you the estimated time for a given block
getBlock will give the list of signatures in a specific block
getSignatures will get you the signatures for an address 1000 at a time, before or after a given signature.
Combine them with a binary search algorithm to find nearby timestamp


text:
Q: Can you recommend any NuGet packages for console app argument parsing and pipelining specifically for .NET 6.0? I'm currently looking for packages to help me develop a C# console app for automatisation in .NET 6.0, the packages should ideally support me in the following tasks:

*

*command line argument parsing

*autocompletion for parameters on the commandline (with TAB)

*"pipelining" or "chaining" the output from one command as input to the next, like it is done f.e. in powershell:

Command-1 | Command-2 | Command-3

Are there any packages that should be used for this specifically in .NET 6.0 (and the new command line template) ?

For "command line argument parsing" I implemented CommandLineParser (last updated 5/1/2020) in the current prototype, which works fine, however this article recommends the new System.CommandLine and also mentions other packages, should I favour that in .NET 6.0 ? Regarding pipeling I found this old SO post, is pipelining even something that is done in C# console apps, or should I consider implementing PowerShell Cmdlets for that?


text:
Q: angular.js ng-repeat - check if conditional is true then use another collection I'm wondering is it possible to check what collection to use inside ng-repeat?
For example, in my controller I have 2 arrays of data fetched from server, now I use ng-switch to switch between them, check this jsbin - http://jsbin.com/diyefevi/1/edit?html,js,output
The problem is that these li views in my real application are big but very similar.. so I really would like to use 1 ng-repeat instead of 2.
So I wonder if something like ng-repeat="book in if list==='adultBooks' adultBooks else childBooks" is possible in Angular?
Thanks!

A: Try this ...
In your controller
$scope.getDataSource=function(condition){

  if(condition){ return dataSource1; }
  return dataSource2;
};

In your Html
ng-repeat="book in getDataSource(/*condition*/)

MVVM Pattern advises to put our logic always in the controller and not in the view(HTML). If you ever find yourself adding "logic" in your view probably there is an alternate "better" way to do it.
But just for "fun" you can do this too:
ng-repeat="book in {true: adultBooks, false: childBooks}[list==='adultBooks']"

Like this:

{{book.name}

Here is the full sample:
http://jsbin.com/diyefevi/5/edit?html,js,output

A: The simplest solutions I can think of would be to define a new array on the scope which you set the other arrays to when you need.
E.g. http://jsbin.com/diyefevi/4/edit?html,js,output

A: Something like this would eliminate the need for ng-switch:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

  Toggle List

{{list}}

{{book.name}}

and the js:
var app = angular.module('test', []);
app.controller('MainCtrl', function ($scope) {
  $scope.list = 'childBooks';

  $scope.childBooks = [{name: 'Dodobird'}, {name: 'Catty Red Hat'}];

  $scope.adultBooks = [{name: 'Little Lady'}, {name: 'Johny Doe'}];

  $scope.toggleList = function () {
    $scope.list = $scope.list === 'childBooks' ? 'adultBooks' : 'childBooks';
  };

  $scope.getBooks = function() {
    if($scope.list == 'adultBooks') {
      return $scope.adultBooks;
    } else {
      return $scope.childBooks;
    }
  }
});

Here is the jsbin code


text:
Q: Вывод данных в консоль из Firebase-базы Как вывести из базы данных на скрине значение balance в консоль?

A: Я так понял что подпапки Users это Uid?
Если нужен баланс по одному пользователю -
Код:
var users = new Firebase("https://<yourappname>.firebaseio.com/users");
var authData = users.getAuth();
var usersRef = ref.child("users/" + authData.uid + "/balance");
usersRef.once("value", function(snapshot) {
var data = snapshot.val();
console.log(data);
});

А вот если для всех пользователей, нужно делать цикл, который будет перебирать UID, менять usersRef, и таким образом вытаскивать информацию.

A: ref.child('users').child(authData.uid).child('balance').on("value",
function(snapshot) {
  console.log('snapshot.val()); // 0
});


text:
Q: Sphinx include only classes, functions which contain docstring I have multiple classes in a python file (sqlalchemy classes to be precise). I am trying to document some classes with sphinx package.
I put some docstrings under some classes but in the end all classes are listed, with and without docstring.
I am using autodoc:
Contents:

.. toctree::
   :maxdepth: 3

.. automodule:: blog.models
   :members:

The only way I can specify which classes I want to be included is like this:
.. automodule:: blog.models
   :members: SomeClass, SomeClass2, .., SomeClass1001

Is there a way to add only classes, functions, which are with docstring?


text:
Q: What is GNU Grub and why does it show up when I start my computer? I'll freely admit to not being the most knowledgeable with this kind of thing, but I want to be transitioning over to Linux from Windows. For a variety of reasons, however, I have to keep a Windows install on this machine.
See title for the core question, but I do have a secondary question, is GNU Grub something I can use to choose which OS I want to boot in to? And, if so, what would I have to type to choose? At the moment I just tell it to exit and it kicks me back into Windows, but I do need to get to Linux somehow.


text:
Q: Why is it my code cannot run many clients in java multithreading? Why is this code nott accumulating many clients?
I'm new to java.
It only runs for only 1 client.
Can anyone explain why it doesn't support multiple clients for socket programming?
import java.net.*;
import java.io.*;

/**
 * Demo Server: Contains a multi-threaded socket server sample code.
 */
public class ServerDemo extends Thread
{
    final static int _portNumber = 5559; //Arbitrary port number

    public static void main(String[] args)
    {
        try {
            new ServerDemo().startServer();
        } catch (Exception e) {
            System.out.println("I/O failure: " + e.getMessage());
            e.printStackTrace();
        }

    }

    public void startServer() throws Exception {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(_portNumber);
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + _portNumber);
            System.exit(-1);
        }

        while (listening) {
            handleClientRequest(serverSocket);
        }

        serverSocket.close();
    }

    private void handleClientRequest(ServerSocket serverSocket) {
        try {
            new ConnectionRequestHandler(serverSocket.accept()).run();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Handles client connection requests.
     */
    public class ConnectionRequestHandler implements Runnable{
        private Socket _socket = null;
        private PrintWriter _out = null;
        private BufferedReader _in = null;

        public ConnectionRequestHandler(Socket socket) {
            _socket = socket;
        }

        public void run() {
            System.out.println("Client connected to socket: " + _socket.toString());

            try {
                _out = new PrintWriter(_socket.getOutputStream(), true);
                _in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));

                String inputLine, outputLine;
                BusinessLogic businessLogic = new BusinessLogic();
                outputLine = businessLogic.processInput(null);
                _out.println(outputLine);

                //Read from socket and write back the response to client.
                while ((inputLine = _in.readLine()) != null) {
                    outputLine = businessLogic.processInput(inputLine);
                    if(outputLine != null) {
                        _out.println(outputLine);
                        if (outputLine.equals("exit")) {
                            System.out.println("Server is closing socket for client:" + _socket.getLocalSocketAddress());
                            break;
                        }
                    } else {
                        System.out.println("OutputLine is null!!!");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally { //In case anything goes wrong we need to close our I/O streams and sockets.
                try {
                    _out.close();
                    _in.close();
                    _socket.close();
                } catch(Exception e) {
                    System.out.println("Couldn't close I/O streams");
                }
            }
        }

    }

    /**
     * Handles business logic of application.
     */
    public static class BusinessLogic {
        private static final int LoginUserName = 0;
        private static final int LoginPassword = 1;
        private static final int AuthenticateUser = 2;
        private static final int AuthSuccess   = 3;

        private int state = LoginUserName;

        private String userName =  null;
        private String userPassword =  null;

        public String processInput(String clientRequest) {
            String reply = null;
            try {
                if(clientRequest != null && clientRequest.equalsIgnoreCase("login")) {
                    state = LoginPassword;
                }if(clientRequest != null && clientRequest.equalsIgnoreCase("exit")) {
                    return "exit";
                }

                if(state == LoginUserName) {
                    reply = "Please Enter your user name: ";
                    state = LoginPassword;
                } else if(state == LoginPassword) {
                    userName = clientRequest;
                    reply = "Please Enter your password: ";
                    state = AuthenticateUser;
                } else if(state == AuthenticateUser) {
                    userPassword = clientRequest;
                    if(userName.equalsIgnoreCase("John") && userPassword.equals("doe")) {
                        reply = "Login Successful...";
                        state = AuthSuccess;
                    } else {
                        reply = "Invalid Credentials!!! Please try again. Enter you user name: ";
                        state = LoginPassword;
                    }
                } else {
                    reply = "Invalid Request!!!";
                }
            } catch(Exception e) {
                System.out.println("input process falied: " + e.getMessage());
                return "exit";
            }

            return reply;
        }
    }
}

A: You are not starting the thread in your code.
instead of
new ConnectionRequestHandler(serverSocket.accept()).run();

call
new Thread(new ConnectionRequestHandler(serverSocket.accept())).start();

method run() of your Runnable class will be invoked when you start your thread, you should not call this run() method directly.
Instead of that you should make a thread instance via
Thread myThread = new Thread(aRunnableInstance);

and start it:
myThread.start();

A: You're not starting a new thread, but simply running the RequestHandler code in the main thread.
Look up the difference between Thread.start() and Runnable.run(). This question might help.
Edit:
You're just missing the part where you would tell the JVM to create a new Thread to execute your Runnable code. Without a call to Thread.start() your current (and only) thread would be busy handling one request at a time. You want one Thread per request, basically. There are more advanced ways of doing this (thread pools and whatnot), but this should get you started.
private void handleClientRequest(ServerSocket serverSocket) {
    try {
        new Thread(ConnectionRequestHandler(serverSocket.accept())).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: How to view a big picture by dragging on Android? Just like we do on Google Maps I've being trying this all night through.    Is there any good solution to do this? Having a sample code is better!

A: I will answer my own question, after a loooong time.
I finally found a solution, just use the WebView, to load the image in the browser inside the WebView, Android then did everything for me!


text:
Q: Laravel: Order hasManyThrough I struggle to understand the "hasManyThrough" concept in laravel.
I got something similar to these tables:
project
- id

project_document
- id
- project_id

project_document_order
- id
- project_document_id

In the project model I've got these relations:
public function projectDocuments(){
    return $this->hasMany(
        ProjectDocuments::class,
        'project_id'
    );
}

public function projectDocumentOrder(){
    return $this->hasManyThrough(
        ProjectDocumentOrder::class,
        ProjectDocuments::class,
        'project_id',
        'project_document_id'
    );
}

Project::where( 'id', $pid )->with( 'projectDocuments', 'projectDocumentOrder' )->firstOrFail();

This results in one project with multiple projectDocuments and multiple projectDocumentOrder.
Result:
#original: array:14 [▼]
"id" => 1
"uuid" => [UUID]
"author" => 1
"project_name" => [NAME]

#relations: array:2 [▼]
"projectDocuments" => Illuminate\Database\Eloquent\Collection {#1352 ▼
    #items: array:5 [▼
        0 => App\Models\projectDocuments {#1368 ▼
            #original: array:10 [▼
                "id" => 1
                "user_id" => 471
                "project_id" => 1
        }
        1 => App\Models\projectDocuments {#1368 ▼
            #original: array:10 [▼
                "id" => 2
                "user_id" => 252
                "project_id" => 1
        }
        2 => App\Models\projectDocuments {#1368 ▼
            #original: array:10 [▼
                "id" => 3
                "user_id" => 252
                "project_id" => 1
        }
        3 => App\Models\projectDocuments {#1368 ▼
            #original: array:10 [▼
                "id" => 4
                "user_id" => 471
                "project_id" => 1
        }
        4 => App\Models\projectDocuments {#1368 ▼
            #original: array:10 [▼
                "id" => 5
                "user_id" => 252
                "project_id" => 1
        }
    ]
}
"projectDocumentOrder" => Illuminate\Database\Eloquent\Collection {#1367 ▼
  #items: array:5 [▼
        0 => App\Models\projectDocumentOrder {#1368 ▼
            #original: array:10 [▼
                "id" => 1
                "project_documents_id" => 1
                "order" => 1
        }
        1 => App\Models\projectDocumentOrder {#1368 ▼
            #original: array:10 [▼
                "id" => 2
                "project_documents_id" => 1
                "order" => 2
        }
        2 => App\Models\projectDocumentOrder {#1368 ▼
            #original: array:10 [▼
                "id" => 3
                "project_documents_id" => 1
                "order" => 3
        }
        3 => App\Models\projectDocumentOrder {#1368 ▼
            #original: array:10 [▼
                "id" => 4
                "project_documents_id" => 1
                "order" => 5
        }
        4 => App\Models\projectDocumentOrder {#1368 ▼
            #original: array:10 [▼
                "id" => 5
                "project_documents_id" => 1
                "order" => 4
        }
    ]
}

Now my question: how would I go about ordering projectDocuments based on the order column in projectDocumentOrder?

A: First I think you only need the with: 'projectDocumentOrder', because laravel to get to projectDocumentOrder, will need to join projectDocuments.
Second You could do something like:
Project::where( 'id', $pid )->with(['projectDocuments'=>function($query){
   $query->leftJoin('table_name','local_key','operator','foreign_key');
   $query->orderBy('table_name.field','ASC|DESC');
)
}])->firstOrFail();

A: I found a solution that works for me.
$project->projectDocumentOrder->sortBy( 'order' )->pluck('projectDocuments')->toJson()

This solution does require having a projectDocuments function linking the ProjectDocumentOrder to the ProjectDocuments in the ProjectDocumentOrder model.