问:
RandomAccessFile readFully EOF exception
I get EOF exception using RandomAccessFile class and read or readFully methods.
The length of the data I am trying to read is 1 and offset is 0 so I wouldn't expect receiving EOF exception. I see the file is created and written into it successfully.

This is my code:

```<code>private static void createFile() {

    if(pub_f != null)
    {
        System.out.println("file already exists");
    }
    try
    {
        pub_f = new RandomAccessFile("file.bin", "rw");
        pub_f.setLength(10*1024);
    }
    catch (IOException e)
    {
        System.out.println("fail to open file. Exception message: " + e.getMessage());
        e.printStackTrace();
    }

    if(f == null)
    {
        System.out.println("fail to open file");
    }
    else
    {
        System.out.println("file created");
    }

    //initialize file content
    for(int i = 0; i<10240; i++)
    {
        try
        {
            pub_f.write(0);
        }
        catch (IOException e)
        {
            System.out.println("fail to initialize file content. Exception message: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

public int ReadFile(int offset, int length, byte[] data)
{
    if (pub_f == null)
    {
        System.out.println("fail to open file for reading");
        return -1;
    }

    try
    {
        pub_f.readFully(data, offset, length);
    }
    catch (IOException e)
    {
        System.out.println("fail to read from file. Exception message: "+ e.getMessage());
        e.printStackTrace();
        return -1;
    }

    return 0;
}
</code>```

In my main:

```<code>int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
readFile(offset, len, data);
</code>```

Please can someone help to find what I am missing here?

Thanks!

答:
You are forgetting to seek (set the file pointer) back to the start of the file after writing to it, so it will try to read from the end of the file. Which will give you the aptly named EOFException.

Add a call to seek(0L) before reading, to start reading from the beginning of the file.

```<code>int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
pub_f.seek(0L); // <---- set the file pointer back to the start of the file.
readFile(offset, len, data);
</code>```

Body:
I get EOF exception using RandomAccessFile class and read or readFully methods.
The length of the data I am trying to read is 1 and offset is 0 so I wouldn't expect receiving EOF exception. I see the file is created and written into it successfully.

This is my code:

private static void createFile() {

    if(pub_f != null)
    {
        System.out.println("file already exists");
    }
    try
    {
        pub_f = new RandomAccessFile("file.bin", "rw");
        pub_f.setLength(10*1024);
    }
    catch (IOException e)
    {
        System.out.println("fail to open file. Exception message: " + e.getMessage());
        e.printStackTrace();
    }

    if(f == null)
    {
        System.out.println("fail to open file");
    }
    else
    {
        System.out.println("file created");
    }

    //initialize file content
    for(int i = 0; i<10240; i++)
    {
        try
        {
            pub_f.write(0);
        }
        catch (IOException e)
        {
            System.out.println("fail to initialize file content. Exception message: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

public int ReadFile(int offset, int length, byte[] data)
{
    if (pub_f == null)
    {
        System.out.println("fail to open file for reading");
        return -1;
    }

    try
    {
        pub_f.readFully(data, offset, length);
    }
    catch (IOException e)
    {
        System.out.println("fail to read from file. Exception message: "+ e.getMessage());
        e.printStackTrace();
        return -1;
    }

    return 0;
}

In my main:

int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
readFile(offset, len, data);

Please can someone help to find what I am missing here?

Thanks!

Body:
You are forgetting to seek (set the file pointer) back to the start of the file after writing to it, so it will try to read from the end of the file. Which will give you the aptly named EOFException.

Add a call to seek(0L) before reading, to start reading from the beginning of the file.

int len = 1;
int offset = 0;
byte[] data = new byte[512];
createFile();
pub_f.seek(0L); // <---- set the file pointer back to the start of the file.
readFile(offset, len, data);


来源: stackexchange

问:
PHP: Standards of class constructors preventing instantiation
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

```<code>    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }
</code>```

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?

答:
getInstance() is used ALL over the place in the Zend Framework, which is my goto for standards and conventions in code.

as for the create(), what about using the magic __construct method so that when you do new Blah() it calls the __construct method for that class?

ContentLicense: CC BY-SA 2.5

Body:
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?


问:
PHP - Is it possible to upload a zip file to the database after the zip is created in php?
So, I watched a tutorial from a youtube video here how to zip a file using php. This is the code I copied.

This is the form to upload zip. I choose 7 files and then name the archive name "testing".

After I clicked the "Add Files to Zip", the files are zipped and are sent to the directory.

These are the code

HTML Code:

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Zip Archiving Tutorial</title>
</head>

<body>

<form action="" method="POST" enctype="multipart/form-data">
Archive Name: <input type="text" name="name"><br />
<input type="file" name="files[]" multiple="true">
<input type="submit" name="create" value="Create Zip"><br><br>
<input type="submit" name="upload" value="Upload to Database">

</form>
</code>```

PHP Code:

```<code><?php

if(isset($_POST['create']))
{
$filesArray = $_FILES["files"];

for($num = 0; $num < count($filesArray["name"]); $num++)
{
    $fileName = $filesArray["name"][$num];
    $tempName = $filesArray["tmp_name"][$num];

    move_uploaded_file($tempName,"tmp/".$fileName);
}

$archiveName = $_POST['name'].".zip";
$filesArrayNames = $_FILES["files"]["name"];

$zipsDir = scandir("zips/");
$error = false;
foreach($zipsDir as $zipDirFile)
{
    if($zipDirFile == $archiveName)
    {
        $error = true;
        break;
    }
}

if($error == false)
{
    $tmpDir = scandir("tmp/");
    $zip = new ZipArchive;
    $zip->open("zips/".$archiveName, ZipArchive::CREATE);

    for($num = 0; $num < count($filesArray["name"]); $num++)
    {
        $fileName = $filesArray["name"][$num];
        foreach($tmpDir as $tmpDirFile)
        {
            if($tmpDirFile == $fileName)
            {
                $zip->addFile("tmp/".$fileName);
                echo "Adding: ".$fileName."<br />";
            }
        }
    }
    $zip->close();

    for($num = 0; $num < count($filesArray["name"]); $num++)
    {
        $fileName = $filesArray["name"][$num];
        foreach($tmpDir as $tmpDirFile)
        {
            if($tmpDirFile == $fileName)
            {
                unlink("tmp/".$fileName);
            }
        }
    }
}

else
{
    echo "Name already exists";
}
}

if (isset($_POST['upload']))
{
    //code to add for uploading zip file to database

}

?>
</code>```

But is it possible to upload the zip file after it is the files is zipped through php? I want the user to upload the files after the files are zipped.

答: PHP does not work on the user machine(the client) but in the server, so if you want to zip and then upload files think of scripts that run in the client side like javascript(angularjs, jquery and other libraries you can use) to use to zip you file and php  to accept them into the server.

ContentLicense: CC BY-SA 3.0

Body:
So, I watched a tutorial from a youtube video here how to zip a file using php. This is the code I copied.

This is the form to upload zip. I choose 7 files and then name the archive name "testing".

After I clicked the "Add Files to Zip", the files are zipped and are sent to the directory.

These are the code

HTML Code:

<!doctype html>

<meta charset="utf-8">
<title>Zip Archiving Tutorial</title>

<form action="" method="POST" enctype="multipart/form-data">
Archive Name: <input type="text" name="name">

<input type="file" name="files[]" multiple="true">
<input type="submit" name="create" value="Create Zip">

<input type="submit" name="upload" value="Upload to Database">

</form>

PHP Code:

<?php

if(isset($_POST['create']))
{
$filesArray = $_FILES["files"];

for($num = 0; $num < count($filesArray["name"]); $num++)
{
    $fileName = $filesArray["name"][$num];
    $tempName = $filesArray["tmp_name"][$num];

    move_uploaded_file($tempName,"tmp/".$fileName);
}

$archiveName = $_POST['name'].".zip";
$filesArrayNames = $_FILES["files"]["name"];

$zipsDir = scandir("zips/");
$error = false;
foreach($zipsDir as $zipDirFile)
{
    if($zipDirFile == $archiveName)
    {
        $error = true;
        break;
    }
}

if($error == false)
{
    $tmpDir = scandir("tmp/");
    $zip = new ZipArchive;
    $zip->open("zips/".$archiveName, ZipArchive::CREATE);

    for($num = 0; $num < count($filesArray["name"]); $num++)
    {
        $fileName = $filesArray["name"][$num];
        foreach($tmpDir as $tmpDirFile)
        {
            if($tmpDirFile == $fileName)
            {
                $zip->addFile("tmp/".$fileName);
                echo "Adding: ".$fileName."
";
            }
        }
    }
    $zip->close();

    for($num = 0; $num < count($filesArray["name"]); $num++)
    {
        $fileName = $filesArray["name"][$num];
        foreach($tmpDir as $tmpDirFile)
        {
            if($tmpDirFile == $fileName)
            {
                unlink("tmp/".$fileName);
            }
        }
    }
}

else
{
    echo "Name already exists";
}
}

if (isset($_POST['upload']))
{
    //code to add for uploading zip file to database

}

?>

But is it possible to upload the zip file after it is the files is zipped through php? I want the user to upload the files after the files are zipped.


问:
cannot find symbol“_mm256_max_epu8” when I want to use AVX2 instruction in visual studio 2010
Environment: Win10, Intel Core i7 5500U CPU, Visual Studio 2010 Ultimate

Now I want to use "_mm256_max_epu8" Intel SIMD instruction which is in AVX2,but the Visual Studio 2010 tells me that:

1>..\svCore\svGrayMorph.cpp(838): error C3861: “_mm256_max_epu8”: 找不到标识符

I have found that AVX2 instructions should be declared in file:

...\Microsoft Visual Studio 10.0\VC\include\immintrin.h

However, the file only have AVX instructions, the "_mm256_max_epu8" and other instructions are not in that file.

While the immintrin.h file of Visual Studio 2013 include the AVX2 instruction.

Do SomeOne Know What I can Do to compile this code in Visual Studio 2010 ?

Thank you so much.

答:
It seems that the symbol _mm256_max_epu8 can be used with Visual Studio 2013 or Visual Studio 2012 as found in those two Intrinsics Lists.

And of course it works as well with VS2015

But does not exist in visual studio 2010

Visual Studio 2010 support: /arch:SSE|SSE2|AVX,

And Visual Studio 2013 support: /arch:IA32|SSE|SSE2|AVX|AVX2


问:
iPhone 6 - position: fixed - not loading until stop scrolling
There are a lot of posts on this site that I have read but nothing is working for me and I'm not sure why.

I'm trying to make a menu that "sticks" to the top of the page as you scroll past it and vice versa (stops sticking when you scroll back up)

Javascript

```<code> $(document).ready(function(){
      var top = $('#FloatingMenu').offset().top - parseFloat($('#FloatingMenu').css('marginTop').replace(/auto/,100))
      document.addEventListener("scroll",Scroll,false);
      document.addEventListener("gesturechange",Scroll,false);
      function Scroll() {
           var y = $(this).scrollTop();
           if (y >= top) {
               $('#FloatingMenu').addClass('fixed');
           } else {
               $('#FloatingMenu').removeClass('fixed');
      }
</code>```

CSS

```<code> #FloatingMenu.fixed {
     position: fixed;
     top: 0;
     left: 0;
     z-index: 1;
     width: 100%;
     background-color: black;
     color: red;
  }
  #FloatingMenu {
     background-color: red;
     color: black;
     width: 100%;
     text-align: center;
  }
</code>```

I've tried doing repainting, i've tried stopping the "inertia" scrolling (which I can't get to stop on Chrome on iOS) Either way, everything I've tried has the same results.  Works perfectly in a PC or on a Android, but on an iPhone, the menu will not repaint and be "stuck" at the top until the scrolling stops AND the finger is removed from the screen.

Is there a fix for this?  Everything I'm reading suggests that there is but notn a single solution has changed anything for me.

The strange thing is, if your scrolling back up (the menu is already stuck at the top) and you scroll past it, it auto un-sticks (even while scrolling) and works fine.

The only time its a problem is when its "repainting" the "fixed" menu.

I hope there is a solution.  Everything suggests that after iOS 8 it was fixed (and i'm testing on 10+) but It wont show the menu while scrolling until you stop and let go.  Tested on an iPhone 6 and and iPad Air 2.  safari and chrome, same results across the board.

答:
The problem is with position:fixed. This seems to have known issues with safari specifically on mobile devices. After doing some searches for hours, I believe that I may have been able to fix this issue.

The solution I used is to use position:-webkit-sticky for iOS safari and use position:sticky for desktop browsers. More documentation on this property can be found here :

http://caniuse.com/#feat=css-sticky

Can you please try the following code:

CSS:

```<code>  #FloatingMenu.fixed {
     top: 0;
     left: 0;
     z-index: 1;
     width: 100%;
     background-color: black;
     color: white;
  }
  #FloatingMenu {
     position: -webkit-sticky;
     position: sticky;
     background-color: lightgray;
     color: black;
     width: 100%;
     height: 60px;
     text-align: center;
     padding-top: 18px;
     font-weight: 800;
  }
</code>```

JS :

```<code> $(document).ready(function(){
    var top = $('#FloatingMenu').offset().top - parseFloat($('#FloatingMenu').css('marginTop').replace(/auto/,100));
    window.addEventListener('scroll',Scroll,false);
      function Scroll() {
        var y = $(this).scrollTop();
        if (y > top) {
            $('#FloatingMenu').addClass('fixed');
        } else if (y<=top) {
            $('#FloatingMenu').removeClass('fixed');
        }
    }
  });
</code>```

Please note that I have removed the fixed property completely and applied the sticky property to the #FloatingMenu selector itself. Seems to work for me on my iOS simulator safari, and iPhone 6 Safari and on Chrome & Safari in my desktop.

A simple working example of this fix can be found here : Link

Hope this helps. Cheers.

Body:
There are a lot of posts on this site that I have read but nothing is working for me and I'm not sure why.

I'm trying to make a menu that "sticks" to the top of the page as you scroll past it and vice versa (stops sticking when you scroll back up)

Javascript

 $(document).ready(function(){
      var top = $('#FloatingMenu').offset().top - parseFloat($('#FloatingMenu').css('marginTop').replace(/auto/,100))
      document.addEventListener("scroll",Scroll,false);
      document.addEventListener("gesturechange",Scroll,false);
      function Scroll() {
           var y = $(this).scrollTop();
           if (y >= top) {
               $('#FloatingMenu').addClass('fixed');
           } else {
               $('#FloatingMenu').removeClass('fixed');
      }

CSS

 #FloatingMenu.fixed {
     position: fixed;
     top: 0;
     left: 0;
     z-index: 1;
     width: 100%;
     background-color: black;
     color: red;
  }
  #FloatingMenu {
     background-color: red;
     color: black;
     width: 100%;
     text-align: center;
  }

I've tried doing repainting, i've tried stopping the "inertia" scrolling (which I can't get to stop on Chrome on iOS) Either way, everything I've tried has the same results.  Works perfectly in a PC or on a Android, but on an iPhone, the menu will not repaint and be "stuck" at the top until the scrolling stops AND the finger is removed from the screen.

Is there a fix for this?  Everything I'm reading suggests that there is but notn a single solution has changed anything for me.

The strange thing is, if your scrolling back up (the menu is already stuck at the top) and you scroll past it, it auto un-sticks (even while scrolling) and works fine.

The only time its a problem is when its "repainting" the "fixed" menu.

I hope there is a solution.  Everything suggests that after iOS 8 it was fixed (and i'm testing on 10+) but It wont show the menu while scrolling until you stop and let go.  Tested on an iPhone 6 and and iPad Air 2.  safari and chrome, same results across the board.

Body:
The problem is with position:fixed. This seems to have known issues with safari specifically on mobile devices. After doing some searches for hours, I believe that I may have been able to fix this issue.

The solution I used is to use position:-webkit-sticky for iOS safari and use position:sticky for desktop browsers. More documentation on this property can be found here :

http://caniuse.com/#feat=css-sticky

Can you please try the following code:

CSS:

  #FloatingMenu.fixed {
     top: 0;
     left: 0;
     z-index: 1;
     width: 100%;
     background-color: black;
     color: white;
  }
  #FloatingMenu {
     position: -webkit-sticky;
     position: sticky;
     background-color: lightgray;
     color: black;
     width: 100%;
     height: 60px;
     text-align: center;
     padding-top: 18px;
     font-weight: 800;
  }

JS :

 $(document).ready(function(){
    var top = $('#FloatingMenu').offset().top - parseFloat($('#FloatingMenu').css('marginTop').replace(/auto/,100));
    window.addEventListener('scroll',Scroll,false);
      function Scroll() {
        var y = $(this).scrollTop();
        if (y > top) {
            $('#FloatingMenu').addClass('fixed');
        } else if (y<=top) {
            $('#FloatingMenu').removeClass('fixed');
        }
    }
  });

Please note that I have removed the fixed property completely and applied the sticky property to the #FloatingMenu selector itself. Seems to work for me on my iOS simulator safari, and iPhone 6 Safari and on Chrome & Safari in my desktop.

A simple working example of this fix can be found here : Link

Hope this helps. Cheers.


问:
Why does this *ptr NOT give the actual value stored at the memory address contained in ptr variable?
Here is a basic C program about pointers:

```<code>#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}
</code>```

This produces the following output:

```<code>Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14
</code>```

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

答:
14 is the HEX value of 20.

Change printf format specifier to %d instead of %x to have 20 as output

```<code>printf("Address of variable: %d\n", *pointerToVariable);
</code>```

Moreover correct format specifier for pointers is %p, so

```<code>printf("Address of variable: %x\n", pointerToVariable);
</code>```

must be

```<code>printf("Address of variable: %p\n", (void *)pointerToVariable);
</code>```

Body:
Here is a basic C program about pointers:

#include <stdio.h>

int main() {
    int variable = 20;
    int *pointerToVariable;

    pointerToVariable = &variable;

    printf("Address of variable: %x\n", &variable);
    printf("Address of variable: %x\n", pointerToVariable);
    printf("Address of variable: %x\n", *pointerToVariable); // * is the DEREFERENCING OPERATOR/INDIRECTION OPERATOR in C.
                                                                //It gives the value stored at the memory address
                                                                //stored in the variable which is its operand.
    getchar();
    return 0;
}

This produces the following output:

Address of variable: 8ffbe4
Address of variable: 8ffbe4
Address of variable: 14

But *pointerToVariable should print 20, shouldn't it? Because * gives the actual value stored at the memory address stored in its operand, right?
What am I missing?

Body:
14 is the HEX value of 20.

Change printf format specifier to %d instead of %x to have 20 as output

printf("Address of variable: %d\n", *pointerToVariable);

Moreover correct format specifier for pointers is %p, so

printf("Address of variable: %x\n", pointerToVariable);

must be

printf("Address of variable: %p\n", (void *)pointerToVariable);


问:
SQL CE 4.0 in Reference Manager of VS
There

I install both of SQL CE version 3.5 and 4.0 on my development machine, which installed VS 2012.
My problem is: But I cannot find 4.0 version from "Reference Manager" of VS. Please look at the screen shots as below.

First: You can see both of them from "programs and features", and the installation sequence is: x86-3.5 --> x64-3.5 --> x64-4.0. And I restarted computer after each installation.

Second: But I cannot find System.Data.SqlServerCe 4.0.0.0 version from "Reference Manager" of VS.

Third: This is my another machine which has the same environment, but 4.0 could be found.

I also compare their registry value regarding of SQL CE section, all are the same.

Appreciate if anyone could provide help on this.

答:
In order to add a reference to SQL CE 4.0, just browse to the 4.0 DLL, which is located in: </p>

```<code>C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop
</code>```

Title: SQL CE 4.0 in Reference Manager of VS

Body:
In order to add a reference to SQL CE 4.0, just browse to the 4.0 DLL, which is located in:

C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop


问:
Uneven data distribution on cassandra nodes
I had a cassandra cluster of 4 nodes in aws singapore region and I have to migrate it to mumbai region so I created a new datacenter in mumbai region added it to the singapore cluster and run rebuild command on all the new nodes one by one.
Data on previous nodes = 150GB/node approx.
Data on new nodes = 200GB/node on two node, 100GB on one node.

I am not able to figure out why this is happening it should be 200GB/node.
I am using cassandra 3.9 and using vnodes on new datacenter and single token on old datacenter.

I want to figure out what is the reason for this.

I tried to rebuild it finished in few seconds and RF is 3
nodetool status is showing all node UP and normal

答:
Try to rebuild last node once again, it can be due to unfinished rebuild process, and review the logs to see any errors.

Also, can you please provide output of nodetool status? And, what are replication factor in each dc?

EDIT:

1) Try to run repair on 100gb node.

2) Stop the problematic node, remove all the data from data folder and rebuild once again (it is possible that you will need to start the node with node replace options).


问:
How to use multiple components on a Vue route
I am just starting out with Vue and am trying to use two components in a route - a navbar and some sales data.  Laravel mix is bundling the assets with Webpack, and npm keeps failing.

index.php

```<code><body>
    <div id="app">
        <router-view name="nav"></router-view>
        <router-view></router-view>
    </div>
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</code>```

app.js:

```<code>import './bootstrap';
import router from './routes';
const app = new Vue({
    el: '#app',
    router
});
</code>```

routes.js:

```<code>import VueRouter    from 'vue-router';
import Sales        from './views/employer/sales/Sales.vue';
import MainNav      from './components/MainNav.vue';

let routes = [
    {
        path: '/sales',
        components: {
            default: Sales,
            nav: MainNav
        }
    }
];

export default new VueRouter({
    routes,
    linkActiveClass: 'is-active'
});
</code>```

Sales.vue

```<code><template>
    <p>This is the Sales view</p>
</template>
</code>```

MainNav.vue

```<code><template>
    <p>This is the MAIN NAVIGATION</p>
</template>
</code>```

The error message from npm is not particularly enlightening:

```<code>Failed at the @ dev script 'node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js
</code>```

It goes on to suggest that I should check I am running the latest node and npm (which I am).

What am I doing wrong?  Curiously, before attempting to include the navigation component this way, I was registering it as a global component.  It seemed to register fine, but whenever I included its element tag in a template, npm would fail in the same manner as above.

答: Looks like node somehow became confused.  I removed the node_modules directory and reinstalled it and its all good.</p>

Body:
I am just starting out with Vue and am trying to use two components in a route - a navbar and some sales data.  Laravel mix is bundling the assets with Webpack, and npm keeps failing.

index.php

        <router-view name="nav"></router-view>
        <router-view></router-view>

app.js:

import './bootstrap';
import router from './routes';
const app = new Vue({
    el: '#app',
    router
});

routes.js:

import VueRouter    from 'vue-router';
import Sales        from './views/employer/sales/Sales.vue';
import MainNav      from './components/MainNav.vue';

let routes = [
    {
        path: '/sales',
        components: {
            default: Sales,
            nav: MainNav
        }
    }
];

export default new VueRouter({
    routes,
    linkActiveClass: 'is-active'
});

Sales.vue

<template>

This is the Sales view

</template>

MainNav.vue

<template>

This is the MAIN NAVIGATION

</template>

The error message from npm is not particularly enlightening:

Failed at the @ dev script 'node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

It goes on to suggest that I should check I am running the latest node and npm (which I am).

What am I doing wrong?  Curiously, before attempting to include the navigation component this way, I was registering it as a global component.  It seemed to register fine, but whenever I included its element tag in a template, npm would fail in the same manner as above.


问:
print last '\n' char using print method in python
Imagine I have the following code in file test.py:

```<code>for x in range(1,11):
     print x
</code>```

This will print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:
</code>```

However, I want it to print:

```<code>$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:
</code>```

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

答:
Nothing is missing; if there wasn't a newline at the end the last line would look like 10$myuser:

Perhaps you want:

```<code>for x in range(1,11):
  print x
print
</code>```

Body:
Imagine I have the following code in file test.py:

for x in range(1,11):
     print x

This will print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10
$myuser:

However, I want it to print:

$myuser: python test.py
1
2
3
4
5
6
7
8
9
10

$myuser:

Notice the last '\n' char, that is missing in the normal case. How do I get this last newline char?

Body:
Nothing is missing; if there wasn't a newline at the end the last line would look like 10$myuser:

Perhaps you want:

for x in range(1,11):
  print x
print


问:
Find minimum value in multiple column range with criteria
How can I find the minimum value in columns B:C in the table below if the volume is <= 10.

The expected result is in yellow.

Regards,
Elio Fernandes

答:
Either:

=AGGREGATE(15,6,C2:C9/(A2:B9<=10),1)

or, array formula**:

=MIN(IF(A2:B9<=10,C2:C9))

If there may be blank cells in B2:C9:

=AGGREGATE(15,6,1/(1/C2:C9)/(A2:B9<=10),1)

or:

=MIN(IF(A2:B9<=10,IF(ISNUMBER(C2:C9),C2:C9)))

Regards


问:
Android Firebase Analytics not working correcty
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

```<code>public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}
</code>```

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data

答:
You can try this :</p>

```<code>  firebaseAnalytics = com.google.firebase.analytics.FirebaseAnalytics.getInstance(c);
    Bundle bundle = new Bundle();
    bundle.putString("homebtn_event",String.valueOf(btn_id));
    firebaseAnalytics.logEvent(com.google.firebase.analytics.FirebaseAnalytics.Event.LOGIN, bundle);
    firebaseAnalytics.setAnalyticsCollectionEnabled(true);
    Log.v("homebtn_event",String.valueOf(btn_id));
</code>```

Body:
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data

Body:
You can try this :

  firebaseAnalytics = com.google.firebase.analytics.FirebaseAnalytics.getInstance(c);
    Bundle bundle = new Bundle();
    bundle.putString("homebtn_event",String.valueOf(btn_id));
    firebaseAnalytics.logEvent(com.google.firebase.analytics.FirebaseAnalytics.Event.LOGIN, bundle);
    firebaseAnalytics.setAnalyticsCollectionEnabled(true);
    Log.v("homebtn_event",String.valueOf(btn_id));


问:
SQL sentence doesn't work with mybatis 3.3.2
I have to duplicate registers in a lot of tables, to do so i've created a simple mybatis configuration like:

```<code><insert id="copy" parameterType="hashmap" useGeneratedKeys="true" keyColumn="id">
  INSERT INTO ${table}
    <foreach item="key" collection="keys" index="index" open="(" separator="," close=")">
        ${key}
    </foreach>
    VALUES
    <foreach item="key" collection="map" index="index" open="(" separator="," close=")">
        ${key}
    </foreach>
</insert>
</code>```

So the approach is to select a row, change keys and some more elements in Java code and then insert it. But if fails with this trace:

```<code>org.springframework.dao.DuplicateKeyException:
### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException:  Invalid argument(s) in call
### SQL: INSERT INTO XYZ      (           ... )
### Cause: java.sql.SQLIntegrityConstraintViolationException: Invalid argument
; SQL []; Argumento(s) no válido(s) en la llamada; nested exception is java.sql.SQLIntegrityConstraintViolationException:  Invalid argument(s) in call
    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:241)
</code>```

But if i copy the SQL from the logs and execute it in SQLDeveloper, it works, how is that?

答: By using the ojdbc6dms_g.jar oracle driver instead of the regular ojdbc6.jar, i could debug with symbols and noticed it was searching for an 'id' column that i introduced with keyColumn="id", i removed it and worked since

Body:
I have to duplicate registers in a lot of tables, to do so i've created a simple mybatis configuration like:

<insert id="copy" parameterType="hashmap" useGeneratedKeys="true" keyColumn="id">
  INSERT INTO ${table}
    <foreach item="key" collection="keys" index="index" open="(" separator="," close=")">
        ${key}
    </foreach>
    VALUES
    <foreach item="key" collection="map" index="index" open="(" separator="," close=")">
        ${key}
    </foreach>
</insert>

So the approach is to select a row, change keys and some more elements in Java code and then insert it. But if fails with this trace:

org.springframework.dao.DuplicateKeyException:
### Error updating database.  Cause: java.sql.SQLIntegrityConstraintViolationException:  Invalid argument(s) in call
### SQL: INSERT INTO XYZ      (           ... )
### Cause: java.sql.SQLIntegrityConstraintViolationException: Invalid argument
; SQL []; Argumento(s) no válido(s) en la llamada; nested exception is java.sql.SQLIntegrityConstraintViolationException:  Invalid argument(s) in call
    at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:241)

But if i copy the SQL from the logs and execute it in SQLDeveloper, it works, how is that?


问:
Module instance methods and Module "regular" methods in Ruby
I'm trying to figure out the true difference between a module's instance methods and a module's "regular" methods.

To do that I fired up an irb and did the following:

```<code>>> Kernel.instance_methods
>> Kernel.methods
</code>```

I noticed that the output between these two is different.

For example, Kernel.methods includes a method :readline while Kernel.instance_methods does not.

Why and how is this happening?

Thanks.

答:
This might clarify things:

```<code>▶ module Test
▷   def im; end
▷   def mm; end
▷   module_function :mm
▷ end
▶ Test.methods(false) # false to not output inherited
#⇒ [
#    [0] mm() Test
# ]
▶ Test.instance_methods(false) # false to not output inherited
#⇒ [
#    [0] :im
# ]
▶ Test.im
#⇒ NoMethodError: undefined method `im' for Test:Module
#     from (pry):99:in `__pry__'
▶ Test.mm
#⇒ nil # fine, called
</code>```

Module methods might be called as is, as seen above. For instance methods, one needs an instance:

```<code>▶ "Hello world!".extend(Test).im
#⇒ nil # fine, called
</code>```

Body:
I'm trying to figure out the true difference between a module's instance methods and a module's "regular" methods.

To do that I fired up an irb and did the following:

>> Kernel.instance_methods
>> Kernel.methods

I noticed that the output between these two is different.

For example, Kernel.methods includes a method :readline while Kernel.instance_methods does not.

Why and how is this happening?

Thanks.

Body:
This might clarify things:

▶ module Test
▷   def im; end
▷   def mm; end
▷   module_function :mm
▷ end
▶ Test.methods(false) # false to not output inherited
#⇒ [
#    [0] mm() Test
# ]
▶ Test.instance_methods(false) # false to not output inherited
#⇒ [
#    [0] :im
# ]
▶ Test.im
#⇒ NoMethodError: undefined method `im' for Test:Module
#     from (pry):99:in `__pry__'
▶ Test.mm
#⇒ nil # fine, called

Module methods might be called as is, as seen above. For instance methods, one needs an instance:

▶ "Hello world!".extend(Test).im
#⇒ nil # fine, called


问:
Jquery - Finding closest matching span isn't working
I am trying to set a variable to match the text displayed inside the closest matching span. I've tried about 10 different ways, and when I alert it (to show what it's getting) it always either displays nothing or it says undefined.

Here is the html

```<code><div class="list-group-item">
<span class="list-group-item-heading commenter-name">Test Name</span><span class="pull-right"><a id="78564610">Reply</a> <span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
<p class="list-group-item-text">First comment on page.</p>
</div>
</code>```

Here is the relevant jQuery (minus the on document ready etc)

```<code>$("a").click(function() {

    var $test = $(this).closest('.commenter-name').text();

alert($test);
</code>```

I am trying to get $test to have the content of the span with the class 'commenter-name' - So $test should be set to "Test Name" in this case; but I always either get an empty response or undefined.

If I change it to something like this

```<code>var $test = $(this).closest('span').text();
</code>```

It shows everything inside the CURRENT span (it would show Reply Mar 29 2017, 00:59:57), but for whatever reason I can't refer to that other span with the name in it.

There are several sets of the above HTML, but I don't see why that should matter since I've been trying both closest, parents, parent, prev, and find.

答:
Use this. This is working.

$("a").click(function() {
 var $test = $(this).closest('.list-group-item')
              .find('.commenter-name').text();
 alert($test);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group-item">
<span class="list-group-item-heading commenter-name">Test Name</span>

<span class="pull-right">
<br />Reply<br />

<span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
<p class="list-group-item-text">First comment on page.</p>
</div></code>```

Body:
I am trying to set a variable to match the text displayed inside the closest matching span. I've tried about 10 different ways, and when I alert it (to show what it's getting) it always either displays nothing or it says undefined.

Here is the html

Test NameReply Mar 29 2017, 00:59:57

First comment on page.

Here is the relevant jQuery (minus the on document ready etc)

$("a").click(function() {

    var $test = $(this).closest('.commenter-name').text();

alert($test);

I am trying to get $test to have the content of the span with the class 'commenter-name' - So $test should be set to "Test Name" in this case; but I always either get an empty response or undefined.

If I change it to something like this

var $test = $(this).closest('span').text();

It shows everything inside the CURRENT span (it would show Reply Mar 29 2017, 00:59:57), but for whatever reason I can't refer to that other span with the name in it.

There are several sets of the above HTML, but I don't see why that should matter since I've been trying both closest, parents, parent, prev, and find.

Body:
Use this. This is working.

$("a").click(function() {
 var $test = $(this).closest('.list-group-item')
              .find('.commenter-name').text();
 alert($test);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list-group-item">
<span class="list-group-item-heading commenter-name">Test Name</span>

<span class="pull-right">
<br /><a id="78564610">Reply</a><br />

<span class="small text-muted">Mar 29 2017, 00:59:57</span></span>
<p class="list-group-item-text">First comment on page.</p>
</div>


问:
Check OS version in Swift?
I'm trying to check system information in Swift. I figured out, that it could be achieved by code:

```<code>var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)
</code>```

I have two problems with this code:

What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.

How can I read information from sysData?

答:
Update for Swift 3.0+</p>

```<code>func SYSTEM_VERSION_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedSame
}

func SYSTEM_VERSION_GREATER_THAN(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedDescending
}

func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}

