问:
JUPYTER_PATH in environment variables not working
I am trying to update JUPYTER_PATH for Jupyter notebook. I set the environment variables following the jupyter documentation but still jupyter contrib nbextension install --user, for example, installed under C:\Users\username\AppData\nbextensions instead of C:\somedir\AppData\Roaming\jupyter\nbextensions.

Added these to my environment variables.

```<code>JUPYTER_CONFIG_DIR=C:\somedir\.jupyter
JUPYTER_PATH=C:\somedir\AppData\Roaming\jupyter
JUPYTER_RUNTIME_DIR=C:\somedir\AppData\Roaming\jupyter
</code>```

jupyter --path shows

```<code>PS C:\somedir\> jupyter --path
config:
    C:\somedir\.jupyter
    C:\anaconda\python27\win64\431\etc\jupyter
    C:\ProgramData\jupyter
data:
    C:\somedir\AppData\Roaming\jupyter
    C:\Users\username\AppData\Roaming\jupyter
    C:\anaconda\python27\win64\431\share\jupyter
    C:\ProgramData\jupyter
runtime:
    C:\somedir\AppData\Roaming\jupyter
</code>```

jupyter --data-dir shows

```<code>jupyter --data-dir
C:\Users\username\AppData\Roaming\jupyter
</code>```

I think C:\Users\username\AppData\Roaming\jupyter needs to be removed but nor sure how. Can you please help?

答:
To set the user data directory, you should instead use the JUPYTER_DATA_DIR environment variable, in your case set to C:\somedir\AppData\Roaming\jupyter. You can also unset JUPYTER_PATH (see below for details).

Although it's not terribly obvious from documentation, the nbextension install command takes no notice of the JUPYTER_PATH environment variable, since it doesn't use the jupyter_core.paths.jupyter_path function, but uses jupyter_core.paths.jupyter_data_dir to construct the user-data nbextensions directory directly.

The entry C:\Users\username\AppData\Roaming\jupyter from the data section of the output of jupyter --paths is the user data directory, since JUPYTER_PATH is used in addition to other entries, rather than replacing any. For your purposes, I suggest you unset JUPYTER_PATH, since you can get what you want without it.

Body:
I am trying to update JUPYTER_PATH for Jupyter notebook. I set the environment variables following the jupyter documentation but still jupyter contrib nbextension install --user, for example, installed under C:\Users\username\AppData\nbextensions instead of C:\somedir\AppData\Roaming\jupyter\nbextensions.

Added these to my environment variables.

JUPYTER_CONFIG_DIR=C:\somedir\.jupyter
JUPYTER_PATH=C:\somedir\AppData\Roaming\jupyter
JUPYTER_RUNTIME_DIR=C:\somedir\AppData\Roaming\jupyter

jupyter --path shows

PS C:\somedir\> jupyter --path
config:
    C:\somedir\.jupyter
    C:\anaconda\python27\win64\431\etc\jupyter
    C:\ProgramData\jupyter
data:
    C:\somedir\AppData\Roaming\jupyter
    C:\Users\username\AppData\Roaming\jupyter
    C:\anaconda\python27\win64\431\share\jupyter
    C:\ProgramData\jupyter
runtime:
    C:\somedir\AppData\Roaming\jupyter

jupyter --data-dir shows

jupyter --data-dir
C:\Users\username\AppData\Roaming\jupyter

I think C:\Users\username\AppData\Roaming\jupyter needs to be removed but nor sure how. Can you please help?


来源: stackexchange

问:
Stuck in infinite while loop while printing values from a custom linked list
I am trying to implement a basic singly linked list. In that, I am trying to insert from head. Then I tried to print the inserted data. My code is below:

```<code> #include<iostream>
 using namespace std;

 template<class T>
 class Node
 {
      public:
      T data;
      Node<T> *next;
      Node():data(T()),next(NULL)
      {}
 };

template<class T>
class SinglyinkedList
{
      public:
      Node<T> *head;
      SinglyinkedList():head(NULL)
      {}
      void insertFromHead(T data)
      {
          Node<T> *temp;
          temp->data = data;
          temp->next = head;
          head = temp;
      }
      void printLinkedist()
      {
           Node<T> *temp;
           temp = head;

           while(temp != NULL)
           {
               cout <<"Hi";
               cout << temp->data;
               temp = temp->next;
           }
      }
 };

int main()
{
    SinglyinkedList<int> list;
    list.insertFromHead(10);
    list.insertFromHead(20);
    list.insertFromHead(30);
    list.insertFromHead(40);
    list.printLinkedist();
    return 0;
}
</code>```

But When I print linked list it just stuck in while loop and printing same value again and again.
Can anyone help why I am stuck in loop?

答:
You are trying working with uninitialized object

```<code>Node<T> *temp;
temp->data = data;
</code>```

You got such kind of undefined behavior.
Just use:

```<code>void insertFromHead( T data )
{
    Node<T> *temp = new Node<T>();
    temp->data = data;
    temp->next = head;
    head = temp;
}
</code>```

An it will solve your problem

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement a basic singly linked list. In that, I am trying to insert from head. Then I tried to print the inserted data. My code is below:

 #include<iostream>
 using namespace std;

 template<class T>
 class Node
 {
      public:
      T data;
      Node<T> *next;
      Node():data(T()),next(NULL)
      {}
 };

template<class T>
class SinglyinkedList
{
      public:
      Node<T> *head;
      SinglyinkedList():head(NULL)
      {}
      void insertFromHead(T data)
      {
          Node<T> *temp;
          temp->data = data;
          temp->next = head;
          head = temp;
      }
      void printLinkedist()
      {
           Node<T> *temp;
           temp = head;

           while(temp != NULL)
           {
               cout <<"Hi";
               cout << temp->data;
               temp = temp->next;
           }
      }
 };

int main()
{
    SinglyinkedList<int> list;
    list.insertFromHead(10);
    list.insertFromHead(20);
    list.insertFromHead(30);
    list.insertFromHead(40);
    list.printLinkedist();
    return 0;
}

But When I print linked list it just stuck in while loop and printing same value again and again.
Can anyone help why I am stuck in loop?

Body:
You are trying working with uninitialized object

Node<T> *temp;
temp->data = data;

You got such kind of undefined behavior.
Just use:

void insertFromHead( T data )
{
    Node<T> *temp = new Node<T>();
    temp->data = data;
    temp->next = head;
    head = temp;
}

An it will solve your problem


答:
Your problem is likely here:

```<code>      Node<T> *temp;
      temp->data = data;
</code>```

temp is not initialized to anything before you attempt to dereference it

Title: Stuck in infinite while loop while printing values from a custom linked list

Body:
Your problem is likely here:

      Node<T> *temp;
      temp->data = data;

temp is not initialized to anything before you attempt to dereference it


问:
About The switch Statement in Java
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

```<code>int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"
</code>```

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

```<code>import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}
</code>```

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

答:
You could solve this by creating an int value to set the input for day as day.nextInt() then you can do the math in the created variable and make the switch depending on that value, this should work:

```<code>   Scanner day = new Scanner(System.in);
    int dayVal = day.nextInt();

    if (dayVal>7){
        dayVal %= 7;
    }

    switch(dayVal){
        case 1 :
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 0:
        System.out.println("Sunday");
        break;
    }
}
</code>```

As said before, you need to change 7 to 0 because you will never have a residue of 0, therefore you will never get a Sunday

Title: About The switch Statement in Java

Body:
I'm still learning. Today I have a question in SoloLearn, into The switch Statement lesion:

int day = 3;

switch(day) {
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;

// Outputs "Wednesday"

and I thinks, I can have a example to remember about input and switch Statement: I want input a number, and 1 as Monday, 2 as Tuesday.... to 7 as Sunday, and repeat: 8 as Monday, 9 as Tuesday....
This is my code:

import java.util.Scanner;

public class Program {
public static void main(String[] args) {
    Scanner day = new Scanner(System.in);

        if (day.nextInt()>7){
            day.nextInt()=day.nextInt()%7;
        }

    switch(day.nextInt()){
        case 1 :
            System.out.println("Monday");
            break;
        case 2:
            System.out.println("Tuesday");
            break;
        case 3:
            System.out.println("Wednesday");
            break;
        case 4:
            System.out.println("Thursday");
            break;
        case 5:
            System.out.println("Friday");
            break;
        case 6:
            System.out.println("Saturday");
            break;
        case 0:
            System.out.println("Sunday");
        case 7:
            System.out.println("Sunday");
            break;

        }
    }
}

and error. My knowledge's not enough to fix this thing (I think so, because i'm a newbie and still learning). Can you expand for me, fix this thing and thanks for teach!
Have fun!