func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedAscending
}

func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedDescending
}
</code>```

Title: Check OS version in Swift?

Body:
I'm trying to check system information in Swift. I figured out, that it could be achieved by code:

var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)

I have two problems with this code:

What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.

How can I read information from sysData?

Body:
Update for Swift 3.0+

func SYSTEM_VERSION_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedSame
}

func SYSTEM_VERSION_GREATER_THAN(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedDescending
}

func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}

func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) == ComparisonResult.orderedAscending
}

func SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(version: String) -> Bool {
    return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedDescending
}


问:
What is the best way to create a sparse array in C++?
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation.

In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array).

A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value.  Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries.

Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime.

I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?

答:
For C++, a map works well.  Several million objects won't be a problem.  10 million items took about 4.4 seconds and about 57 meg on my computer.

My test application is as follows:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <map>

class triple {
public:
    int x;
    int y;
    int z;
    bool operator<(const triple &other) const {
        if (x < other.x) return true;
        if (other.x < x) return false;
        if (y < other.y) return true;
        if (other.y < y) return false;
        return z < other.z;
    }
};

int main(int, char**)
{
    std::map<triple,int> data;
    triple point;
    int i;

    for (i = 0; i < 10000000; ++i) {
        point.x = rand();
        point.y = rand();
        point.z = rand();
        //printf("%d %d %d %d\n", i, point.x, point.y, point.z);
        data[point] = i;
    }
    return 0;
}
</code>```

Now to dynamically choose the number of variables, the easiest solution is to represent index as a string, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index  will look like "34,45,56". A simple implementation of this technique is as follows:

```<code>std::map data<string,int> data;
char ix[100];

sprintf(ix, "%d,%d", x, y); // 2 vars
data[ix] = i;

sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars
data[ix] = i;
</code>```

Body:
For C++, a map works well.  Several million objects won't be a problem.  10 million items took about 4.4 seconds and about 57 meg on my computer.

My test application is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <map>

class triple {
public:
    int x;
    int y;
    int z;
    bool operator<(const triple &other) const {
        if (x < other.x) return true;
        if (other.x < x) return false;
        if (y < other.y) return true;
        if (other.y < y) return false;
        return z < other.z;
    }
};

int main(int, char**)
{
    std::map<triple,int> data;
    triple point;
    int i;

    for (i = 0; i < 10000000; ++i) {
        point.x = rand();
        point.y = rand();
        point.z = rand();
        //printf("%d %d %d %d\n", i, point.x, point.y, point.z);
        data[point] = i;
    }
    return 0;
}

Now to dynamically choose the number of variables, the easiest solution is to represent index as a string, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index  will look like "34,45,56". A simple implementation of this technique is as follows:

std::map data<string,int> data;
char ix[100];