Body:
You could solve this by creating an int value to set the input for day as day.nextInt() then you can do the math in the created variable and make the switch depending on that value, this should work:

   Scanner day = new Scanner(System.in);
    int dayVal = day.nextInt();

    if (dayVal>7){
        dayVal %= 7;
    }

    switch(dayVal){
        case 1 :
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 0:
        System.out.println("Sunday");
        break;
    }
}

As said before, you need to change 7 to 0 because you will never have a residue of 0, therefore you will never get a Sunday


问:
ReactJS and NodeJS same server?

I build a project with nodejs and react. I don't know if I must split in 2 servers, one for the react app and one for API in nodejs and the react app ask request at nodejs server.

Or I must group both in only one nodejs process ? What's the difference ? There are a better choice ?

答:
It's up to you React when builded is just static files, don't get confused by the development server. I would recommend you for the beginning to put them in one node process. Just declare the folder of the static files like this:

```<code>app.use('/app', express.static(path.join(__dirname + '/dist/app')));
</code>```

Also if you are using React Router you should add this as your last router

```<code>app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/src/index.html'));
});
</code>```

You can check my template repo with webpack here

Title: ReactJS and NodeJS same server?

Body:
It's up to you React when builded is just static files, don't get confused by the development server. I would recommend you for the beginning to put them in one node process. Just declare the folder of the static files like this:

app.use('/app', express.static(path.join(__dirname + '/dist/app')));

Also if you are using React Router you should add this as your last router

app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/src/index.html'));
});

You can check my template repo with webpack here


问:
Generate a Key, Value JSON object from a Ruby Object Array
I have a Ruby array of students. Student class has attributes id, name and age.

```<code>students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]
</code>```

I want to create a JSON key value object from this array as follows.

```<code>json_object = {id1:name1, id2:name2, id3:name3}
</code>```

答:
```<code>input = [ {id:"id1",name:"name1",age:"age1"},
          {id:"id2",name:"name2",age:"age2"},
          {id:"id3",name:"name3",age:"age3"}]

require 'json'
JSON.dump(input.map { |hash| [hash[:id], hash[:name]] }.to_h)
#⇒ '{"id1":"name1","id2":"name2","id3":"name3"}'
</code>```

Body:
I have a Ruby array of students. Student class has attributes id, name and age.

students = [
             {id:"id1",name:"name1",age:"age1"},
             {id:"id2",name:"name2",age:"age2"},
             {id:"id3",name:"name3",age:"age3"}
           ]

I want to create a JSON key value object from this array as follows.

json_object = {id1:name1, id2:name2, id3:name3}


问:
Raising event from base class
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

```<code>public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}
</code>```

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

答:
The final result:</p>

```<code>public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    protected event EventHandler<FooEventArgs> backEndStorage;
    public abstract event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        if (backEndStorage != null)
            backEndStorage(sender, e);
    }
}

public class FooDerived : FooBase {
    public override event EventHandler<FooEventArgs> FooValueChanged {
        add { backEndStorage += value; }
        remove { backEndStorage -= value; }
    }
}
</code>```

OwnerDisplayName: vanslly

ContentLicense: CC BY-SA 2.5

Title: Raising event from base class

Body:
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

LastEditorDisplayName: vanslly

Body:
The final result:

public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    protected event EventHandler<FooEventArgs> backEndStorage;
    public abstract event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        if (backEndStorage != null)
            backEndStorage(sender, e);
    }
}

public class FooDerived : FooBase {
    public override event EventHandler<FooEventArgs> FooValueChanged {
        add { backEndStorage += value; }
        remove { backEndStorage -= value; }
    }
}


问:
Subversion, Hudson, Maven, Trac. What's good/bad?
Our project is soon migrating to these open source tools. In a proactive effort, I'm wondering from the experts - What you've found to be the good, bad, and uglies about these products?  What is less than intuitive? No need to comment on all of them, but feel free if you want!

If this should be a wiki or edited to be more "questiony," please advise or edit. Thanks yall!

答:
To really be able to answer your question, can you share what products you are migrating /from/?

My team recently moved from VSS to Subversion and we love it.  It gives us significantly more capabilities and far fewer problems.  It is important that you learn how it works before using it, especially (as someone mentioned) branching and merging.  Thankfully, the official Subversion book is freely available (just google "subversion book") and very well-written.  In particular, we enjoy Subversion's atomic commits, the ability to easily branch, the ability to handle most merges automatically, and the 'blame' feature which can tell you who last changed a line of code.  Our main dislike was the learning curve.  Subversion is quite different from VSS and it took some of our older developers quite a while to get used to it.  Several devs have started using git to interface with the svn repository and have reported improved productivity, but I haven't done that myself yet.  There are also a wide variety of Subversion tools available, so its easy to find one that fits your style.

Trac is much more than just a bug tracker.  We just implemented Trac, and it has been an instant hit.  Trac's ability to automatically cross-reference repository commits and tickets is making our QA team's job much easier.  Being able to also link a ticket to the wiki-based documentation and searching through everything from a single search box makes it very easy to locate information and learn about parts of the project that you haven't worked on before.  The "milestone" feature (plus a couple of plugins) is automating some of the project management tasks that we used to do by hand.  Again, the downside is the learning curve.  Its something new that developers have to get accustomed to using, and the wiki uses a markup syntax that has to be learned.  It's not too big of a hurdle, though.  We only had Trac up and running for a week before two or three other teams were wanting their own.  I personally enjoy the fact that Trac is open-source and easily extendable with a little Python.

I haven't used Maven or Hudson, so I can't comment on those.


问:
Symfony3 wont convert file to UploadedFile
I'm following this tutorial http://symfony.com/doc/current/controller/upload_file.html but the $file isn't being converted to an UploadedFile, it stays as a string:

```<code>var_dump($file);
/home/owner/Desktop/Workspace/Documentary/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php:103:string '/tmp/phpmmv1LP' (length=14)
</code>```

Type error: Argument 1 passed to DW\DocumentaryBundle\Uploader\PosterUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, called in /home/owner/Desktop/Workspace/DocumentaryWIRE/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php on line 106

Create Action:

```<code>     /**
     * @param Request $request
     * @return Response
     */
    public function createAction(Request $request)
    {
        $documentary = new Documentary();

        $form = $this->createForm(DocumentaryType::class, $documentary);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $file = $documentary->getPoster();

            $posterUploader = $this->getPosterUploader();
            $fileName = $posterUploader->upload($file);

            $documentary->setPoster($fileName);

            $documentaryService = $this->getDocumentaryService();
            $documentaryService->save($documentary);
        }

        return $this->render('DocumentaryBundle:Admin:create.html.twig', array(
            'form' => $form->createView(),
        ));
    }
</code>```

View

```<code>{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
</code>```

Form:

```<code><?php

namespace DW\DocumentaryBundle\Form;

use DW\DocumentaryBundle\Entity\Documentary;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DocumentaryType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('storyline', TextareaType::class)
            ->add('summary', TextareaType::class)
            ->add('year', IntegerType::class)
            ->add('length', IntegerType::class)
            ->add('status', TextType::class)
            ->add('views', IntegerType::class)
            ->add('shortUrl', TextType::class)
            ->add('videoId', TextType::class)
            ->add('videoSource', TextType::class)
            ->add('poster', FileType::class, [
                'label' => 'Poster'])
            ->add('category', EntityType::class, [
                'class' => 'CategoryBundle:Category',
                'choice_label' => 'name',
            ])
            ->add('submit', SubmitType::class);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Documentary::class,
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return "documentary";
    }
}
</code>```

Controller:

```<code><?php

namespace DW\DocumentaryBundle\Uploader;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class PosterUploader
{
    /**
     * @var string
     */
    private $targetDir;

    /**
     * @param string $targetDir
     */
    public function __construct(string $targetDir)
    {
        $this->targetDir = $targetDir;
    }

    /**
     * @param UploadedFile $file
     * @return string
     */
    public function upload(UploadedFile $file)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();

        $file->move($this->targetDir, $fileName);

        return $fileName;
    }
}
</code>```

答:
The documentation is NOT wrong! They don't use type hinting in their example:

```<code>// src/AppBundle/Entity/Product.php
public function setBrochure($brochure)
{
    $this->brochure = $brochure;

    return $this;
}
</code>```

When you use string type hinting then UploadedFile::__toString() will be invoked!
So check your entity. It should be something like this:

```<code>public function setPoster($poster)
{
   // ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm following this tutorial http://symfony.com/doc/current/controller/upload_file.html but the $file isn't being converted to an UploadedFile, it stays as a string:

var_dump($file);
/home/owner/Desktop/Workspace/Documentary/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php:103:string '/tmp/phpmmv1LP' (length=14)

Type error: Argument 1 passed to DW\DocumentaryBundle\Uploader\PosterUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, called in /home/owner/Desktop/Workspace/DocumentaryWIRE/src/DW/DocumentaryBundle/Controller/Admin/DocumentaryController.php on line 106

Create Action:

     /**
     * @param Request $request
     * @return Response
     */
    public function createAction(Request $request)
    {
        $documentary = new Documentary();

        $form = $this->createForm(DocumentaryType::class, $documentary);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $file = $documentary->getPoster();

            $posterUploader = $this->getPosterUploader();
            $fileName = $posterUploader->upload($file);

            $documentary->setPoster($fileName);

            $documentaryService = $this->getDocumentaryService();
            $documentaryService->save($documentary);
        }

        return $this->render('DocumentaryBundle:Admin:create.html.twig', array(
            'form' => $form->createView(),
        ));
    }

View

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

Form:

<?php

namespace DW\DocumentaryBundle\Form;

use DW\DocumentaryBundle\Entity\Documentary;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DocumentaryType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('storyline', TextareaType::class)
            ->add('summary', TextareaType::class)
            ->add('year', IntegerType::class)
            ->add('length', IntegerType::class)
            ->add('status', TextType::class)
            ->add('views', IntegerType::class)
            ->add('shortUrl', TextType::class)
            ->add('videoId', TextType::class)
            ->add('videoSource', TextType::class)
            ->add('poster', FileType::class, [
                'label' => 'Poster'])
            ->add('category', EntityType::class, [
                'class' => 'CategoryBundle:Category',
                'choice_label' => 'name',
            ])
            ->add('submit', SubmitType::class);
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Documentary::class,
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return "documentary";
    }
}

Controller:

<?php

namespace DW\DocumentaryBundle\Uploader;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class PosterUploader
{
    /**
     * @var string
     */
    private $targetDir;

    /**
     * @param string $targetDir
     */
    public function __construct(string $targetDir)
    {
        $this->targetDir = $targetDir;
    }

    /**
     * @param UploadedFile $file
     * @return string
     */
    public function upload(UploadedFile $file)
    {
        $fileName = md5(uniqid()).'.'.$file->guessExtension();

        $file->move($this->targetDir, $fileName);

        return $fileName;
    }
}

Body:
The documentation is NOT wrong! They don't use type hinting in their example:

// src/AppBundle/Entity/Product.php
public function setBrochure($brochure)
{
    $this->brochure = $brochure;

    return $this;
}

When you use string type hinting then UploadedFile::__toString() will be invoked!
So check your entity. It should be something like this:

public function setPoster($poster)
{
   // ...
}


问:
how is std::set (red/black tree) forward iteration implemented?
if i did an inorder traversal of a balanced BST from smallest to largest value, i'd use a DFS which maintains a stack of size lg(n). but if I needed to find the inorder successor of an arbitrary node, it's a worst case lg(n) operation. but if I wanted to iterate in order, id need to find the inorder successor repeatedly for each node yielding O(n*lg(n)). Does std::set use some trick for inorder iteration, or does it really cost O(n*lg(n)), or is the time cost amortized somehow?</p>

答:
There is no trick in the in-order iteration; all you need is an O(1) mechanism for finding the parent of the current node.

The in-order scan traverses each parent-child edge exactly twice: once from parent-to-child and once from child-to-parent. Since there are the same number of edges as non-root nodes in the tree, it follows that the complete iteration performs Θ(n) transitions to iterate over n nodes, which is amortised constant time per node.

The usual way to find the parent is to store a parent link in the node. The extra link certainly increases the size of a node (four pointers instead of three) but the cost is within reason.

If it were not for the C++ iterator invalidation rules, which require that iterators to elements of  ordered associative containers must not be invalidated by insertion or deletion of other elements, it would be possible to maintain a stack of size O(log n) in the iterator. Such an iterator would be bulky but not unmanageably so (since log n is limited in practice to a smallish integer), but it would not be usable after any tree modification.


问:
Can't pull first $key from CSV using foreach
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

```<code>Part Number,Description,List Price
</code>```

Then Data so on and so forth.

What I have:

```<code>ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Print:

```<code>partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2
</code>```

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

```<code>test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3
</code>```

Type check:

```<code>echo "I'm of Type ". gettype($value) . ". ";
</code>```

returns:

```<code>partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.
</code>```

Side Note:

```<code>case "partnumber":
    $pn = $key;
    break;
</code>```

is never accessed

```<code>case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;
</code>```

This returns without any result.

Any Suggestions?

This Scenario is thanks to @azjezz

```<code>$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Results in:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:
</code>```

Another weird scinario:

```<code>    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }
</code>```

Returns:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:
</code>```

答:
I hope you don't mind me proposing an alternative method to the one your following.

```<code>ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    // Read the header line with the field names in it
    $keyLine = fgets($openItems);
    $keyLine = preg_replace('/\h+/', '', strtolower($keyLine));
    // Convert the line into an array of field names
    $keys = str_getcsv($keyLine);
    // While you have some more data in the file...
    while ( $data = fgetcsv($openItems)) {
        $csv = [];
        $csv['pn'] = $data[array_search('partnumber', $keys )];
        $csv['lp'] = $data[array_search('listprice', $keys )];
        $csv['des'] = $data[array_search('description', $keys )];
        print_r($csv);
    }
    fclose($openItems);
}
</code>```

This would hopefully be simpler and more concise than your trying to get working. The main loop just reads a line in and then checks where any particular element is held in the line (could be better to assign this to an stored value rather than using array_search each time).

One thing which could be improved on is that it assumes that each field is present.  You could add extra logic to say if the description field isn't present then don't try and fetch a value for it.

Body:
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

Part Number,Description,List Price

Then Data so on and so forth.

What I have:

ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Print:

partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3

Type check:

echo "I'm of Type ". gettype($value) . ". ";

returns:

partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.

Side Note:

case "partnumber":
    $pn = $key;
    break;

is never accessed

case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;

This returns without any result.

Any Suggestions?

This Scenario is thanks to @azjezz

$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Results in:

partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:

Another weird scinario:

    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }

Returns:

partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:

Body:
I hope you don't mind me proposing an alternative method to the one your following.

ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    // Read the header line with the field names in it
    $keyLine = fgets($openItems);
    $keyLine = preg_replace('/\h+/', '', strtolower($keyLine));
    // Convert the line into an array of field names
    $keys = str_getcsv($keyLine);
    // While you have some more data in the file...
    while ( $data = fgetcsv($openItems)) {
        $csv = [];
        $csv['pn'] = $data[array_search('partnumber', $keys )];
        $csv['lp'] = $data[array_search('listprice', $keys )];
        $csv['des'] = $data[array_search('description', $keys )];
        print_r($csv);
    }
    fclose($openItems);
}

This would hopefully be simpler and more concise than your trying to get working. The main loop just reads a line in and then checks where any particular element is held in the line (could be better to assign this to an stored value rather than using array_search each time).

One thing which could be improved on is that it assumes that each field is present.  You could add extra logic to say if the description field isn't present then don't try and fetch a value for it.


问:
Geocoding in Python
I am using the geocoder package in Python to obtain the coordinates for a set of addresses (around 30k). I get the following error:

Status code Unknown from
  https://maps.googleapis.com/maps/api/geocode/json: ERROR -
  HTTPSConnectionPool(host='maps.googleapis.com', port=443): Max retries
  exceeded with url:
  /maps/api/geocode/json?address=Rancho+Palos+Verdes%2CCA%2CUS&bounds=&components=&region=&language=
  (Caused by ProxyError('Cannot connect to proxy.', timeout('timed
  out',)))

The number of times I receive the error reduces if I add the time.sleep(x) function but it significantly increases the time taken to execute the code. Is there a more efficient way to run the code?

Following is a snippet of the code:

```<code>for add in clean_address:
    g=geocoder.google(add)
    time.sleep(7)
    if(g.ok==True):
        lat.append(str(g.lat))
        lon.append(str(g.lng))
    if(g.ok==False):
        lat.append("")
        lon.append("")
</code>```

答:
Your addresses are 30K and the limit is 2,5K per day.

As Google quotes in the relevant docs:

To use the Google Maps Geocoding API, you must register your app
  project on the Google API Console and get a Google API key which you
  can add to your app or website.

After doing so, these are the limits:

Users of the standard API:

2,500 free requests per day, calculated as the sum of client-side and server-side queries.

50 requests per second, calculated as the sum of client-side and server-side queries.

Title: Geocoding in Python

Body:
I am using the geocoder package in Python to obtain the coordinates for a set of addresses (around 30k). I get the following error:

Status code Unknown from
  https://maps.googleapis.com/maps/api/geocode/json: ERROR -
  HTTPSConnectionPool(host='maps.googleapis.com', port=443): Max retries
  exceeded with url:
  /maps/api/geocode/json?address=Rancho+Palos+Verdes%2CCA%2CUS&bounds=&components=&region=&language=
  (Caused by ProxyError('Cannot connect to proxy.', timeout('timed
  out',)))

The number of times I receive the error reduces if I add the time.sleep(x) function but it significantly increases the time taken to execute the code. Is there a more efficient way to run the code?

Following is a snippet of the code:

for add in clean_address:
    g=geocoder.google(add)
    time.sleep(7)
    if(g.ok==True):
        lat.append(str(g.lat))
        lon.append(str(g.lng))
    if(g.ok==False):
        lat.append("")
        lon.append("")


问:
More concise way of doing the grouping in Ruby
Ok so i have an array of 4 objects like

```<code> => [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
 matches.size
 => 4
</code>```

with 4 different objects (Graphic, Collection, Category, Volume) I now need to separate these into 4 arrays based on the objects. So i created this method and it works but its so hackish....any ideas on how to achieve the same thing in a more concise way ...more rubyesk

Here is my method

```<code>def self.get_results(matches)
  graphics =  [], collections =  [], categories =  [], sub_categories =  []
  matches.group_by(&:class).each do |key, group|
    case group.first.class.to_s
    when "Graphic"
     graphics << group
    when "Category"
     categories << group
    when "SubCategory"
     sub_categories << group
    when "Collection"
     collections << group
    end
  end
  [graphics.flatten, collections.flatten, categories.flatten, sub_categories.flatten]
end
</code>```

答:
```<code>matches_by = matches.group_by {|m| m.class.to_s }
%w{Graphic Category SubCategory Collection}.map do |class_name|
  matches_by[class_name] || []
end
</code>```

If you don't care what order they're in, try this

```<code>matches.group_by {|m| m.class.to_s }.values
</code>```

If you just want a Hash, indexed by the class name (where the value of each entry is an Array of objects of that type), it's simply

```<code>matches.group_by {|m| m.class.to_s }
</code>```

Body:
Ok so i have an array of 4 objects like

 => [#<Graphic id: 3...">, #<Collection id: 1....">, #<Category id:...">, #<Volume id: 15...">]
 matches.size
 => 4

with 4 different objects (Graphic, Collection, Category, Volume) I now need to separate these into 4 arrays based on the objects. So i created this method and it works but its so hackish....any ideas on how to achieve the same thing in a more concise way ...more rubyesk

Here is my method

def self.get_results(matches)
  graphics =  [], collections =  [], categories =  [], sub_categories =  []
  matches.group_by(&:class).each do |key, group|
    case group.first.class.to_s
    when "Graphic"
     graphics << group
    when "Category"
     categories << group
    when "SubCategory"
     sub_categories << group
    when "Collection"
     collections << group
    end
  end
  [graphics.flatten, collections.flatten, categories.flatten, sub_categories.flatten]
end

Body:
matches_by = matches.group_by {|m| m.class.to_s }
%w{Graphic Category SubCategory Collection}.map do |class_name|
  matches_by[class_name] || []
end

If you don't care what order they're in, try this

matches.group_by {|m| m.class.to_s }.values

If you just want a Hash, indexed by the class name (where the value of each entry is an Array of objects of that type), it's simply

matches.group_by {|m| m.class.to_s }


问:
How can I write an array of strings into a file.txt using system calls write() and open()
I want to write a predefined array of strings to a file.txt, like so:

```<code>#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    char *somestr[] = {"haha\n", "aww\n", "hmm\n", "hello\n", "there\n"};
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
    for (int i = 0; i < 5; ++i) {
        write(filedesc, somestr[i], 24);
    }
    return 0;
}
</code>```

This will create testfile.txt. Expected file content:

```<code>haha
aww
hmm
hello
there
</code>```

But when I tried, it gives a weird result. Actual content:

haha
  \00aww
  \00hmm
  \00hello
  \00there
  \00aww
  \00hmm
  \00hello
  \00there
  \00testfihmm
  \00hello
  \00there
  \00testfile.txhello
  \00there
  \00testfile.txt\00\00there
  \00testfile.txt\00\00;4\00\00\00

答:
Just to make more clear and readable your code Here are my observation :

First thing when you are using open() system call with O_CREAT flag, you should provide explicit permission, reason for this is if you observe man page of open() written by Michael Kerrisk, open() with 2 argument and open() with 3 arguments.

```<code>int open(const char *pathname, int flags);

int open(const char *pathname, int flags, mode_t mode);
</code>```

when you are creating file and writing/appending/truncating file using open() system call you should use open() call with 3 argument . as man page says

mode specifies the permissions to use in case a new file is created.  This argument must be supplied when O_CREAT is  specified
          in  flags and make sure umask value is not set to 0.

Refer the man pages for this "The effective permissions are modified by the process's umask in
              the   usual  way";

and if you try to open a already existing file using open() you can use open() system call with 2 arguments as man page says "if O_CREAT is not specified, then mode is ignored"

So replace  this

```<code> int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
</code>```

with

```<code> int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT , 0664);
 if (filedesc == -1) {
     perror("open");
     …exit or return or …
 }