sprintf(ix, "%d,%d", x, y); // 2 vars
data[ix] = i;

sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars
data[ix] = i;

LastEditorDisplayName: Mark Harrison


问:
How do I get a distinct, ordered list of names from a DataTable using LINQ?
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

```<code>var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();
</code>```

Why does the orderby not get enforced?

答:
To make it more readable and maintainable, you can also split it up into multiple LINQ statements.

First, select your data into a new list, let's call it x1, do a projection if desired

Next, create a distinct list, from x1 into x2, using whatever distinction you require

Finally, create an ordered list, from x2 into x3, sorting by whatever you desire

Body:
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();

Why does the orderby not get enforced?

LastEditorDisplayName: Keith

OwnerDisplayName: AndrewDotHay


问:
Reloading TableView on iPhone from another class
So I have a FirstViewController, which is a UITableViewController, as well as delegate and dataSource. It has the table view.

I have another class, FeedParser, that parses the data - but after it's done parsing, I need it to go and refresh the UITableView or else it won't show anything.

This is probably a stupid question, so forgive me, but how should I go about calling FirstViewController's tableView.reloadData from FeedParser?

Is there a method to return that view?

Thanks!

答:
Register the view controller to receive notifications that the data has been changed, and have it refresh the table when it receives one. Then have the parser send it out.

Registering for it is easy:

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(yourRefreshMethodHere:)
                                             name:@"YourNotificationName"
                                           object:nil];
</code>```

Your refresh method needs to be set up to receive these notifications, along these lines:

```<code>- (void)reloadTable:(NSNotification *)notif {
    [self.yourTableName reloadData];
}
</code>```

And it's important to stop observing in your ViewDidUnload:

```<code>[[NSNotificationCenter defaultCenter] removeObserver:self];
</code>```

Then in the parser you need to simply add this when it's complete:

```<code>[[NSNotificationCenter defaultCenter] postNotificationName:@"YourNotificationName"
                                                    object:nil];
</code>```

The view controller (and anyone else observing the notification with that name) will get the message and perform its task.

Body:
Register the view controller to receive notifications that the data has been changed, and have it refresh the table when it receives one. Then have the parser send it out.

Registering for it is easy:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(yourRefreshMethodHere:)
                                             name:@"YourNotificationName"
                                           object:nil];

Your refresh method needs to be set up to receive these notifications, along these lines:

- (void)reloadTable:(NSNotification *)notif {
    [self.yourTableName reloadData];
}

And it's important to stop observing in your ViewDidUnload:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Then in the parser you need to simply add this when it's complete:

[[NSNotificationCenter defaultCenter] postNotificationName:@"YourNotificationName"
                                                    object:nil];

The view controller (and anyone else observing the notification with that name) will get the message and perform its task.


问:
Thread.sleep() pauses JFrame before other statements
Thread.sleep() always pauses JFrame before the sleep() statement even gets executed.
I have the following method to pause the thread:

```<code>private void sleep(int milli)   {
    try {
        Thread.sleep(milli);
    }   catch   (InterruptedException ex)   {
        writeToConsoleError("Interrupted");
    }
}
</code>```

I'm calling it in the following switch-case statement under case CARDNOMATCH:, this method is in a class which extends JFrame.

```<code>public void handlePacket(Packet recieved)   {
    int cmd = recieved.getCommand();
    int arg1 = -99;
    int arg2 = -99;
    switch (cmd)    {
        case CARDNOMATCH:
            arg1 = recieved.getFirstArg();
            arg2 = recieved.getSecondArg();
            if(arg1 > 9)    {
                arg1 = 9;
            }
            if(arg2 > 9)    {
                arg2 = 9;
            }
            flipCard(choice1, arg1);
            flipCard(choice2, arg2);
            sleep(3000);
            flipCard(choice1, 10);
            flipCard(choice2, 10);
            break;
        case ENABLE_TURN:
            this.isTurn = true;
            break;
        case DISABLE_TURN:
            this.isTurn = false;
            break;
    }
}
</code>```

Please, anyone, give me some insight :(

答:
UI is not updated instantaneously.

When you call

```<code>flipCard(choice1, arg1);
flipCard(choice2, arg2);
</code>```

I assume flipCard updates the UI in some way. And your expected behaviour is that choice1 and choice2 cards will be flipped, wait 3 seconds, and flip them again. But the actual behaviour you get is that nothing happens until 3 seconds have passed, after 3 seconds, the cards flipped twice.

What you need to understand is that UI has a frame rate. When you call flipCard, the card will not be flipped until the next frame. During the time between this frame and the next, Thread.sleep is called so everything, including the frames, pause for 3 seconds. That's why the UI updated after 3 seconds' pause.

I suggest you to use javax.swing.Timer or javax.swing.SwingWorker. See here or here for more info.

Body:
Thread.sleep() always pauses JFrame before the sleep() statement even gets executed.
I have the following method to pause the thread:

private void sleep(int milli)   {
    try {
        Thread.sleep(milli);
    }   catch   (InterruptedException ex)   {
        writeToConsoleError("Interrupted");
    }
}

I'm calling it in the following switch-case statement under case CARDNOMATCH:, this method is in a class which extends JFrame.

public void handlePacket(Packet recieved)   {
    int cmd = recieved.getCommand();
    int arg1 = -99;
    int arg2 = -99;
    switch (cmd)    {
        case CARDNOMATCH:
            arg1 = recieved.getFirstArg();
            arg2 = recieved.getSecondArg();
            if(arg1 > 9)    {
                arg1 = 9;
            }
            if(arg2 > 9)    {
                arg2 = 9;
            }
            flipCard(choice1, arg1);
            flipCard(choice2, arg2);
            sleep(3000);
            flipCard(choice1, 10);
            flipCard(choice2, 10);
            break;
        case ENABLE_TURN:
            this.isTurn = true;
            break;
        case DISABLE_TURN:
            this.isTurn = false;
            break;
    }
}

Please, anyone, give me some insight :(

Body:
UI is not updated instantaneously.

When you call

flipCard(choice1, arg1);
flipCard(choice2, arg2);

I assume flipCard updates the UI in some way. And your expected behaviour is that choice1 and choice2 cards will be flipped, wait 3 seconds, and flip them again. But the actual behaviour you get is that nothing happens until 3 seconds have passed, after 3 seconds, the cards flipped twice.

What you need to understand is that UI has a frame rate. When you call flipCard, the card will not be flipped until the next frame. During the time between this frame and the next, Thread.sleep is called so everything, including the frames, pause for 3 seconds. That's why the UI updated after 3 seconds' pause.

I suggest you to use javax.swing.Timer or javax.swing.SwingWorker. See here or here for more info.


问:
how to set variable as table name in create query
im trying to create a table in mysql using jsp application. I need to set a variable in the place of tablename in the create query how to do so?</p>

```<code>String name="tablename";
Class.forName("com.mysql.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "root");

String strQuery="create table "+name+"(cname varchar(25);";
Statement st=con1.createStatement();
st.executeUpdate(strQuery);
</code>```

答:
There is an sql syntax error in your code due to which it is failing while creating the table.

You have missed a closing parenthesis at the end of the create table query. It should be as below -

String strQuery="create table "+name+"(cname varchar(25));";

Your code works fine with this change, with my assumption that the database is already created.

Body:
im trying to create a table in mysql using jsp application. I need to set a variable in the place of tablename in the create query how to do so?

String name="tablename";
Class.forName("com.mysql.jdbc.Driver");
Connection con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "root");

String strQuery="create table "+name+"(cname varchar(25);";
Statement st=con1.createStatement();
st.executeUpdate(strQuery);


问:
How to validate the grid table value in protractor?
In protractor, I want to verify whether added value is displaying in the grid.
How do I validate it?

The grid looks like this:

答:
Let me assume you have created a new row with below details,

```<code>var newRow = {
  "obligation_name" : "sudharsan",
  "status" : "",
  "module" : "Test Module"
}
</code>```

If you want to verify that the newly entered row is displayed,You can try the below code,

```<code>var rowList = element.all(by.repeater("(colRenderIndex, col) in colContainer.renderedColumns"));
var expectedRow = rowList.filter(function(rowElement,index) {
  var columnList = rowElement.all(by.css("div.ui-grid-cell-contents"));
  return columnList.getText().then(function(columnValues) {
    return (columnValues[0]== newRow["obligation_name"]) && (columnValues[1] == newRow["status"]) && (columnValues[2] == newRow["module"]);
  });
});
expect(expectedRow.count()).toBeGreaterThan(0);
</code>```

Body:
Let me assume you have created a new row with below details,

var newRow = {
  "obligation_name" : "sudharsan",
  "status" : "",
  "module" : "Test Module"
}

If you want to verify that the newly entered row is displayed,You can try the below code,

var rowList = element.all(by.repeater("(colRenderIndex, col) in colContainer.renderedColumns"));
var expectedRow = rowList.filter(function(rowElement,index) {
  var columnList = rowElement.all(by.css("div.ui-grid-cell-contents"));
  return columnList.getText().then(function(columnValues) {
    return (columnValues[0]== newRow["obligation_name"]) && (columnValues[1] == newRow["status"]) && (columnValues[2] == newRow["module"]);
  });
});
expect(expectedRow.count()).toBeGreaterThan(0);


问:
I cannot login to wordpress dashboard locally even after changing database or config file. It just does not accept anything
I had wordpress project files with me. I installed WAMP and copied the wordpress project files to the www folder.

I modified the wp-config file with the database file name, username and password. Now, I try to access http://localhost/my_wp_folder/, it does not ask me to enter wordpress details. Instead it takes me directly to my site first page.
I try http://localhost/my_wp_folder/wp-login.php, comes up with a login page. I entered username and password from wp_users table, and it refuses to connect.

What am I doing wrong?

答: try deleting the data base and recreating it, that will required wordpress to create the required tables, probably by doing that you will be asked for user and password. </p>


问:
How to get HTML code as String from a HTML file in java?
I need to get HTML code as String from an existing HTML file? How can I do that in Java?

I tried the following, but the result was something that is not html syntax.

```<code>        File htmlFile = new File(filePath);
        StringBuilder contentBuilder = new StringBuilder();
        String str;
        try {
            BufferedReader in = new BufferedReader(new FileReader(htmlFile));
            while ((str = in.readLine()) != null) {
                contentBuilder.append(str);
            }
            in.close();
        } catch (IOException e) {
        }
        String htmlCodeAsString = contentBuilder.toString();
</code>```

答:
You can also use a Scanner:

```<code>Scanner scanner = new Scanner(new File("test.html"));
String text = scanner.useDelimiter("\\A").next();
scanner.close();
</code>```

The regex \A marks the beginning of the input. Scanner uses a buffer which default size is 1024, but will be increased by the Scanner when needed.

Body:
I need to get HTML code as String from an existing HTML file? How can I do that in Java?

I tried the following, but the result was something that is not html syntax.

        File htmlFile = new File(filePath);
        StringBuilder contentBuilder = new StringBuilder();
        String str;
        try {
            BufferedReader in = new BufferedReader(new FileReader(htmlFile));
            while ((str = in.readLine()) != null) {
                contentBuilder.append(str);
            }
            in.close();
        } catch (IOException e) {
        }
        String htmlCodeAsString = contentBuilder.toString();

Body:
You can also use a Scanner:

Scanner scanner = new Scanner(new File("test.html"));
String text = scanner.useDelimiter("\\A").next();
scanner.close();

The regex \A marks the beginning of the input. Scanner uses a buffer which default size is 1024, but will be increased by the Scanner when needed.


问:
Php magento SESSION variables getting unset before executing javascript code inside php
I am trying to show pop-up using jQuery inside php code.

setting value to session variable $SESSION['prod_id']="123"

When user is not logged in I am setting some value to session_variable i.e.  and as User get logged in I want to call javascript(inside php code) if value is set for this variable then show pop-up to user and unset the variable from session.

```<code>if(Mage::getSingleton('customer/session')->isLoggedIn()){
    if (isset($_SESSION['prod_id'])) {
         Mage::helper('company/product')->addDatabase($_SESSION['prod_id']);
         $productName = $session->getData('product_session');
         if (!empty($productName)){
             echo "<script type='text/javascript'>
             jQuery(document).ready(function(){
              jQuery('.show-toast').removeAttr('style').css('display','block');
                });
            });
                    </script>";
         $session->unsetData('product_session');
         unset($_SESSION['prod_id']);
     }
  }
}
</code>```

But the problem is that before executing javascript code session variable is getting unset.But if I comment out unset session line then it works fine.

答:
As after huge struggle I noticed that Magento session was on server side,and it was resets before JavaScript code get called. We need something like callback function to reset session.
I have written One function inside JavaScript unsetSessionVar() that will call an api of server side and will reset session for unset($_SESSION['prod_id']); and working perfect

```<code>if(Mage::getSingleton('customer/session')->isLoggedIn()){
if (isset($_SESSION['prod_id'])) {
     Mage::helper('company/product')->addDatabase($_SESSION['prod_id']);
     $productName = $session->getData('product_session');
     if (!empty($productName)){
         echo "<script type='text/javascript'>
          jQuery(document).ready(function(){
            jQuery('.show-toast').removeAttr('style').css('display','block');
            unsetSessionVar();
          });
        </script>";
     }
  }
}

<script type="text/javascript">
  function unsetSessionVar(){
    jQuery.ajax({
         url: 'company.com/api/sessionaction/unsetses/',
    }).done(function() {});
  }
</script>
</code>```

Body:
I am trying to show pop-up using jQuery inside php code.

setting value to session variable $SESSION['prod_id']="123"

When user is not logged in I am setting some value to session_variable i.e.  and as User get logged in I want to call javascript(inside php code) if value is set for this variable then show pop-up to user and unset the variable from session.

if(Mage::getSingleton('customer/session')->isLoggedIn()){
    if (isset($_SESSION['prod_id'])) {
         Mage::helper('company/product')->addDatabase($_SESSION['prod_id']);
         $productName = $session->getData('product_session');
         if (!empty($productName)){
             echo "";
         $session->unsetData('product_session');
         unset($_SESSION['prod_id']);
     }
  }
}

But the problem is that before executing javascript code session variable is getting unset.But if I comment out unset session line then it works fine.

Body:
As after huge struggle I noticed that Magento session was on server side,and it was resets before JavaScript code get called. We need something like callback function to reset session.
I have written One function inside JavaScript unsetSessionVar() that will call an api of server side and will reset session for unset($_SESSION['prod_id']); and working perfect

if(Mage::getSingleton('customer/session')->isLoggedIn()){
if (isset($_SESSION['prod_id'])) {
     Mage::helper('company/product')->addDatabase($_SESSION['prod_id']);
     $productName = $session->getData('product_session');
     if (!empty($productName)){
         echo "<script type='text/javascript'>
          jQuery(document).ready(function(){
            jQuery('.show-toast').removeAttr('style').css('display','block');
            unsetSessionVar();
          });
        </script>";
     }
  }
}

<script type="text/javascript">
  function unsetSessionVar(){
    jQuery.ajax({
         url: 'company.com/api/sessionaction/unsetses/',
    }).done(function() {});
  }
</script>


问:
Create groupings using GroupBY
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

```<code>class A {
   string X {get; set;}
}

var list = listOfAs;
List<A> listOfAWithXEqualAA;
List<A> listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.
</code>```

Please suggest me such a query.

答:
With LINQ you can create only one IEnumerable using Select, Where etc..
Why just use foreach with simple if:</p>

```<code>        foreach (var item in list)
        {
            if (item.X  == "AA")
            {
                listOfAWithXEqualAA.Add(item);
            }
            else
            {
                listOfAWithXNotEqualAA.Add(item);
            }
        }
</code>```

Title: Create groupings using GroupBY

Body:
I have a list of objects. I want to split this list into a list of objects based on specific property. Any object whose that specific property's value is some value should end up in one list and the rest in the other. I want to use one LINQ query that can achieve that.

Some pseudo code below:

class A {
   string X {get; set;}
}

var list = listOfAs;
List listOfAWithXEqualAA;
List listOfAWithXNotEqualAA;

var query = one LINQ query to populate above declared lists.

Please suggest me such a query.

Body:
With LINQ you can create only one IEnumerable using Select, Where etc..
Why just use foreach with simple if:

        foreach (var item in list)
        {
            if (item.X  == "AA")
            {
                listOfAWithXEqualAA.Add(item);
            }
            else
            {
                listOfAWithXNotEqualAA.Add(item);
            }
        }


问:
clear value in Partial view(Multiple)
I have one patialview which is user two time

Parialview:

```<code><divclass="row Address2">
    <divclass="col-sm-4">
        <divclass="md-form">
                @Html.DropDownListFor(m=>m.StateId,Model.States,"--SelectState--",new{@id="addressState",@class="posT mdb-select",@autocomplete="off"})
        </div>
    </div>
    <divclass="col-sm-4">
        <divclass="md-form">
            <divclass="loader-div">
                @Html.TextBoxFor(m=>m.City,new{@id="addressCity",@autocomplete="off",@class="form-control Clr"})
            </div>
        </div>
    </div>
    <divclass="col-sm-4">
        <divclass="md-form">
            <divclass="loader-div">
                @Html.TextBoxFor(m=>m.Zipcode,new{@id="addressZipcode",@autocomplete="off",@class="form-control Clr",})
            </div>
        </div>
    </div>