</code>```

Second thing, somestr is array of char pointers, each pointer can have any length. Instead of random no of characters (24 as mentioned), if you want to make it generic, use strlen(somestr[i]).

```<code>int no_of_string = sizeof(somestr)/sizeof(somestr[0]);
for (int i = 0; i < no_of_string; ++i) {
    write(filedesc, somestr[i], strlen(somestr[i]));
}
</code>```

Body:
I want to write a predefined array of strings to a file.txt, like so:

#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    char *somestr[] = {"haha\n", "aww\n", "hmm\n", "hello\n", "there\n"};
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
    for (int i = 0; i < 5; ++i) {
        write(filedesc, somestr[i], 24);
    }
    return 0;
}

This will create testfile.txt. Expected file content:

haha
aww
hmm
hello
there

But when I tried, it gives a weird result. Actual content:

haha
  \00aww
  \00hmm
  \00hello
  \00there
  \00aww
  \00hmm
  \00hello
  \00there
  \00testfihmm
  \00hello
  \00there
  \00testfile.txhello
  \00there
  \00testfile.txt\00\00there
  \00testfile.txt\00\00;4\00\00\00

Body:
Just to make more clear and readable your code Here are my observation :

First thing when you are using open() system call with O_CREAT flag, you should provide explicit permission, reason for this is if you observe man page of open() written by Michael Kerrisk, open() with 2 argument and open() with 3 arguments.

int open(const char *pathname, int flags);

int open(const char *pathname, int flags, mode_t mode);

when you are creating file and writing/appending/truncating file using open() system call you should use open() call with 3 argument . as man page says

mode specifies the permissions to use in case a new file is created.  This argument must be supplied when O_CREAT is  specified
          in  flags and make sure umask value is not set to 0.

Refer the man pages for this "The effective permissions are modified by the process's umask in
              the   usual  way";

and if you try to open a already existing file using open() you can use open() system call with 2 arguments as man page says "if O_CREAT is not specified, then mode is ignored"

So replace  this

 int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);

with

 int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT , 0664);
 if (filedesc == -1) {
     perror("open");
     …exit or return or …
 }

Second thing, somestr is array of char pointers, each pointer can have any length. Instead of random no of characters (24 as mentioned), if you want to make it generic, use strlen(somestr[i]).

int no_of_string = sizeof(somestr)/sizeof(somestr[0]);
for (int i = 0; i < no_of_string; ++i) {
    write(filedesc, somestr[i], strlen(somestr[i]));
}


问:
Create TOC in Jaspersoft studio with dotted lines
I am trying to create my table of contents in jasper studio 6.4.3. It has to be a dotted TOC, which means I need to fill the space between label text field and page number text filed with dots. The solution that I have at the time has two problems.

First: There are half dots to see, depending the length of the texts in fields

Second: I can not get the dots and page number field aligned to the label after stretch.
The solution for the dots is, having a static text field behind both text fields and set the text fields background to with, in order to cover the dots behind the texts.

```<code><band height="31" splitType="Stretch">
        <property name="local_mesure_unitheight" value="pixel"/>
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
        <printWhenExpression><![CDATA[$F{level} == 1]]></printWhenExpression>
        <staticText>
            <reportElement style="InhaltsverzeichnisPunkte" mode="Transparent" x="0" y="1" width="440" height="18" uuid="b08b479c-10a8-4d87-8507-4f32fd50004f"/>
            <text><![CDATA[. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .]]></text>
        </staticText>
        <textField isStretchWithOverflow="true">
            <reportElement style="InhaltsverzeichnisPunkte" x="396" y="1" width="45" height="18" uuid="bc43bd36-7466-457c-95e6-384410c05cbe"/>
            <textElement textAlignment="Right"/>
            <textFieldExpression><![CDATA["<style backcolor='white'>"+($V{PAGE_NUMBER} + $F{pageIndex} + 3)+"</style>"]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true" hyperlinkType="LocalAnchor">
            <reportElement style="Formatvorlage Standard (kleiner) + 10 Pt." mode="Transparent" x="0" y="3" width="396" height="15" uuid="b19a02f7-3d3f-4086-86ed-5dc6859e5fd1"/>
            <textElement textAlignment="Left" markup="styled"/>
            <textFieldExpression><![CDATA["<style backcolor='white'>"+$F{label}+"</style>"]]></textFieldExpression>
            <hyperlinkAnchorExpression><![CDATA[$F{label}]]></hyperlinkAnchorExpression>
        </textField>
    </band>
</code>```

As you can see in the picture, the page number 6 need and the dots should be appear aligned to the second line in the text field, and the dot after character g is cut.

答:
You can almost achieve what you want with:

verticalAlignment set to Bottom for all your text elements

stretchType set to ContainerBottom for the 'dotted' staticText and the 'page index' textField elements

like so:

```<code><band height="39" splitType="Stretch">
<staticText>
    <reportElement stretchType="ContainerBottom" mode="Transparent" x="0" y="1" width="440" height="18" uuid="b08b479c-10a8-4d87-8507-4f32fd50004f"/>
    <textElement verticalAlignment="Bottom"/>
    <text><![CDATA[. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .]]></text>
</staticText>
<textField isStretchWithOverflow="true">
    <reportElement stretchType="ContainerBottom" x="396" y="1" width="45" height="18" uuid="bc43bd36-7466-457c-95e6-384410c05cbe"/>
    <textElement textAlignment="Right" verticalAlignment="Bottom" markup="styled"/>
    <textFieldExpression><![CDATA["<style backcolor='white'>"+($V{PAGE_NUMBER} + $F{pageIndex} + 3)+"</style>"]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true" hyperlinkType="LocalAnchor">
    <reportElement mode="Transparent" x="0" y="3" width="396" height="16" uuid="b19a02f7-3d3f-4086-86ed-5dc6859e5fd1">
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textElement textAlignment="Left" verticalAlignment="Bottom" markup="styled"/>
    <textFieldExpression><![CDATA["<style backcolor='white'>"+$F{label}+"</style>"]]></textFieldExpression>
    <hyperlinkAnchorExpression><![CDATA[$F{label}]]></hyperlinkAnchorExpression>
</textField>
</code>```

The output:

Note:

You may still experience 'cut' dots because the text elements overlap. I cannot think of a different approach for this.

I have adjusted your code by removing the styles and tweaking the elements' height to align properly.

Body:
I am trying to create my table of contents in jasper studio 6.4.3. It has to be a dotted TOC, which means I need to fill the space between label text field and page number text filed with dots. The solution that I have at the time has two problems.

First: There are half dots to see, depending the length of the texts in fields

Second: I can not get the dots and page number field aligned to the label after stretch.
The solution for the dots is, having a static text field behind both text fields and set the text fields background to with, in order to cover the dots behind the texts.

<band height="31" splitType="Stretch">
        <property name="local_mesure_unitheight" value="pixel"/>
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
        <printWhenExpression><![CDATA[$F{level} == 1]]></printWhenExpression>
        <staticText>
            <reportElement style="InhaltsverzeichnisPunkte" mode="Transparent" x="0" y="1" width="440" height="18" uuid="b08b479c-10a8-4d87-8507-4f32fd50004f"/>
            <text><![CDATA[. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .]]></text>
        </staticText>
        <textField isStretchWithOverflow="true">
            <reportElement style="InhaltsverzeichnisPunkte" x="396" y="1" width="45" height="18" uuid="bc43bd36-7466-457c-95e6-384410c05cbe"/>
            <textElement textAlignment="Right"/>
            <textFieldExpression><![CDATA[""]]></textFieldExpression>
        </textField>
        <textField isStretchWithOverflow="true" hyperlinkType="LocalAnchor">
            <reportElement style="Formatvorlage Standard (kleiner) + 10 Pt." mode="Transparent" x="0" y="3" width="396" height="15" uuid="b19a02f7-3d3f-4086-86ed-5dc6859e5fd1"/>
            <textElement textAlignment="Left" markup="styled"/>
            <textFieldExpression><![CDATA[""]]></textFieldExpression>
            <hyperlinkAnchorExpression><![CDATA[$F{label}]]></hyperlinkAnchorExpression>
        </textField>
    </band>

As you can see in the picture, the page number 6 need and the dots should be appear aligned to the second line in the text field, and the dot after character g is cut.

Body:
You can almost achieve what you want with:

verticalAlignment set to Bottom for all your text elements

stretchType set to ContainerBottom for the 'dotted' staticText and the 'page index' textField elements

like so:

<band height="39" splitType="Stretch">
<staticText>
    <reportElement stretchType="ContainerBottom" mode="Transparent" x="0" y="1" width="440" height="18" uuid="b08b479c-10a8-4d87-8507-4f32fd50004f"/>
    <textElement verticalAlignment="Bottom"/>
    <text><![CDATA[. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .]]></text>
</staticText>
<textField isStretchWithOverflow="true">
    <reportElement stretchType="ContainerBottom" x="396" y="1" width="45" height="18" uuid="bc43bd36-7466-457c-95e6-384410c05cbe"/>
    <textElement textAlignment="Right" verticalAlignment="Bottom" markup="styled"/>
    <textFieldExpression><![CDATA["<style backcolor='white'>"+($V{PAGE_NUMBER} + $F{pageIndex} + 3)+"</style>"]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true" hyperlinkType="LocalAnchor">
    <reportElement mode="Transparent" x="0" y="3" width="396" height="16" uuid="b19a02f7-3d3f-4086-86ed-5dc6859e5fd1">
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
    </reportElement>
    <textElement textAlignment="Left" verticalAlignment="Bottom" markup="styled"/>
    <textFieldExpression><![CDATA["<style backcolor='white'>"+$F{label}+"</style>"]]></textFieldExpression>
    <hyperlinkAnchorExpression><![CDATA[$F{label}]]></hyperlinkAnchorExpression>
</textField>

The output:

Note:

You may still experience 'cut' dots because the text elements overlap. I cannot think of a different approach for this.

I have adjusted your code by removing the styles and tweaking the elements' height to align properly.


答:
```<code>ret = {}
matches.group_by(&:class).each do |klass, item|
  ret[klass.to_s] = item
end
ret.values
</code>```

Title: More concise way of doing the grouping in Ruby


问:
Is there a way to infuse the input variable in regex?
EDIT: So apparently, this is a string interpolation in regex. Thanks for clarifying.

I have a input function that is named omj.

```<code>omj
</code>```

When I run it, it gives me

```<code>"obik"
</code>```

I then use that output in this regex function

```<code>re.findall("\w*obik\w*",dataframe)
</code>```

I received EXACTLY what I wanted, which is the answer

```<code>"Yaobikuni"
</code>```

Notice that "obik" is in the word, and there is only one match for it. Is there a way to put the input omj in the regex function to get Yaobikuni straightforwardly, or is this the only way it would work?

EDIT: I don't understand why people are downvoting, but I thought I made it clear that omj can be considered as an input string that gives the answer obik.

```<code>omj = """obik"""
</code>```

EDIT2: Thank you for the help @Nick Chapman . I tried this on the first time and I thought it might not have been possible to infuse the input omj on an regex function:

```<code>re.findall("\w*"omj"\w*",dataframe)
</code>```

答:
The first argument is just a string, so your real question is how to do string interpolation in Python.

How about this:

```<code>re.findall("\w*{}\w*".format(omj()), dataframe)
</code>```

Body:
EDIT: So apparently, this is a string interpolation in regex. Thanks for clarifying.

I have a input function that is named omj.

omj

When I run it, it gives me

"obik"

I then use that output in this regex function

re.findall("\w*obik\w*",dataframe)

I received EXACTLY what I wanted, which is the answer

"Yaobikuni"

Notice that "obik" is in the word, and there is only one match for it. Is there a way to put the input omj in the regex function to get Yaobikuni straightforwardly, or is this the only way it would work?

EDIT: I don't understand why people are downvoting, but I thought I made it clear that omj can be considered as an input string that gives the answer obik.

omj = """obik"""

EDIT2: Thank you for the help @Nick Chapman . I tried this on the first time and I thought it might not have been possible to infuse the input omj on an regex function:

re.findall("\w*"omj"\w*",dataframe)

Body:
The first argument is just a string, so your real question is how to do string interpolation in Python.

How about this:

re.findall("\w*{}\w*".format(omj()), dataframe)


问:
User login system including username and password
How is it possible to check the entries for login and password and if they are correct, new tabs will open. If the entries are incorrect, an error message will be displayed. The user should also be able to register for an account</p>

```<code> from tkinter import *
import sqlite3
import tkinter
import time
root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)
labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

Label(root, text="Username:", background='grey').grid(row=3, column=0, sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0, sticky=W)

e1 = Entry(root)
e1.grid(row=3, column=1)

if e1 == 'yes':
    command =new_winF

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()
</code>```

答:
create a function and bind it to login button to check your entry inputs.Here your Username entry should be yes the password no if it matches then the window will pop up, if not mesagebox will pop it to alert the user.

```<code>from tkinter import *
import sqlite3
from tkinter import messagebox
import tkinter
import time

root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)

labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

 Label(root, text="Username:", background='grey').grid(row=3,column=0,sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0,
sticky=W)

def login_fun():
    if e1.get() == "yes" and e2.get() == "no":
       new_winF()
    else:
        messagebox.showerror("error","try agian boy")

e1 = Entry(root)
e1.grid(row=3, column=1)

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10, command=login_fun)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()
</code>```

Body:
How is it possible to check the entries for login and password and if they are correct, new tabs will open. If the entries are incorrect, an error message will be displayed. The user should also be able to register for an account

 from tkinter import *
import sqlite3
import tkinter
import time
root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)
labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

Label(root, text="Username:", background='grey').grid(row=3, column=0, sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0, sticky=W)

e1 = Entry(root)
e1.grid(row=3, column=1)

if e1 == 'yes':
    command =new_winF

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()

Body:
create a function and bind it to login button to check your entry inputs.Here your Username entry should be yes the password no if it matches then the window will pop up, if not mesagebox will pop it to alert the user.

from tkinter import *
import sqlite3
from tkinter import messagebox
import tkinter
import time

root = Tk()

root.title("Sale System")
root.geometry("500x500")
root.configure(background='grey')

Label(root, text="Checkout System", background='grey').grid(row=0, column=1)
Label(root, text="Time:", background='grey').grid(row=1, column=1)

def clock():
    t=time.strftime('%I:%M:%S',time.localtime())
    if t!='':
        labeltime.config(text=t)
    root.after(100,clock)

labeltime=Label(root, text="Current System Time", background='grey')
labeltime.grid(row=1, column=1)
time1 = clock()

def new_winF(): #Opens registration confirmation window
    newwin = Toplevel(root)
    display = Label(newwin, text="Your account has been created. Please log in with your new details. This window may be closed.")
    display.pack()

 Label(root, text="Username:", background='grey').grid(row=3,column=0,sticky=W)
Label(root, text="Password:", background='grey').grid(row=4, column=0,
sticky=W)

def login_fun():
    if e1.get() == "yes" and e2.get() == "no":
       new_winF()
    else:
        messagebox.showerror("error","try agian boy")

e1 = Entry(root)
e1.grid(row=3, column=1)

e2 = Entry(root)
e2.grid(row=4, column=1)

LoginButton = Button(root, text="Login", width=10, command=login_fun)
LoginButton.grid(row=5, column=1)

RegisterButton = Button(root, text ="Register", command =new_winF, width=10)
RegisterButton.grid(row=6, column=1)

root.mainloop()


答:
Linked-list code usually contains one use of new for each node, and you forgot yours.

This means that you were using an uninitialised pointer, which is undefined.

Add the missing object:

```<code>void insertFromHead(T data)
{
    Node<T> *temp = new Node<T>;
    temp->data = data;
    temp->next = head;
    head = temp;
}
</code>```

If you add a constructor to Node,

```<code>Node(const T& d, Node<T>* n): data(d), next(n) {}
</code>```

you can shorten it a bit, too:

```<code>void insertFromHead(const T& data)
{
    head = new Node<T>(data, head);
}
</code>```

Body:
I am trying to implement a basic singly linked list. In that, I am trying to insert from head. Then I tried to print the inserted data. My code is below:

 #include<iostream>
 using namespace std;

 template<class T>
 class Node
 {
      public:
      T data;
      Node<T> *next;
      Node():data(T()),next(NULL)
      {}
 };

template<class T>
class SinglyinkedList
{
      public:
      Node<T> *head;
      SinglyinkedList():head(NULL)
      {}
      void insertFromHead(T data)
      {
          Node<T> *temp;
          temp->data = data;
          temp->next = head;
          head = temp;
      }
      void printLinkedist()
      {
           Node<T> *temp;
           temp = head;

           while(temp != NULL)
           {
               cout <<"Hi";
               cout << temp->data;
               temp = temp->next;
           }
      }
 };

int main()
{
    SinglyinkedList<int> list;
    list.insertFromHead(10);
    list.insertFromHead(20);
    list.insertFromHead(30);
    list.insertFromHead(40);
    list.printLinkedist();
    return 0;
}

But When I print linked list it just stuck in while loop and printing same value again and again.
Can anyone help why I am stuck in loop?

Body:
Linked-list code usually contains one use of new for each node, and you forgot yours.

This means that you were using an uninitialised pointer, which is undefined.

Add the missing object:

void insertFromHead(T data)
{
    Node<T> *temp = new Node<T>;
    temp->data = data;
    temp->next = head;
    head = temp;
}

If you add a constructor to Node,

Node(const T& d, Node<T>* n): data(d), next(n) {}

you can shorten it a bit, too:

void insertFromHead(const T& data)
{
    head = new Node<T>(data, head);
}


问:
drawing an ellipse in wpf from within a secondary thread
I am writing a wpf application in which balls are bouncing independently on a canvas, each ball in a different thread. Each time the user clicks on the canvas a new thread is added to the threadpool and an ellipse representing the ball is created. In order to add the ellipse and draw it I use Dispatcher.Invoke. However, the command myCanvas.Children.Add(el); called from within the code surrounded by Invoke causes the application to crash the moment the Invoke block ends, by entering break mode.
Obviously, this is not the way to achieve my goal, so how can I do it? </p>

```<code>        Dispatcher.Invoke(new Action(() =>
        {
            Ellipse el = new Ellipse();
            el.Fill = color1;
            el.Margin = new Thickness(10);
            el.Height = 40;
            el.Width = 40;
            balls.Add(ballsCounter, el);
            Canvas.SetTop(el, p.Y - 2 * el.Height / 3);
            Canvas.SetLeft(el, p.X - 2 * el.Width / 3);
            myCanvas.Children.Add(el);
            tbNumBalls.Text = ballsCounter.ToString();
        }));