</div>
</code>```

Now I want to Delete State and zipcode base on state dropdown change.

Suppose i select above dropdown then its should delete above or current div state and zipcode
if i select below dropdown than below state and zipcode should be delete.

But in my case when i select below dropdown that time its always clear above.
My java script as bellow.

```<code>$(".mdb-select").change(function(){
if($(this).closest('.Address2').find('#addressState').val()==''){

$(this).closest('.Address2').find('#addressCity').val("");
$(this).closest('.Address2').find('#addressZipcode').val("");

//$(this).parents('.Address2').find('#addressCity').val("");
//$(this).parents('.Address2').find('#addressZipcode').val("");
}
}
})
</code>```

and i have bind partialview like this

```<code>@Html.Partial("_AddressPartial", feedback.AddressProperty, new ViewDataDictionary() { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "AddressProperty" } })

 and

 @Html.Partial("_AddressPartial", feedback.EscrowProperty, new ViewDataDictionary() { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "EscrowProperty" } })
</code>```

and also try to remove by below JQ
 $(this).closest('.Address2').find('.Clr').val("");

but Result is same.

答:
Your use of HtmlFieldPrefix correctly generates unique id attributes but your use of new { @id=".." } is overriding that and generating duplicate id attributes which is invalid html, and your jquery selectors will only ever select the first one.

Change it to use class names and relative selectors instead

```<code>@Html.DropDownListFor(m => m.StateId, Model.States,"--SelectState--", new { @class="posT mdb-select", @autocomplete="off"})
@Html.TextBoxFor(m => m.City, new { @class="city form-control Clr", @autocomplete="off",})
@Html.TextBoxFor( m=> m.Zipcode, new {@class="zipcode form-control Clr", @autocomplete="off" })
</code>```

Then the scripts becomes

```<code>$('.mdb-select').change(function() {
    var state = $(this).val();
    var container = $(this).closest('.Address2');
    container.find('.city').val('');
    container.find('.zipcode').val('');
});
</code>```

As a side note, it easier to use an EditorTemplate to generate the controls. Assuming your class is Address.cs, then rename your partial to /Views/Shared/EditorTemplates/Address.cshtml (ie to match the class name), and then in the main view it becomes

```<code>@Html.EditorFor(m => m.AddressProperty)
@Html.EditorFor(m => m.EscrowProperty)
</code>```

Title: clear value in Partial view(Multiple)

Body:
I have one patialview which is user two time

Parialview:

<divclass="row Address2">
    <divclass="col-sm-4">
        <divclass="md-form">
                @Html.DropDownListFor(m=>m.StateId,Model.States,"--SelectState--",new{@id="addressState",@class="posT mdb-select",@autocomplete="off"})

    <divclass="col-sm-4">
        <divclass="md-form">
            <divclass="loader-div">
                @Html.TextBoxFor(m=>m.City,new{@id="addressCity",@autocomplete="off",@class="form-control Clr"})

    <divclass="col-sm-4">
        <divclass="md-form">
            <divclass="loader-div">
                @Html.TextBoxFor(m=>m.Zipcode,new{@id="addressZipcode",@autocomplete="off",@class="form-control Clr",})

Now I want to Delete State and zipcode base on state dropdown change.

Suppose i select above dropdown then its should delete above or current div state and zipcode
if i select below dropdown than below state and zipcode should be delete.

But in my case when i select below dropdown that time its always clear above.
My java script as bellow.

$(".mdb-select").change(function(){
if($(this).closest('.Address2').find('#addressState').val()==''){

$(this).closest('.Address2').find('#addressCity').val("");
$(this).closest('.Address2').find('#addressZipcode').val("");

//$(this).parents('.Address2').find('#addressCity').val("");
//$(this).parents('.Address2').find('#addressZipcode').val("");
}
}
})

and i have bind partialview like this

@Html.Partial("_AddressPartial", feedback.AddressProperty, new ViewDataDictionary() { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "AddressProperty" } })

 and

 @Html.Partial("_AddressPartial", feedback.EscrowProperty, new ViewDataDictionary() { TemplateInfo = new TemplateInfo() { HtmlFieldPrefix = "EscrowProperty" } })

and also try to remove by below JQ
 $(this).closest('.Address2').find('.Clr').val("");

but Result is same.

Body:
Your use of HtmlFieldPrefix correctly generates unique id attributes but your use of new { @id=".." } is overriding that and generating duplicate id attributes which is invalid html, and your jquery selectors will only ever select the first one.

Change it to use class names and relative selectors instead

@Html.DropDownListFor(m => m.StateId, Model.States,"--SelectState--", new { @class="posT mdb-select", @autocomplete="off"})
@Html.TextBoxFor(m => m.City, new { @class="city form-control Clr", @autocomplete="off",})
@Html.TextBoxFor( m=> m.Zipcode, new {@class="zipcode form-control Clr", @autocomplete="off" })

Then the scripts becomes

$('.mdb-select').change(function() {
    var state = $(this).val();
    var container = $(this).closest('.Address2');
    container.find('.city').val('');
    container.find('.zipcode').val('');
});

As a side note, it easier to use an EditorTemplate to generate the controls. Assuming your class is Address.cs, then rename your partial to /Views/Shared/EditorTemplates/Address.cshtml (ie to match the class name), and then in the main view it becomes

@Html.EditorFor(m => m.AddressProperty)
@Html.EditorFor(m => m.EscrowProperty)


问:
More than one value for the key user.name Git
For some reason I'm getting the error that "More than one value for the key user.name" when I try to set the user.name for my git account.  How can I set it to a single name?</p>

答:
You should examine the contents of ~/.gitconfig (your user-global config) as well as .git/config in the repository in question (the repo-specific config). You should see two name lines under a user section in one of them. (It could also be two separate user sections in one file.) Just delete the one you don't want, and you should be good to go.

You could also directly set it with git config --global user.name "Desired name" if you want it to be a global setting (probably the case), or the same minus the --global for a repo-specific setting - but it's probably best to inspect the files and find the culprit yourself, to make sure you know what you have. The repo-specific one will override the global one. Ideally you should set your name globally, and only override it in a project for a good reason.


问:
Google Analytics for iOS - minimum deployment target?
I'm trying to install Google Analytics for iOS using cocoapods, and see this error:

[!] Unable to satisfy the following requirements:

'Google/Analytics' required by 'Podfile'

Specs satisfying the 'Google/Analytics' dependency were found, but they required a higher minimum deployment target.

So, how can I get minimum deployment target for analytics? Documentation gives no clue. My app should support iOS 6.0, btw.

答:
It is described here: cocoapods spec

```<code>"platforms": {
"ios": "5.0"
</code>```

},

So right now the support is iOS 5 and up.

Body:
It is described here: cocoapods spec

"platforms": {
"ios": "5.0"

},

So right now the support is iOS 5 and up.


问:
Changing the attribute of each element in a v-for array
I am attempting to figure things out with Vue way of writing javascript.

Considering this scenario:

at .vue template

```<code> <button  v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button>

   <div v-for="(tweet, index) in tweets">
      <div class="each_tweet">
        <textarea v-on:keyup="typing(index)"
                  v-model="tweet.content"
                  placeholder="What's happening now">{{ tweet.content }}</textarea>
      </div>
    </div>
</code>```

at .vue

答:
document.getElementsByClassName method returns a nodeList so you have to access a DOM element using its index.

```<code>export default {
  methods: {
     biggerFont:  function() {
          var tweets=document.getElementsByClassName("each_tweet");
          for(var i=0;i<tweets.length;i++){
              tweets[i].style.fontSize = "xx-large";
          }
     }
  }
}
</code>```

Body:
I am attempting to figure things out with Vue way of writing javascript.

Considering this scenario:

at .vue template

 <button  v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button>

        <textarea v-on:keyup="typing(index)"
                  v-model="tweet.content"
                  placeholder="What's happening now">{{ tweet.content }}</textarea>

at .vue

Body:
document.getElementsByClassName method returns a nodeList so you have to access a DOM element using its index.

export default {
  methods: {
     biggerFont:  function() {
          var tweets=document.getElementsByClassName("each_tweet");
          for(var i=0;i<tweets.length;i++){
              tweets[i].style.fontSize = "xx-large";
          }
     }
  }
}


问:
Show Enlarged Image over other Images in a ListBox during MouseOver
I'm trying to create a photo gallery of sorts and i've managed to get images displayed in a nice looking grid but i'm struggling with a specific trigger that transforms the thumbnail and (is supposed to) show the transformed thumbnail over the other images.

Through research i found that changing the ZIndex to a high number should allow the transformed thumbnail to appear over other thumbnails but the transformed thumbnail is still showing under other images.

Code

```<code><Grid>
    <ListBox ItemsSource="{Binding Images, Mode=OneWay}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <TextBlock Panel.ZIndex="1000" Grid.Row="1" Text="{Binding Label}" Foreground="White" Width="100" Height="20" TextTrimming="CharacterEllipsis" VerticalAlignment="Center">
                        <TextBlock.Background>
                            <SolidColorBrush Opacity="0.50" Color="Black"/>
                        </TextBlock.Background>
                    </TextBlock>
                    <Border Grid.Row="0" Grid.RowSpan="2" BorderThickness="1" Margin="1" x:Name="border" MouseDown="OnImageViewBorderMouseDown">
                        <Image Source="{Binding Thumbnail, Mode=OneWay}" Height="100" Width="100" />
                        <Border.Style>
                            <Style TargetType="Border">
                                <Setter Property="BorderBrush" Value="Black" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding ElementName=border, Path=IsMouseOver}" Value="True">
                                        <Setter Property="BorderBrush" Value="{DynamicResource AccentColorBrush}"/>
                                        <Setter Property="Grid.ZIndex" Value="1000"/>
                                        <Setter Property="Panel.ZIndex" Value="1000"/>
                                        <Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
                                        <Setter Property="RenderTransform">
                                            <Setter.Value>
                                                <ScaleTransform ScaleX="1.20" ScaleY="1.20"/>
                                            </Setter.Value>
                                        </Setter>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                    </Border>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</Grid>
</code>```

Image of Problem

答:
Sample ListBox Style copied from the C.B.R. : Comic Book Reader project on CodePlex, from file CBR/Resources/XAML/System/ListBox.xaml
</p>

```<code><Style x:Key="CbrStandardListBox" TargetType="{x:Type ListBox}">
    <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"/>
    <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Standard"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="True">
                    <ScrollViewer Style="{DynamicResource CbrScrollViewer}" Focusable="False" Padding="{TemplateBinding Padding}">
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.InactiveCaptionTextBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="IsGrouping" Value="True">
                        <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Resources>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="Background" Value="{DynamicResource CbrBackgroundNormal}"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Grid Margin="4,0,4,4">
                            <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="1" SnapsToDevicePixels="True"/>
                            <ContentPresenter Margin="8,5"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="IsSelected" Value="False"/>
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="{DynamicResource CbrBackgroundHighlighted}" />
                                <Setter Property="BorderBrush" Value="{DynamicResource CbrBorderBrushHighlighted}" />
                            </MultiTrigger>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" Value="{DynamicResource CbrBackgroundSelected}" />
                                <Setter Property="BorderBrush" Value="{DynamicResource CbrBorderBrushSelected}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Style.Resources>
</Style>
</code>```

Body:
I'm trying to create a photo gallery of sorts and i've managed to get images displayed in a nice looking grid but i'm struggling with a specific trigger that transforms the thumbnail and (is supposed to) show the transformed thumbnail over the other images.

Through research i found that changing the ZIndex to a high number should allow the transformed thumbnail to appear over other thumbnails but the transformed thumbnail is still showing under other images.

Code

<Grid>
    <ListBox ItemsSource="{Binding Images, Mode=OneWay}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <TextBlock Panel.ZIndex="1000" Grid.Row="1" Text="{Binding Label}" Foreground="White" Width="100" Height="20" TextTrimming="CharacterEllipsis" VerticalAlignment="Center">
                        <TextBlock.Background>
                            <SolidColorBrush Opacity="0.50" Color="Black"/>
                        </TextBlock.Background>
                    </TextBlock>
                    <Border Grid.Row="0" Grid.RowSpan="2" BorderThickness="1" Margin="1" x:Name="border" MouseDown="OnImageViewBorderMouseDown">
                        <Image Source="{Binding Thumbnail, Mode=OneWay}" Height="100" Width="100" />
                        <Border.Style>

                            </Style>
                        </Border.Style>
                    </Border>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" IsItemsHost="True"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
    </ListBox>
</Grid>

Image of Problem

Body:
Sample ListBox Style copied from the C.B.R. : Comic Book Reader project on CodePlex, from file CBR/Resources/XAML/System/ListBox.xaml

<Style x:Key="CbrStandardListBox" TargetType="{x:Type ListBox}">
    <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"/>
    <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Standard"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBox}">
                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="True">
                    <ScrollViewer Style="{DynamicResource CbrScrollViewer}" Focusable="False" Padding="{TemplateBinding Padding}">
                        <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </ScrollViewer>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.InactiveCaptionTextBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="IsGrouping" Value="True">
                        <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Resources>
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
            <Setter Property="Background" Value="{DynamicResource CbrBackgroundNormal}"/>
            <Setter Property="BorderBrush" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Grid Margin="4,0,4,4">
                            <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
                                    BorderThickness="1" SnapsToDevicePixels="True"/>
                            <ContentPresenter Margin="8,5"/>
                        </Grid>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="IsSelected" Value="False"/>
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value="{DynamicResource CbrBackgroundHighlighted}" />
                                <Setter Property="BorderBrush" Value="{DynamicResource CbrBorderBrushHighlighted}" />
                            </MultiTrigger>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" Value="{DynamicResource CbrBackgroundSelected}" />
                                <Setter Property="BorderBrush" Value="{DynamicResource CbrBorderBrushSelected}" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Style.Resources>
</Style>


问:
Express js :separate controller and router file returns 404 error on route
I would like seprate all of my routes from the app.js file into a seprat
 route file which will loads the controllers from the controller directory.

Here is my folder structure

```<code><project folder>
   controllers
         testController.js
   routes
        route.js
app.js
</code>```

Here is my testController.js

```<code>module.exports = {
    getMovie : function(req, res){
        //do something
        res.send('respond with test resource');
    },
    postMovie : function(req, res){
        //do something
    }
}
</code>```

route.js under route directory.

```<code>var express = require('express');
//load the contrller
var test = require('../controllers/testController.js');
var router = express.Router();

router.route('/hello').get(test.getMovie);

module.exports = router;
</code>```

when i access my route localhost:3000/hello i got 404 error.

I just tried the solutions from this question  separate file for routes in express

app.js

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes');

var app = express();
app.use('api',routes);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
</code>```

答:
Please Update

```<code>var routes = require('./route')
</code>```

to

```<code>var routes = require('./routes/route');
</code>```

Body:
I would like seprate all of my routes from the app.js file into a seprat
 route file which will loads the controllers from the controller directory.

Here is my folder structure

<project folder>
   controllers
         testController.js
   routes
        route.js
app.js

Here is my testController.js

module.exports = {
    getMovie : function(req, res){
        //do something
        res.send('respond with test resource');
    },
    postMovie : function(req, res){
        //do something
    }
}

route.js under route directory.

var express = require('express');
//load the contrller
var test = require('../controllers/testController.js');
var router = express.Router();

router.route('/hello').get(test.getMovie);

module.exports = router;

when i access my route localhost:3000/hello i got 404 error.

I just tried the solutions from this question  separate file for routes in express

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes');

var app = express();
app.use('api',routes);

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

Body:
Please Update

var routes = require('./route')

to

var routes = require('./routes/route');


问:
Linking thumbnails to video files, and adding a title
Long shot here but...

I have 200 thumbnails, and 50 videos. That's 4 thumbnails per video that I can choose from, but I only need to link 1 thumbnail to the appropriate video.

So I have
video1thumb1, video1thumb2.jpg, video1thumb3.jpg, video1thumb4.jpg  ---- video1.avi
video2thumb1, video2thumb2.jpg, video2thumb3.jpg, video2thumb4.jpg  ---- video2.avi
video3thumb1, video3thumb2.jpg, video3thumb3.jpg, video3thumb4.jpg  ---- video3.avi
... and so on... Images are in the /Image folder, and videos are in the /videos folder.

Now... Is there a script/program/code out there that will allow me to choose the best image or each video AND add a title to each video?

答:
You can break down your problem into separate parts:

Pick the best thumbnail out of 3.

Add title to each video.

For the first part, you can easily get this done using bash (if you're on Linux) and imagemagick (cross-platform imaging library).

For each video, you would want to do something like this (I sense a for loop):

```<code>filename=videoX.avi

#
# Strip the file extension.
#
vname="${filename%.*}"
#
# Show the three thumbnails side by side.
#
montage $vname-thumb1.jpg $vname-thumb2.jpg $vname-thumb3.jpg -adjoin - | display
#
# Get the user to select the best thumbnail.
#
echo "Which thumbnail do you prefer: 1, 2 or 3?"
read -n 1 -s reply
if [ "$reply" = "1" ] || [ "$reply" = "2" ] || [ "$reply" = "3" ]
then
    cp $vname-thumb$reply.jpg $vname-selected.jpg
else
    echo "Invalid response: $reply"
fi
</code>```

Body:
You can break down your problem into separate parts:

Pick the best thumbnail out of 3.

Add title to each video.

For the first part, you can easily get this done using bash (if you're on Linux) and imagemagick (cross-platform imaging library).

For each video, you would want to do something like this (I sense a for loop):

filename=videoX.avi

#
# Strip the file extension.
#
vname="${filename%.*}"
#
# Show the three thumbnails side by side.
#
montage $vname-thumb1.jpg $vname-thumb2.jpg $vname-thumb3.jpg -adjoin - | display
#
# Get the user to select the best thumbnail.
#
echo "Which thumbnail do you prefer: 1, 2 or 3?"
read -n 1 -s reply
if [ "$reply" = "1" ] || [ "$reply" = "2" ] || [ "$reply" = "3" ]
then
    cp $vname-thumb$reply.jpg $vname-selected.jpg
else
    echo "Invalid response: $reply"
fi