</code>```

答:
You can't create the Ellipse on one (UI) thread and then add it to a Canvas that was created on another (UI) thread.

This is not possible because of fact that WPF uses a single threaded exeuction model with thread affinity. This basically means that a UI control cannot be accessed from any other thread than the one on which it was originally created. There are checks in the base classes that enforce this by throwing InvalidOperationExceptions whenever you try to do this.

So you should either create all controls on the same thread, or keep them forever separated on different threads.

Body:
I am writing a wpf application in which balls are bouncing independently on a canvas, each ball in a different thread. Each time the user clicks on the canvas a new thread is added to the threadpool and an ellipse representing the ball is created. In order to add the ellipse and draw it I use Dispatcher.Invoke. However, the command myCanvas.Children.Add(el); called from within the code surrounded by Invoke causes the application to crash the moment the Invoke block ends, by entering break mode.
Obviously, this is not the way to achieve my goal, so how can I do it?

        Dispatcher.Invoke(new Action(() =>
        {
            Ellipse el = new Ellipse();
            el.Fill = color1;
            el.Margin = new Thickness(10);
            el.Height = 40;
            el.Width = 40;
            balls.Add(ballsCounter, el);
            Canvas.SetTop(el, p.Y - 2 * el.Height / 3);
            Canvas.SetLeft(el, p.X - 2 * el.Width / 3);
            myCanvas.Children.Add(el);
            tbNumBalls.Text = ballsCounter.ToString();
        }));


问:
publish to kafka topic within a map method
Writing to kafka topic from within a map function (SCALA) ?

Reading from a kafka topic in a FLINK Application

Processing the data within a map function

Problem Statement - Within the map function I am looping through a list. For each element in the list I want to publish to a kafka topic.

when I get the output from the map and sink it works, but if I try a push to topic from within map method it doesn't

Is it possible to publish to topic from within a map method

```<code>// Main Function
def main(args: Array[String]) {

...
// some list
val list_ = ("a", "b", "c", "d")
// Setup Properties
val props = new Properties()
props.setProperty("zookeeper.connect", zookeeper_url + ":" + zookeeper_port)
props.setProperty("bootstrap.servers", broker_url + ":" + broker_port)
props.setProperty("auto.offset.reset", "earliest")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

...

// Connect to Source
val input_stream = env.addSource(new FlinkKafkaConsumer09[String](topic_in, new SimpleStringSchema(), properties))

// Process each Record
val stream = input_stream.map(x=> {

  // loop through list "list_" -> variable in in Main
  // and publish to topic_out
  // -- THIS IS MY CURRENT ISSUE !!!)
  // -- Does not work (No compile issue)
  //
  var producer2 = new KafkaProducer[String, String](props)
  var record    = new ProducerRecord(topic_out, "KEY", list(i))
  producer2.send(record)
  producer2.flush()

 // ... Other process and return processed string

})

// publish to different topic of proccessed input string (Works)
stream.addSink(new FlinkKafkaProducer09[String](broker_url + ":" + broker_port, other_topic, new SimpleStringSchema()))
</code>```

答:
Do not make a kafka producer inside of a map function and do not try to write to a kafka topic inside of a map. Honestly, I can't quote anything saying it's a bad idea...but it is a bad idea.

Instead. change your map function to a flatMap (see the first example here: https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/datastream_api.html).

So in your loop, instead of making a kafka producer every loop, you just do collector.collect(recordToPublishToKafka).

And your sink will publish each out as they are collected.

Body:
Writing to kafka topic from within a map function (SCALA) ?

Reading from a kafka topic in a FLINK Application

Processing the data within a map function

Problem Statement - Within the map function I am looping through a list. For each element in the list I want to publish to a kafka topic.

when I get the output from the map and sink it works, but if I try a push to topic from within map method it doesn't

Is it possible to publish to topic from within a map method

// Main Function
def main(args: Array[String]) {

...
// some list
val list_ = ("a", "b", "c", "d")
// Setup Properties
val props = new Properties()
props.setProperty("zookeeper.connect", zookeeper_url + ":" + zookeeper_port)
props.setProperty("bootstrap.servers", broker_url + ":" + broker_port)
props.setProperty("auto.offset.reset", "earliest")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

...

// Connect to Source
val input_stream = env.addSource(new FlinkKafkaConsumer09[String](topic_in, new SimpleStringSchema(), properties))

// Process each Record
val stream = input_stream.map(x=> {

  // loop through list "list_" -> variable in in Main
  // and publish to topic_out
  // -- THIS IS MY CURRENT ISSUE !!!)
  // -- Does not work (No compile issue)
  //
  var producer2 = new KafkaProducer[String, String](props)
  var record    = new ProducerRecord(topic_out, "KEY", list(i))
  producer2.send(record)
  producer2.flush()

 // ... Other process and return processed string

})

// publish to different topic of proccessed input string (Works)
stream.addSink(new FlinkKafkaProducer09[String](broker_url + ":" + broker_port, other_topic, new SimpleStringSchema()))


问:
Objective-C: Read specific buffer size from URL
I need to download large files from a URL asynchronously and fill a buffer (for example 4096 bytes) to a specific size before processing the data.  It would be great to use a built-in object such as NSURLConnection but I am having some problems.

With NSURLConnection, the didReceiveData:data message decides when to fire on its own.  For example, I might receive 954 bytes the first time and subsequently 1048 bytes until it's done downloading.  Is there anyway I can modify NSURLConnection to force it to read to the buffer size I need before firing the receive message?

I also looked into using the CFNetwork classes, but this seems alot more difficult and would like to avoid it if possible.

Additionally I might be able to accomplish this by using the well known AsyncSocket class, but then I'd have to parse HTTP headers and I have a feeling more issues would come up down the line with other web server configurations.

Thank you in advance.

答:
With NSURLConnection you have to read the data into your own buffer anyway (e.g. an NSData object).  So why not just read from that buffer every 4096 bytes?

It sounds like you're only interested in processing the data as it arrives, and not in keeping all of it.  So perhaps you could do something like this whenever you receive data (pseudocode):

```<code>while buffer.size > 4096:
  copy first 4096 bytes into separate buffer
  process separate buffer
  delete first 4096 bytes from buffer
</code>```

And then process whatever is left (if necessary) when the connection closes.

Body:
With NSURLConnection you have to read the data into your own buffer anyway (e.g. an NSData object).  So why not just read from that buffer every 4096 bytes?

It sounds like you're only interested in processing the data as it arrives, and not in keeping all of it.  So perhaps you could do something like this whenever you receive data (pseudocode):

while buffer.size > 4096:
  copy first 4096 bytes into separate buffer
  process separate buffer
  delete first 4096 bytes from buffer

And then process whatever is left (if necessary) when the connection closes.


问:
Unable to remote debug gdbserver over serial port
I'm trying to remote debug using gdbserver.

I connect my target device to my PC through USB port using this command to open terminal controlling my device :

minicom -D "/dev/ttyUSB0".

Now on my target device, I need to run gdbserver with this cmd:

gdbserver /dev/my_USB_serial_port my_Program.

However, I can't find ttyUSB0, all I got ís a bunch of ttyx(with x is a number) as below:

```<code>~ # /dev/tty
tty    tty14  tty20  tty27  tty33  tty4   tty46  tty52  tty59  tty8
tty0   tty15  tty21  tty28  tty34  tty40  tty47  tty53  tty6   tty9
tty1   tty16  tty22  tty29  tty35  tty41  tty48  tty54  tty60  ttyS0
tty10  tty17  tty23  tty3   tty36  tty42  tty49  tty55  tty61  ttyS1
tty11  tty18  tty24  tty30  tty37  tty43  tty5   tty56  tty62
tty12  tty19  tty25  tty31  tty38  tty44  tty50  tty57  tty63
tty13  tty2   tty26  tty32  tty39  tty45  tty51  tty58  tty7
</code>```

How could I find which one is the correct serial port of my USB port ?

Update 1: As Employed Russian mentioned in the answer, I got confused about the USB port but I still couldn't connect to gdbserver using his command.

答:
However, I can't find ttyUSB0

You are confused -- of course you will not find ttyUSB0 on the target -- the target doesn't have anything plugged into its USB port.

On the target, you want to run gdbserver - my_Program &, then disconnect minicom, and finally use gdb and target remote /dev/ttyUSB0 on the host.

Body:
I'm trying to remote debug using gdbserver.

I connect my target device to my PC through USB port using this command to open terminal controlling my device :

minicom -D "/dev/ttyUSB0".

Now on my target device, I need to run gdbserver with this cmd:

gdbserver /dev/my_USB_serial_port my_Program.

However, I can't find ttyUSB0, all I got ís a bunch of ttyx(with x is a number) as below:

~ # /dev/tty
tty    tty14  tty20  tty27  tty33  tty4   tty46  tty52  tty59  tty8
tty0   tty15  tty21  tty28  tty34  tty40  tty47  tty53  tty6   tty9
tty1   tty16  tty22  tty29  tty35  tty41  tty48  tty54  tty60  ttyS0
tty10  tty17  tty23  tty3   tty36  tty42  tty49  tty55  tty61  ttyS1
tty11  tty18  tty24  tty30  tty37  tty43  tty5   tty56  tty62
tty12  tty19  tty25  tty31  tty38  tty44  tty50  tty57  tty63
tty13  tty2   tty26  tty32  tty39  tty45  tty51  tty58  tty7

How could I find which one is the correct serial port of my USB port ?

Update 1: As Employed Russian mentioned in the answer, I got confused about the USB port but I still couldn't connect to gdbserver using his command.


问:
Displaying a final price as currency format and reading from file in java
I'm nearly finished with a program I've been writing for quite some time for a school final assignment.  It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.

I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.

There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).

Here's my code.  Any help is appreciated.

```<code>    package dessertshop;

import java.text.NumberFormat;
import java.util.Scanner;

abstract class DessertItem
{
   protected String name;

   public DessertItem()
   {
      this.name = "";
   }

   public DessertItem( String name )
   {
      this.name = name;
   }

   public final String getName()
   {
      return name;
   }

   public abstract double getCost(int number);
}

class Candy extends DessertItem
{
   private double pricePerPound;

   public Candy( String name, double unitPrice )
   {
      super( name );
      this.pricePerPound = unitPrice;
   }

   @Override
   public double getCost(int amount)
   {
      return( amount * pricePerPound );
   }

   public String toString()
   {
      NumberFormat   formatter = NumberFormat.getCurrencyInstance();
      return( "Candy\t" + name + "\t @ " + formatter.format( this.pricePerPound ) + " per pound");
   }
}

class Cookie extends DessertItem
{
    private double pricePerDozen;

    public Cookie(String name, double pricePerDozen)
    {
        super(name);
        this.pricePerDozen=pricePerDozen;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * pricePerDozen)/12;
    }

    public String toString()
    {
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        return( "Cookie\t" + name + "\t @ " + formatter.format( this.pricePerDozen) + " per dozen");
    }
}

class IceCream extends DessertItem
{
    private double cost;

    public IceCream(String name, double cost)
    {
        super(name);
        this.cost=cost;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * cost);
    }

    public String toString()
    {
        NumberFormat   formatter = NumberFormat.getCurrencyInstance();
        return( "Ice Cream\t" + name + "\t @ " + formatter.format( this.cost ) + " per scoop");
    }
}

public class DessertShop
{
    private String name = "";
    private DessertItem[] menu;
    private int numberOfItems = 0;

    public DessertShop(String name)
    {
        this.name = name;
        menu = new DessertItem[200];
    }
    public DessertShop()
    {
        menu = new DessertItem[200];
    }

    public void addToMenu(DessertItem item)
    {
        menu[numberOfItems++] = item;
    }

    public void printMenu()
    {
        System.out.println(this.toString());
        for (int i = 0; i < numberOfItems; i++)
        {
            System.out.print((i + 1) + ": " + menu[i].toString());
            System.out.println("");
        }
    }

    public double createNewOrder()
    {
        double totalCost = 0;
        Scanner input = new Scanner(System.in);
            while (true)
            {
            this.printMenu();
            System.out.print("What would you like to purchase? (0 to checkout) > ");
            int choice = input.nextInt();
            if (choice == 0)
            {
                break;
            }
            System.out.print("How many (lbs. or amount) > ");
            int amount = input.nextInt();
            totalCost += menu[(choice - 1)].getCost(amount);
            }
        input.close();
        return totalCost;
    }

    public String toString()
    {
        return ("Welcome to " + name);
    }

    public static void main( String[] args )
    {

        DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
        Candy candy01 = new Candy("Reece's Pieces", 3.99);
        Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
        Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
        Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
        Cookie cookie03 = new Cookie("Sugar", 4.50);
        IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
        IceCream icecream02 = new IceCream("Vanilla", 2.00);
        IceCream icecream03 = new IceCream("Caramel", 3.50);
        IceCream icecream04 = new IceCream("Rocky Road", 2.99);
        IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
        shop01.addToMenu(candy01);
        shop01.addToMenu(candy02);
        shop01.addToMenu(cookie01);
        shop01.addToMenu(cookie02);
        shop01.addToMenu(cookie03);
        shop01.addToMenu(icecream01);
        shop01.addToMenu(icecream02);
        shop01.addToMenu(icecream03);
        shop01.addToMenu(icecream04);
        shop01.addToMenu(icecream05);

        double frankOrder = shop01.createNewOrder();

        System.out.println(frankOrder);
    }
}
</code>```

答:
If you don't want to hassle too much, you can get decent result with printf:

```<code>System.out.printf("Price is: €%,d", 12342353563623L);
</code>```

Output is: Price is: €12,342,353,563,623

Formatter on "," flag:

The result will include locale-specific grouping separators

Body:
I'm nearly finished with a program I've been writing for quite some time for a school final assignment.  It's 99% complete, but I'd like to add a couple things to make it as perfect as possible and need help.

I'd like to display the final price of an order in currency format, but have only figured out a way to format as currency if it's in my tostring method.

There's also bonus points to be had with this if I create a method that creates an order from a file. (ex: orders 1 Reece's Pieces, 6 sugar cookies, 1 chocolate chip cookie, and 1 scoop of caramel ice cream).

Here's my code.  Any help is appreciated.

    package dessertshop;

import java.text.NumberFormat;
import java.util.Scanner;

abstract class DessertItem
{
   protected String name;

   public DessertItem()
   {
      this.name = "";
   }

   public DessertItem( String name )
   {
      this.name = name;
   }

   public final String getName()
   {
      return name;
   }

   public abstract double getCost(int number);
}

class Candy extends DessertItem
{
   private double pricePerPound;

   public Candy( String name, double unitPrice )
   {
      super( name );
      this.pricePerPound = unitPrice;
   }

   @Override
   public double getCost(int amount)
   {
      return( amount * pricePerPound );
   }

   public String toString()
   {
      NumberFormat   formatter = NumberFormat.getCurrencyInstance();
      return( "Candy\t" + name + "\t @ " + formatter.format( this.pricePerPound ) + " per pound");
   }
}

class Cookie extends DessertItem
{
    private double pricePerDozen;

    public Cookie(String name, double pricePerDozen)
    {
        super(name);
        this.pricePerDozen=pricePerDozen;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * pricePerDozen)/12;
    }

    public String toString()
    {
        NumberFormat formatter = NumberFormat.getCurrencyInstance();
        return( "Cookie\t" + name + "\t @ " + formatter.format( this.pricePerDozen) + " per dozen");
    }
}

class IceCream extends DessertItem
{
    private double cost;

    public IceCream(String name, double cost)
    {
        super(name);
        this.cost=cost;
    }

    @Override
    public double getCost(int amount)
    {
        return(amount * cost);
    }

    public String toString()
    {
        NumberFormat   formatter = NumberFormat.getCurrencyInstance();
        return( "Ice Cream\t" + name + "\t @ " + formatter.format( this.cost ) + " per scoop");
    }
}

public class DessertShop
{
    private String name = "";
    private DessertItem[] menu;
    private int numberOfItems = 0;

    public DessertShop(String name)
    {
        this.name = name;
        menu = new DessertItem[200];
    }
    public DessertShop()
    {
        menu = new DessertItem[200];
    }

    public void addToMenu(DessertItem item)
    {
        menu[numberOfItems++] = item;
    }

    public void printMenu()
    {
        System.out.println(this.toString());
        for (int i = 0; i < numberOfItems; i++)
        {
            System.out.print((i + 1) + ": " + menu[i].toString());
            System.out.println("");
        }
    }

    public double createNewOrder()
    {
        double totalCost = 0;
        Scanner input = new Scanner(System.in);
            while (true)
            {
            this.printMenu();
            System.out.print("What would you like to purchase? (0 to checkout) > ");
            int choice = input.nextInt();
            if (choice == 0)
            {
                break;
            }
            System.out.print("How many (lbs. or amount) > ");
            int amount = input.nextInt();
            totalCost += menu[(choice - 1)].getCost(amount);
            }
        input.close();
        return totalCost;
    }

    public String toString()
    {
        return ("Welcome to " + name);
    }

    public static void main( String[] args )
    {

        DessertShop shop01 = new DessertShop("Chuck D's Dessert Depot");
        Candy candy01 = new Candy("Reece's Pieces", 3.99);
        Candy candy02 = new Candy("Chocolate Covered Raisins", 4.99);
        Cookie cookie01 = new Cookie("Peanut Butter", 5.99);
        Cookie cookie02 = new Cookie("Chocolate Chip", 4.99);
        Cookie cookie03 = new Cookie("Sugar", 4.50);
        IceCream icecream01 = new IceCream("Cookie Dough", 3.00);
        IceCream icecream02 = new IceCream("Vanilla", 2.00);
        IceCream icecream03 = new IceCream("Caramel", 3.50);
        IceCream icecream04 = new IceCream("Rocky Road", 2.99);
        IceCream icecream05 = new IceCream("Mint Chocolate Chip", 3.99);
        shop01.addToMenu(candy01);
        shop01.addToMenu(candy02);
        shop01.addToMenu(cookie01);
        shop01.addToMenu(cookie02);
        shop01.addToMenu(cookie03);
        shop01.addToMenu(icecream01);
        shop01.addToMenu(icecream02);
        shop01.addToMenu(icecream03);
        shop01.addToMenu(icecream04);
        shop01.addToMenu(icecream05);

        double frankOrder = shop01.createNewOrder();

        System.out.println(frankOrder);
    }
}

Body:
If you don't want to hassle too much, you can get decent result with printf:

System.out.printf("Price is: €%,d", 12342353563623L);

Output is: Price is: €12,342,353,563,623

Formatter on "," flag:

The result will include locale-specific grouping separators