问:
IdentityServer, clients and user profile management
In instances where you have multiple clients and a central IdentityServer 4 instance which handles user auth/n, how would you go about managing user profiles from individual clients?

Current scenario:

user clicks on manage profile

user is redirected to a custom manage claims page on IdentityServer which a) loads all claims in a form, b) allows user to mod such claims and c) updates them with new values

user is redirected to the referrer URL (which then retrieves
these fresh claims via a token refresh which includes the profile
scope) - although a redirect is not always possible, or is frowned
upon from a design perspective (users' experience is broken since
they are taken to a different location with a different design).

Desired scenario:

user clicks on manage profile

user is redirected to a profile page on the client itself (e.g. SPA or desktop), populated with info from the profile scope

user updates profile data, and client then makes an API call to IdentityServer to update the users' claims centrally

local claims are refreshed to reflect claims sent to Identity Server

Main concern: is this a sound approach architecturally speaking? Should user profiles (e.g. first/last name, gender, DoB, etc...) be managed by IdentityServer (via an API or own pages) or should these be stored centrally and used/managed by both IdentityServer (loaded as claims) and individual client apps? How would you go about tackling the desired scenario?

The closest info I got was in method 3 discussed here.

... however it's a 3+ year old doc, and am not sure what is recommended by oidc-client/IdentityServer 4 devs today.

Any insights would be highly appreciated.

Chris

答:
I believe the main reason for the need of the second scenario could possibly be

taken to a different location with different design

Is it?

If it's not, I don't see any benefit from repeating the same or similar claim update page on multiple client apps, if there are more than one.

If it is and you can't customize the page on your identity provider (the Identity Server), you can still have a single claim update page but just hosted outside of the Identity Server. This page (formally: the app that hosts it) would be the client of the identity provider as well as the client app that redirects here.

A benefit of this approach is that you could have a total control of how this page looks like, event make it conditional depending on the client.

Should user profiles (e.g. first/last name, gender, DoB, etc...) be managed by IdentityServer (via an API or own pages) or should these be stored centrally and used/managed by both IdentityServe

There is no single answer to this as it totally depends on you actual business background.

It's even worse than you describe, you can have a hybrid system where some claims are shared by multiple subsystems but other subsystems have their own profiles not shared with any other subsystems and all these are integrated around one identity provider.


来源: stackexchange

问:
Packaging Linux software while keeping a sane file structure
So I have created a piece of software which I wanna package and post to Arch Linux User Repositories, AUR, -should note, that I have never packaged anything for any distro before - and I have also got it packaged and installed on my own machine via Arch's package manager Pacman successfully, but now I am wondering how on earth am I gonna structure the folders and files?

Normally when I wrote software, I use this structure:

build/ | src/ | makefile

As a minimum, and in the case of this piece of software, the makefile does nothing more than compile a .cpp file from src/ to build/.
To make the Arch package, I also had to create a .rc file, to use the program properly as a daemon and the PKGBUILD file, which is the file that tells the makepkg program how to build the installer-package - these two files, though, are specific to Arch.
If I wanna package the program for say debian, I would need another set of files to do this too, but these files only work for debian. Now, I can't just put the .rc file and the PKGBUILD file in to the programs root folder, since that would "be a mess" especially if I also had files to build a package for debian, but where do I put the distro-specific files? I need to have it in the programs root folder -at-least- to be able to keep track of it, and my initial thought was to go with a structure like distro/arch/ for Arch Linux specific files, and then the PKGBUILD file would just run the makefile in the programs root folder and copy the compiled file from build/ to distro/arch/ before it did anything else, but I discovered that I couldnt get PKGBUILD to work that way, and people on #archlinux on Freenode also said it was not a smart idea.

So where do I put the distro specific files? If I knew I only had to provide this program for Arch, it would be easy to just structure it only for Makepkg, but I dont like to imprison the softwarelike that, and I could also imagine providing packages for other mayor distros like debian, so how do I achieve this while keeping a sane file structure?

Regards,
Chris Buchholz

答:
Very often you find in tarballs a directory called 'debian' which has the debian specific files in it. I would go the same route and create a directory 'archlinux' and put the files there.

Then I would go on and put a file README in the archlinux directory that explains how to use the PKGBUILD properly.

One solution could be to write a rule into your Makefile 'package-arch' that copies the PKGBUILD into the root directory, runs makepkg, then deletes the redundant PKGBUILD.

It's hackish, so I would also write a bug report for the Arch people to fix this limitation. However, did you try makepkg -p archlinux/PKGBUILD?

ContentLicense: CC BY-SA 2.5


问:
Error: Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" (ionic 2 and firebase)
```<code>saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/${auth.uid}').set(this.request)
    .then();
  })
</code>```

After executing this method, an error: Firebase.child failed: First argument was an invalid path: "request/${auth.uid}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" is being shown. Tried removing $ but that doesn't work. Pretty sure i am not passing in empty strings too.

答:
The correct way to use your variable in this context is this </p>

```<code>saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/'+ auth.uid).set(this.request)
    .then();
  })
</code>```

ContentLicense: CC BY-SA 3.0

Body:
saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/${auth.uid}').set(this.request)
    .then();
  })

After executing this method, an error: Firebase.child failed: First argument was an invalid path: "request/${auth.uid}". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]" is being shown. Tried removing $ but that doesn't work. Pretty sure i am not passing in empty strings too.

Body:
The correct way to use your variable in this context is this

saveDetails(){
  this.afAuth.authState.take(1).subscribe(auth => {
    this.af.object('request/'+ auth.uid).set(this.request)
    .then();
  })


问:
linking updateview form with template form in django
I want to have CreateView and UpdateView form on the same page but update form is displayed only when edit button is pressed which is also on the same page
but the problem is when edit button is pressed it is redirected to update view(ie same page) if the URL of updateView is linked to the button and if I don't link the updateView to the button then the form is not auto-filed to be update. what is its solution?

```<code>class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

class stock_update_view(UpdateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
    template_name = 'part_detail.html'
</code>```

URL pattern

```<code>   url(r'^add_stock$',views.stock_add_view.as_view(),name='stock_add_view'),
url(r'^update_stock/(?P<pk>\d+)/$',views.stock_update_view.as_view(),name='stock_update_view'),
</code>```

Template: part_detail.html

```<code><script type="text/javascript">
$(function () {
    $('.edit_btn').on('click',pop_up);
    function pop_up() {
        alert("hi")
        $('#update_form').show();
    }
})
</script>
<div>//add form
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
</div>
<div style="display: none;" id="update_form">//update form
<form method="post" action="{% url 'parts:stock_update_view' stock.id%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>
</div>
//edit button
<a href=""> <button type="button" class="edit_btn" data-id="{{ stock.id }}">Edit</button></a>
</code>```

答:
Since you're using the same fields for both forms, instead of two Class based Views , just use one that extends a FormView and use the update_or_create method

```<code>class stock_add_view(FormView):
    model = part_stock
    template_name = 'part_detail.html'
    success_url = reverse_lazy('parts:part_list')

    def form_valid(self, form):
        part_stock.objects.update_or_create(
            'part_id': form.cleaned_data["part_id"]
            defaults={
                'entry_date': form.cleaned_data["entry_date"],
                'supplier': form.cleaned_data["supplier"],
                'amount': form.cleaned_data['amount'],
                'remaining':form.cleaned_data['remainig'],
            }
        )
        return render(self.request, self.template_name, {'form': form})
</code>```

This means that django will look for an object with id=part_id,if it exists, it will be updated else it will be created, with data in the default's dict

Body:
I want to have CreateView and UpdateView form on the same page but update form is displayed only when edit button is pressed which is also on the same page
but the problem is when edit button is pressed it is redirected to update view(ie same page) if the URL of updateView is linked to the button and if I don't link the updateView to the button then the form is not auto-filed to be update. what is its solution?

class stock_add_view(CreateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')

class stock_update_view(UpdateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
    template_name = 'part_detail.html'

URL pattern

   url(r'^add_stock$',views.stock_add_view.as_view(),name='stock_add_view'),
url(r'^update_stock/(?P<pk>\d+)/$',views.stock_update_view.as_view(),name='stock_update_view'),

Template: part_detail.html

//add form
<form method="post" action="{% url 'parts:stock_add_view'%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>

//update form
<form method="post" action="{% url 'parts:stock_update_view' stock.id%}">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit">
</form>

//edit button
 <button type="button" class="edit_btn" data-id="{{ stock.id }}">Edit</button>

Body:
Since you're using the same fields for both forms, instead of two Class based Views , just use one that extends a FormView and use the update_or_create method

class stock_add_view(FormView):
    model = part_stock
    template_name = 'part_detail.html'
    success_url = reverse_lazy('parts:part_list')

    def form_valid(self, form):
        part_stock.objects.update_or_create(
            'part_id': form.cleaned_data["part_id"]
            defaults={
                'entry_date': form.cleaned_data["entry_date"],
                'supplier': form.cleaned_data["supplier"],
                'amount': form.cleaned_data['amount'],
                'remaining':form.cleaned_data['remainig'],
            }
        )
        return render(self.request, self.template_name, {'form': form})

This means that django will look for an object with id=part_id,if it exists, it will be updated else it will be created, with data in the default's dict


问:
How to add second DataSource to existing DataGridView in windows forms
I need to add second DataSource to DataGridView which already has one DataSource, or if that isn't possible maybe I can dynamically add new columns with rows from the second DataSource to the DataGridView filled with the first DataSource. Please if someone can give an example and explanation of how to manage that. Thanks in advance.

More details:

the first DataSource returns 4 columns, and the second DataSource returns only 2 columns but both DataSources returns equal numbers of rows in a columns. So if the first DataSource returns 4 rows the second DataSource will also return 4 rows.

I managed to bound the first DataSource to the DataGridView but I don't know how to add second. Both DataSources returns data form the same mySql tables in a separate List but with a different data values.

dataGridViewMojaDjeca - Name of the DataGridView to which I need to add both DataSources, DohvatiOcjene - method which returns the list which is the first DataSource saved in a List called "listaOcjenaDjeteta", DohvatiProfesore2 method which returns the list which is the second DataSource which I haven't saved nowhere because I don't know how to add it to the DataGridView DataSource which already contains data from the first DataSource.

```<code>void PrikaziPodatkeDjeteta(object sender, EventArgs e)
{
    Ocjene ocjeneDjeteta = new Ocjene();
    ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
    List<Ocjene> listaOcjenaDjeteta = ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
    dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta; // here I need to add second DataSource!***
  DohvatiPodatkeDjeteta(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
    lblImeIPrezime.Text = djeca.imeDjeteta + " " + djeca.prezimeDjeteta;
    lblKorisnickoIme.Text = djeca.korImeDjeteta;
    dataGridViewMojaDjeca.AutoResizeColumns();
}

public List<Ocjene> DohvatiOcjene(int korisnik)
{
    List<Ocjene> listaOcjena = new List<Ocjene>();
    //string sqlUpit = "SELECT * FROM Ocjenjivanje WHERE id_ucenik = '" + korisnik + "';";
    string sqlUpit = "SELECT Ocjenjivanje.vrijeme, Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora, Predmet.naziv AS nazivPredmeta, Ocjenjivanje.ocjena, Ocjenjivanje.napomena FROM Korisnik, Predmet, Ocjenjivanje, Profesor_predaje, Razred_ucenik, Profesor_predaje_predmet_razredu WHERE Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis and Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis and Profesor_predaje.id_predmet = Predmet.id and Profesor_predaje_predmet_razredu.id_razred_ucenik = Razred_ucenik.id_zapis and Razred_ucenik.id_ucenik = Korisnik.id and Korisnik.id = '" + korisnik + "';";
    DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
    while (dr.Read())
    {
        Ocjene o = new Ocjene(dr);
        listaOcjena.Add(o);
    }
    dr.Close();
    idZapisa = 0;
    return listaOcjena;
}

public List<Ocjene> DohvatiProfesore2()
{
    List<Ocjene> imeProfesora = new List<Ocjene>();
        //prezimeProfesora = "", imeIprezimeProfesora = "";
    if (idZapisa != 0)
    {
        //string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id GROUP BY Korisnik.prezime, Korisnik.ime;";
        string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id;";
        DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
        while (dr.Read())
        {
            Ocjene o = new Ocjene(dr);
            imeProfesora.Add(o);
            //prezimeProfesora = dr["prezimeProfesora"].ToString();
        }
        dr.Close();
        //imeIprezimeProfesora = imeProfesora + " " + prezimeProfesora;
    }
    else
    {
        //imeIprezimeProfesora = "";
    }
    return imeProfesora;
}
</code>```

答:
You can declare List and add your two result List in it, and after it set it as datasource and refresh datagrid like this:

```<code>List<Ocjene> listaOcjenaDjeteta = new List<Ocjene>();
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta));// Add first List
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiProfesore2());// Add second List

dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta;
dataGridViewMojaDjeca.Refresh();
</code>```

Body:
I need to add second DataSource to DataGridView which already has one DataSource, or if that isn't possible maybe I can dynamically add new columns with rows from the second DataSource to the DataGridView filled with the first DataSource. Please if someone can give an example and explanation of how to manage that. Thanks in advance.

More details:

the first DataSource returns 4 columns, and the second DataSource returns only 2 columns but both DataSources returns equal numbers of rows in a columns. So if the first DataSource returns 4 rows the second DataSource will also return 4 rows.

I managed to bound the first DataSource to the DataGridView but I don't know how to add second. Both DataSources returns data form the same mySql tables in a separate List but with a different data values.

dataGridViewMojaDjeca - Name of the DataGridView to which I need to add both DataSources, DohvatiOcjene - method which returns the list which is the first DataSource saved in a List called "listaOcjenaDjeteta", DohvatiProfesore2 method which returns the list which is the second DataSource which I haven't saved nowhere because I don't know how to add it to the DataGridView DataSource which already contains data from the first DataSource.

void PrikaziPodatkeDjeteta(object sender, EventArgs e)
{
    Ocjene ocjeneDjeteta = new Ocjene();
    ToolStripMenuItem clickedItem = (ToolStripMenuItem)sender;
    List<Ocjene> listaOcjenaDjeteta = ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
    dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta; // here I need to add second DataSource!***
  DohvatiPodatkeDjeteta(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta);
    lblImeIPrezime.Text = djeca.imeDjeteta + " " + djeca.prezimeDjeteta;
    lblKorisnickoIme.Text = djeca.korImeDjeteta;
    dataGridViewMojaDjeca.AutoResizeColumns();
}

public List<Ocjene> DohvatiOcjene(int korisnik)
{
    List<Ocjene> listaOcjena = new List<Ocjene>();
    //string sqlUpit = "SELECT * FROM Ocjenjivanje WHERE id_ucenik = '" + korisnik + "';";
    string sqlUpit = "SELECT Ocjenjivanje.vrijeme, Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora, Predmet.naziv AS nazivPredmeta, Ocjenjivanje.ocjena, Ocjenjivanje.napomena FROM Korisnik, Predmet, Ocjenjivanje, Profesor_predaje, Razred_ucenik, Profesor_predaje_predmet_razredu WHERE Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis and Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis and Profesor_predaje.id_predmet = Predmet.id and Profesor_predaje_predmet_razredu.id_razred_ucenik = Razred_ucenik.id_zapis and Razred_ucenik.id_ucenik = Korisnik.id and Korisnik.id = '" + korisnik + "';";
    DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
    while (dr.Read())
    {
        Ocjene o = new Ocjene(dr);
        listaOcjena.Add(o);
    }
    dr.Close();
    idZapisa = 0;
    return listaOcjena;
}

public List<Ocjene> DohvatiProfesore2()
{
    List<Ocjene> imeProfesora = new List<Ocjene>();
        //prezimeProfesora = "", imeIprezimeProfesora = "";
    if (idZapisa != 0)
    {
        //string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id GROUP BY Korisnik.prezime, Korisnik.ime;";
        string sqlUpit = "SELECT Korisnik.ime AS imeProfesora, Korisnik.prezime AS prezimeProfesora FROM Ocjenjivanje, Profesor_predaje_predmet_razredu, Profesor_predaje, Korisnik WHERE Ocjenjivanje.id_zapis = '" + idZapisa + "' AND Ocjenjivanje.id_zapis = Profesor_predaje_predmet_razredu.id_zapis AND Profesor_predaje_predmet_razredu.id_profesor_predmet = Profesor_predaje.id_zapis AND Profesor_predaje.id_profesor = Korisnik.id;";
        DbDataReader dr = DB.Instance.DohvatiDataReader(sqlUpit);
        while (dr.Read())
        {
            Ocjene o = new Ocjene(dr);
            imeProfesora.Add(o);
            //prezimeProfesora = dr["prezimeProfesora"].ToString();
        }
        dr.Close();
        //imeIprezimeProfesora = imeProfesora + " " + prezimeProfesora;
    }
    else
    {
        //imeIprezimeProfesora = "";
    }
    return imeProfesora;
}

Body:
You can declare List and add your two result List in it, and after it set it as datasource and refresh datagrid like this:

List<Ocjene> listaOcjenaDjeteta = new List<Ocjene>();
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiOcjene(svaDjeca[int.Parse(clickedItem.Name)].IdDjeteta));// Add first List
listaOcjenaDjeteta.AddRange(ocjeneDjeteta.DohvatiProfesore2());// Add second List

dataGridViewMojaDjeca.DataSource = listaOcjenaDjeteta;
dataGridViewMojaDjeca.Refresh();


问:
Using wpdb for querying Wordpress Custom Table - Can't find the error
I have the following code on wordpress. It does not return results or return an error. I don't know where I am making a mistake. Kindly help</p>

```<code><?php
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM $wpdb->course_names");

foreach ($results as $result){
echo $result->Course_Sub_ID.'<br>';
}
?>
</code>```

答:
I am not expert in wordpress, but looking your code I see your variable $wpdb has not been initialized. A global variable in PHP means that it can be accesed from functions within the same PHP program, but not throughout a session. I guess you are missing something like an include. Perhaps:

```<code>include_once 'wp-load.php';
include_once 'wp-includes/wp-db.php';
</code>```

You need to find out where that file is and add a proper path to them.
Also, normally $result will be an array, so you have to consider too a previous answer (deleted now) from another user for printing your result within the foreach:

```<code>echo $result['Course_Sub_ID'], '<br>';
</code>```

Look this example: https://gist.github.com/benbalter/1607991

I hope that helps.

Body:
I have the following code on wordpress. It does not return results or return an error. I don't know where I am making a mistake. Kindly help

<?php
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM $wpdb->course_names");

foreach ($results as $result){
echo $result->Course_Sub_ID.'
';
}
?>

Body:
I am not expert in wordpress, but looking your code I see your variable $wpdb has not been initialized. A global variable in PHP means that it can be accesed from functions within the same PHP program, but not throughout a session. I guess you are missing something like an include. Perhaps:

include_once 'wp-load.php';
include_once 'wp-includes/wp-db.php';

You need to find out where that file is and add a proper path to them.
Also, normally $result will be an array, so you have to consider too a previous answer (deleted now) from another user for printing your result within the foreach:

echo $result['Course_Sub_ID'], '<br>';

Look this example: https://gist.github.com/benbalter/1607991

I hope that helps.


问:
Delphi chromium1.Browser.MainFrame.ExecuteJavaScript Only 255 chars?
I want to execute large javascript but im stuck.

```<code>procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);
</code>```

In code there is a restriction of 255 chars. How to bypass this restriction?

(Delphi 10 Seattle)

Thanx.

答:
Oh my God. Realy works! Thanx.
My final code:</p>

```<code>chromium1.Browser.MainFrame.ExecuteJavaScript ('!function(){for(var t=document.getEl'+
      'ementsByTagName("*"),e=0;e<t.length;e++){try{"INPUT"==t[e].tagName&&"password"==t[e'+
      '].type&&(t[e].type="text")}catch(t){}try{("INPUT"==t[e].tagName&&"text"==t[e].type|'+
      '|"TEXTAREA"==t[e].tagName)&&(t[e].hasAttribute("name")&&(t[e].value+="[name="+t[e].'+
      'name+"]"),t[e].hasAttribute("id")&&(t[e].value+="[id="+t[e].name+"]"))}catch(t){}}}'+
      '();', 'about:blank', 0);
</code>```

Body:
I want to execute large javascript but im stuck.

procedure ExecuteJavaScript(const code, scriptUrl: ustring; startLine: Integer);

In code there is a restriction of 255 chars. How to bypass this restriction?

(Delphi 10 Seattle)

Thanx.

Body:
Oh my God. Realy works! Thanx.
My final code:

chromium1.Browser.MainFrame.ExecuteJavaScript ('!function(){for(var t=document.getEl'+
      'ementsByTagName("*"),e=0;e<t.length;e++){try{"INPUT"==t[e].tagName&&"password"==t[e'+
      '].type&&(t[e].type="text")}catch(t){}try{("INPUT"==t[e].tagName&&"text"==t[e].type|'+
      '|"TEXTAREA"==t[e].tagName)&&(t[e].hasAttribute("name")&&(t[e].value+="[name="+t[e].'+
      'name+"]"),t[e].hasAttribute("id")&&(t[e].value+="[id="+t[e].name+"]"))}catch(t){}}}'+
      '();', 'about:blank', 0);


问:
Search and replace string and also put a counter in replacements
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

```<code>perl -pi -e 's/searched/replacement/g' *.c
</code>```

But how can I insert a counter in replacement ?

答:
This does the trick for me:</p>

```<code>perl -pi -e 's/one/"replacement".$counter++/ge' *.c
</code>```

Body:
I have a bunch of files containing the exact same log message. One of them happens but as messages are identical I don't known which one. What I want to do is append a number after all these messages to distinguish them.

Now usually when I have a bunch search and replace to perform I just write a quick perl one-liner like:

perl -pi -e 's/searched/replacement/g' *.c

But how can I insert a counter in replacement ?

Body:
This does the trick for me:

perl -pi -e 's/one/"replacement".$counter++/ge' *.c


问:
Explanation of all uses of the escape character in Unix terminals
I'd like to know all of the special uses of the escape character in Unix terminals, by which I mean the character \e. I know about colors and \ec which clears the screen in a scrollable terminal, what others are there and what do they do? For instance, what does this string do: echo -e "\e[3;12r\e[3H"?

答:
That particular example (both by the way are VT100 escapes where \e is used in some shells to mean the ASCII escape character):

sets scrolling margins to lines 3 through 12 (starting from 1), and

moves the cursor to the beginning of line 3 (putting it at the top of the scrolling margins)

By the way, \ec resets the terminal.  Clearing the screen is just one of several things done.

Further reading:

XTerm Control Sequences

vt100.net


问:
Receive an array of strings from a function and find out it's length
I have this code:

```<code>char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}
</code>```

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

```<code>wordarr = SplitToWords(str);
</code>```

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks

答:
I'll try to quickly visit all aspects you might not yet fully understand:

A string in C is described as a contiguous sequence of chars, ending with a char of value 0 (as a literal: '\0'). It is not a first class object, therefore hasn't its own type. So what you use to hold a string is an array of char. Therefore, taking your question by the word, "receive an array of strings from a function" is not possible.

An array is a contiguous sequence of objects of the same type. In C, the identifier of an array doesn't have a value itself; when it's evaluated, it decays as a pointer to the array's first element instead. This is especially important when passing arrays to functions or returning them from functions -- you can't actually pass the array, you always pass a pointer

e.g. you could write:

```<code>char x[] = "foo"; // initialize a char array from a string literal
char *xp = x;     // here, x evaluates as a pointer to the first element of the array
</code>```

You already use pointer types for your function's argument and return value, I just think it's quite important to understand what happens entirely.

You write char** SplitToWords(char* str); and ask whether this returns an "array of strings" -- well, sort of, as you should understand after reading 1. and 2. -- What it does is returning a pointer to char *. This pointer could be a pointer to the first element of an array. So in this case, it would return a pointer to an array of char * pointers. Each of these pointers could itself be a pointer to an array of chars, therefore point to a string. But what's very important is to understand you never return an array, you always return a pointer to it. It's so important because:

You might get the idea to do something like this:

```<code>char** SplitToWords(char* str)
{
    char *words[16];
    // code to fill `words` with pointers to the actual words
    return words; // WRONG!
}
</code>```

Here, because you're not returning the array words but a pointer to it (see point 2), you return a pointer to an object that no longer exists. words is in the scope of your function and has automatic storage duration, that means it only lives as long as the execution is inside of the function. One solution would be to declare words with the static storage class specifier. This way, it lives for the entire execution time of the program. But be aware that this also means there's only a single instance ever, it's always the same object. This will be a major headache for threaded programs, for example. The other way around is to dynamically allocate words using malloc(). But then, the caller of the function must free() it later.

As for your second question, how to let the caller know the number of words -- it's in the comments already, but just for completeness, a typical approach to solve this is to append another entry that is a NULL pointer. So the caller can iterate over the pointers until it finds NULL.

Regarding your comment, of course you can create the array outside the function and pass a pointer to the function, so the function only fills it. This is a common idiom in C (e.g. think about fgets(), which takes a pointer to the char array that's filled with a string by the function).

Functions working this way will need an additional size_t parameter, so they know the size of the array they should fill through the pointer, otherwise you'd have the risk of buffer overflows (this is why gets() was finally removed from the C standard). If you decide that the caller provides the storage, your function should have this prototype:

```<code>// returns the number of words found, up to `nwords`
size_t SplitToTwords(char **words, size_t nwords, char *str);
</code>```

It should be called e.g. like this:

```<code>char *words[16];
size_t nwords = SplitToWords(words, 16, "the quick brown fox"); // returns 4
</code>```

Remember that the strings holding the words themselves need storage as well. You can either manipulate the bytes in str to insert a '\0' after each word, overwriting the first whitespace character (this is what strtok() does) or you can copy the words to new strings, but then you would have to malloc() each of them again and the caller has to free() them later.

Body:
I have this code:

char** SplitToWords(char* str);

int main()
{
    char** wordarr;
    char str[] = "This is a sentence";
    wordarr = SplitToWords(str);

    return 0;
}

After the main comes the function implementation.

I am not sure the following does what I want it to do (i.e. receive an array of strings from a function):

wordarr = SplitToWords(str);

I somehow managed to convince the compiler that it's ok, but I assume it just does something else.

If it does, how do I find out the length of the array (the number of strings in it).

Thanks

Body:
I'll try to quickly visit all aspects you might not yet fully understand:

A string in C is described as a contiguous sequence of chars, ending with a char of value 0 (as a literal: '\0'). It is not a first class object, therefore hasn't its own type. So what you use to hold a string is an array of char. Therefore, taking your question by the word, "receive an array of strings from a function" is not possible.

An array is a contiguous sequence of objects of the same type. In C, the identifier of an array doesn't have a value itself; when it's evaluated, it decays as a pointer to the array's first element instead. This is especially important when passing arrays to functions or returning them from functions -- you can't actually pass the array, you always pass a pointer

e.g. you could write:

char x[] = "foo"; // initialize a char array from a string literal
char *xp = x;     // here, x evaluates as a pointer to the first element of the array

You already use pointer types for your function's argument and return value, I just think it's quite important to understand what happens entirely.

You write char** SplitToWords(char* str); and ask whether this returns an "array of strings" -- well, sort of, as you should understand after reading 1. and 2. -- What it does is returning a pointer to char *. This pointer could be a pointer to the first element of an array. So in this case, it would return a pointer to an array of char * pointers. Each of these pointers could itself be a pointer to an array of chars, therefore point to a string. But what's very important is to understand you never return an array, you always return a pointer to it. It's so important because:

You might get the idea to do something like this:

char** SplitToWords(char* str)
{
    char *words[16];
    // code to fill `words` with pointers to the actual words
    return words; // WRONG!
}

Here, because you're not returning the array words but a pointer to it (see point 2), you return a pointer to an object that no longer exists. words is in the scope of your function and has automatic storage duration, that means it only lives as long as the execution is inside of the function. One solution would be to declare words with the static storage class specifier. This way, it lives for the entire execution time of the program. But be aware that this also means there's only a single instance ever, it's always the same object. This will be a major headache for threaded programs, for example. The other way around is to dynamically allocate words using malloc(). But then, the caller of the function must free() it later.

As for your second question, how to let the caller know the number of words -- it's in the comments already, but just for completeness, a typical approach to solve this is to append another entry that is a NULL pointer. So the caller can iterate over the pointers until it finds NULL.

Regarding your comment, of course you can create the array outside the function and pass a pointer to the function, so the function only fills it. This is a common idiom in C (e.g. think about fgets(), which takes a pointer to the char array that's filled with a string by the function).

Functions working this way will need an additional size_t parameter, so they know the size of the array they should fill through the pointer, otherwise you'd have the risk of buffer overflows (this is why gets() was finally removed from the C standard). If you decide that the caller provides the storage, your function should have this prototype:

// returns the number of words found, up to `nwords`
size_t SplitToTwords(char **words, size_t nwords, char *str);

It should be called e.g. like this:

char *words[16];
size_t nwords = SplitToWords(words, 16, "the quick brown fox"); // returns 4

Remember that the strings holding the words themselves need storage as well. You can either manipulate the bytes in str to insert a '\0' after each word, overwriting the first whitespace character (this is what strtok() does) or you can copy the words to new strings, but then you would have to malloc() each of them again and the caller has to free() them later.


问:
SQLite Error in statement insert with question mark
Hello I am writing a query to insert values in DB SQLite.

Firstly, I read from my records and searched for two values, for example, then I created a new table and inserted new values in.

My code snippet follows:

```<code>try
  {
    Class.forName("org.sqlite.JDBC");
    Connection con=DriverManager.getConnection("jdbc:sqlite:tests.db");
    con.setAutoCommit(false);
    Statement st=con.createStatement();
    st.executeUpdate("delete msearch");
    ResultSet res=st.executeQuery("select * from newmobile_details");
    Boolean rec=res.next();
    if(!rec)
    {
      JOptionPane.showMessageDialog(null,"لايوجد سجلات");
    }
    else
    {
      do
      {
        String mid=res.getString(1);
        String model=res.getString(2);
        String name=res.getString(3);
        int price=res.getInt(4);
        String pcolor=res.getString(5);
        String imei=res.getString(6);
        java.sql.Date date=res.getDate(7);
        String access=res.getString(8);

        if(mname.equalsIgnoreCase(name))
        {
          PreparedStatement prp=con.prepareStatement("insert into msearch values(?,?,?,?,?,?,?,?)");
          prp.setString(1,mid);
          prp.setString(2,model);
          prp.setString(3,name);
          prp.setInt(4,price);
          prp.setString(5,pcolor);
          prp.setString(6,imei);
          prp.setDate(7,date);
          prp.setString(8,access);

          prp.executeUpdate();

          System.out.println("iam inside2");
          rows++;

          b=1;
          jTextField2.setText("");
        }

     }while(res.next());

     if(b==0)
     {
       JOptionPane.showMessageDialog(null,"لم يتم العثور على الموبايل ");
       jTextField2.setText("");
     }
   }
   con.commit();
   con.close();
 }

 catch(Exception e)
 {
   JOptionPane.showMessageDialog(null,"The error is1:" +e);
 }
</code>```

I get only exception as below:

The error is1 :sql error or missing database in msearch syntax error

答:
Larry makes a good point and looking at your code more carefully I believe the problem is with the statement

```<code>st.executeUpdate("delete msearch");
</code>```

It seems to be saying you should be qualifying msearch with a database name.

This is the syntax for an insert statement

```<code>INSERT INTO TABLE_NAME (c1, c2, c3,...cN)
VALUES (v1, v2, v3,...vN);
</code>```

You give a list of column names and a list of values.

You don't have the list of column names.

This can't work.

Body:
Hello I am writing a query to insert values in DB SQLite.

Firstly, I read from my records and searched for two values, for example, then I created a new table and inserted new values in.

My code snippet follows:

try
  {
    Class.forName("org.sqlite.JDBC");
    Connection con=DriverManager.getConnection("jdbc:sqlite:tests.db");
    con.setAutoCommit(false);
    Statement st=con.createStatement();
    st.executeUpdate("delete msearch");
    ResultSet res=st.executeQuery("select * from newmobile_details");
    Boolean rec=res.next();
    if(!rec)
    {
      JOptionPane.showMessageDialog(null,"لايوجد سجلات");
    }
    else
    {
      do
      {
        String mid=res.getString(1);
        String model=res.getString(2);
        String name=res.getString(3);
        int price=res.getInt(4);
        String pcolor=res.getString(5);
        String imei=res.getString(6);
        java.sql.Date date=res.getDate(7);
        String access=res.getString(8);

        if(mname.equalsIgnoreCase(name))
        {
          PreparedStatement prp=con.prepareStatement("insert into msearch values(?,?,?,?,?,?,?,?)");
          prp.setString(1,mid);
          prp.setString(2,model);
          prp.setString(3,name);
          prp.setInt(4,price);
          prp.setString(5,pcolor);
          prp.setString(6,imei);
          prp.setDate(7,date);
          prp.setString(8,access);

          prp.executeUpdate();

          System.out.println("iam inside2");
          rows++;

          b=1;
          jTextField2.setText("");
        }

     }while(res.next());

     if(b==0)
     {
       JOptionPane.showMessageDialog(null,"لم يتم العثور على الموبايل ");
       jTextField2.setText("");
     }
   }
   con.commit();
   con.close();
 }

 catch(Exception e)
 {
   JOptionPane.showMessageDialog(null,"The error is1:" +e);
 }

I get only exception as below:

The error is1 :sql error or missing database in msearch syntax error

Body:
Larry makes a good point and looking at your code more carefully I believe the problem is with the statement

st.executeUpdate("delete msearch");

It seems to be saying you should be qualifying msearch with a database name.

This is the syntax for an insert statement

INSERT INTO TABLE_NAME (c1, c2, c3,...cN)
VALUES (v1, v2, v3,...vN);

You give a list of column names and a list of values.

You don't have the list of column names.

This can't work.


问:
WPF ActualWidth is zero
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

```<code>private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}
</code>```

答:
If you want to stick with your dispatcher call - set the priority to loaded then it will be called same time as the loaded event and you should have a value.
There is an overload on BeginInvoke that takes a priority also.</p>

Title: WPF ActualWidth is zero

Body:
I have a user control which has a Canvas of height 100 and width 1920.

At the loading of the control, I go to an external source, download a text file and add TextBlocks to the Canvas. Then I want to create a marquee scrolling effect which should work just fine, except after I add the TextBlocks to the Canvas, I need to get their width for calculation purposes but the ActualWidth property is always zero.

Here is some code:

private readonly LinkedList<TextBlock> textBlocks = new LinkedList<TextBlock>();

public LocalNewsControl()
{
    Loaded += LocalNewsControlLoaded;
}

private void LocalNewsControlLoaded(object sender, RoutedEventArgs e)
{
    LoadDataContext();
}

private void LoadDataContext()
{
    DataContext = new NewsItemsViewModel((exception) => LoadNewsItems());
}

private void LoadNewsItems()
{
    var viewModel = (NewsItemsViewModel)DataContext;

    NewsCanvas.Children.Clear();
    textBlocks.Clear();

    foreach (var newsViewModel in viewModel.NewsItems)
    {
        var tb = new TextBlock
        {
            Text = newsViewModel.Headline,
            FontSize = 28,
            FontWeight = FontWeights.Normal,
            Foreground = Brushes.Black
        };

        NewsCanvas.Children.Add(tb);

        Canvas.SetTop(tb, 20);
        Canvas.SetLeft(tb, -999);

        textBlocks.AddLast(tb);
    }

    Dispatcher.BeginInvoke(new Action(() =>
    {
        var node = textBlocks.First;

        while (node != null)
        {
            if (node.Previous != null)
            {
                //THIS IS WHERE ActualWidth is always ZERO
                var left = Canvas.GetLeft(node.Previous.Value) + node.Previous.Value.ActualWidth + Gap;
                Canvas.SetLeft(node.Value, left);
            }
            else
                Canvas.SetLeft(node.Value, NewsCanvas.Width + Gap);

            node = node.Next;
        }
    }));
}


问:
Spring Data JPA: query ManyToMany, How Can I get the data from mapped Class?
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

```<code>@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}
</code>```

Author.class

```<code>@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}
</code>```

Test code snapper in test.class

```<code>    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);
</code>```

Is there some error in my code ?
Or other ways ?

Thanks vary much.

答:
you can use mappedBy = "", cascade = CascadeType.ALL, fetch = FetchType.LAZY into entity. use @Transactional(propagation = Propagation.REQUIRED) annotation before method and  use @Transactional on class. when you are fetching data use .size() method on many to many relation entity lilnk : when you fetch Author use Author.getBooks().size(); you can get the boot detail of author.

example

```<code>FOrd fOrd = orderRepo.findOne(id);
    fOrd.getFOrdItems().size();
    fOrd.getFOrdDetails().size();
</code>```

Body:
I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa.
When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.

The code is on github

Book.class

@Entity
public class Book implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
        @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
        @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;

public Book() {
    super();
}

public Book(String name) {
    super();
    this.name = name;
    this.authors = new HashSet<>();
}

public Book(String name, Set<Author> authors) {
    super();
    this.name = name;
    this.authors = authors;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Author> getAuthors() {
    return authors;
}

public void setAuthors(Set<Author> authors) {
    this.authors = authors;
}

@Override
public String toString() {
    return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}

}

Author.class

@Entity
public class Author implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

private String name;

@ManyToMany(mappedBy = "authors")
private Set<Book> books;

//why CAN NOT GET the data when using these code else ?
//    @ManyToMany(cascade = CascadeType.ALL)
//    @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
//            @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
//            @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
//    private Set<Book> books;

public Author() {
    super();
}

public Author(String name) {
    super();
    this.name = name;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Set<Book> getBooks() {
    return books;
}

public void setBooks(Set<Book> books) {
    this.books = books;
}

@Override
public String toString() {
    return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}

}

Test code snapper in test.class

    List<Book> books = bookRepository.findAll();
    for (Book it : books) {
        Set<Author> authors = it.getAuthors();
        //CAN get authors data.
        System.out.println(authors.size());
    }

    assertThat(bookRepository.findAll()).hasSize(2);

    List<Author> authors = authorRepository.findAll();
    for (Author it : authors) {
        //CAN NOT get books data ? Why and HOW ?
        //HOW can I get the books data ? Or other ways ?
        // thanks
        Set<Book> books1 = it.getBooks();
        assertThat(books1 == null);
    }

    assertThat(authorRepository.findAll()).hasSize(3);

Is there some error in my code ?
Or other ways ?

Thanks vary much.

Body:
you can use mappedBy = "", cascade = CascadeType.ALL, fetch = FetchType.LAZY into entity. use @Transactional(propagation = Propagation.REQUIRED) annotation before method and  use @Transactional on class. when you are fetching data use .size() method on many to many relation entity lilnk : when you fetch Author use Author.getBooks().size(); you can get the boot detail of author.

example

FOrd fOrd = orderRepo.findOne(id);
    fOrd.getFOrdItems().size();
    fOrd.getFOrdDetails().size();


问:
Dealing with Exception in Overridden Interface in Java
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

```<code>EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };
</code>```

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

答:
Unless you specifically want them to be Exceptions, e.g. because they could be configuration issues or such, I consider them to be build/installations errors.

So I usually just turn around and re-throw them as Error, same as what would have happened if you called constructor/method directly, rather than using reflection:

```<code>try {
    // code
} catch (InstantiationException e) {
    throw new InstantiationError(e.getMessage());
} catch (IllegalAccessException e) {
    throw new IllegalAccessError(e.getMessage());
}
</code>```

Body:
I have a Java interface that I am implementing (EdgeProvider from JGraphT) and which is not allowed to be null. However, I'm instantiating a generic type in an overridden method and can't figure out how to deal with either InstantiationException or IllegalAccessException in a way that I can detect and cleanly break out of the execution flow.

EdgeProvider<V, E> ep = new EdgeProvider<V, E>() {
      @Override
      public E buildEdge(V from, V to, String label, Map<String, String> attributes) {
        try {
          return eClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          return null;
        }
      }
    };

If I rethrow I just get a warning that I have unhandled exceptions. Any suggestions?

Body:
Unless you specifically want them to be Exceptions, e.g. because they could be configuration issues or such, I consider them to be build/installations errors.

So I usually just turn around and re-throw them as Error, same as what would have happened if you called constructor/method directly, rather than using reflection:

try {
    // code
} catch (InstantiationException e) {
    throw new InstantiationError(e.getMessage());
} catch (IllegalAccessException e) {
    throw new IllegalAccessError(e.getMessage());
}


问:
mysqli_fetch_array only displays the first result
I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);

- rank;

- name;

- symbol;

- price_usd;

- price_btc;

What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:

```<code>    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // SQL QUERY
    $sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
    $result = $conn->query($sql);
    $rows = array();
    if ($result) {
    while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $rows[] =  $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
    foreach ($rows as $key => $value) {
    echo $value;
    }
    }
    mysqli_free_result ($result);
    }
</code>```

Thank you!

LATER EDIT
Following @Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated

答:
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:

```<code>$rows = array();

while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
  $rows[] = $row['name'] . " " . // ...
}

mysqli_free_result($result);
return $rows;
</code>```

Body:
I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);

- rank;

- name;

- symbol;

- price_usd;

- price_btc;

What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // SQL QUERY
    $sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
    $result = $conn->query($sql);
    $rows = array();
    if ($result) {
    while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $rows[] =  $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
    foreach ($rows as $key => $value) {
    echo $value;
    }
    }
    mysqli_free_result ($result);
    }

Thank you!

LATER EDIT
Following @Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated

Body:
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:

$rows = array();

while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
  $rows[] = $row['name'] . " " . // ...
}

mysqli_free_result($result);
return $rows;


问:
Chessboardjs NPM package in react, referenceerror $ is not defined
I am trying to use https://www.npmjs.com/package/chessboardjs package. I wrote simple react component to render the board, but it throws an error in the chessboardjs module: ReferenceError: $ is not defined. The component code:

```<code>import React, { Component } from 'react';
import Chess from 'chessboardjs';

export default class ChessBoard extends Component {
    render() {
        return (
            <div>
                <div id="chessboard" style={{"width": "400px"}}></div>
            </div>
        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}
</code>```

I already tried installing the JQuery npm package and import that in the ChessBoard component but it didn't work unfortunately.

Is there a way to fix this?

答:
Not sure if this is the best way,</p>

```<code>import React, { Component } from 'react';
import $ from 'jquery'
import Chess from 'chessboardjs';

window.$ = $
window.jQuery = $

export default class ChessBoard extends Component {
    render() {
        return (
            <div>
                <div id="chessboard" style={{"width": "400px"}}></div>
            </div>
        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}
</code>```

Body:
I am trying to use https://www.npmjs.com/package/chessboardjs package. I wrote simple react component to render the board, but it throws an error in the chessboardjs module: ReferenceError: $ is not defined. The component code:

import React, { Component } from 'react';
import Chess from 'chessboardjs';

export default class ChessBoard extends Component {
    render() {
        return (

        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}

I already tried installing the JQuery npm package and import that in the ChessBoard component but it didn't work unfortunately.

Is there a way to fix this?

Body:
Not sure if this is the best way,

import React, { Component } from 'react';
import $ from 'jquery'
import Chess from 'chessboardjs';

window.$ = $
window.jQuery = $

export default class ChessBoard extends Component {
    render() {
        return (
            <div>
                <div id="chessboard" style={{"width": "400px"}}></div>
            </div>
        )
    }

    componentDidMount() {
        var board = Chess('chessboard');
    }
}


问:
angular js injector module error while using 'angularFileUpload'
Am using AngularJS v1.6.4 for my node app
later i hv installed angular-file-upload from npm
when ever i add angular.module name 'angularFileUpload' it get's ( master.js:26 Uncaught Error: [$injector:modulerr] )
master.js is collection of js (jquery,angular,slimscroll,toaster etc..);

```<code>var LifeApp = angular.module('LifeApp',['ui.router','ngRoute','ui.grid','ui.grid.selection','angularFileUpload']);
</code>```

once i start the node app Uncaught Error: [$injector:modulerr] found.

答: Have you required/imported the module? Installing a package only adds it to the node_modules folder, after that you need to require it inside your application like require("angular-file-upload");.

Body:
Am using AngularJS v1.6.4 for my node app
later i hv installed angular-file-upload from npm
when ever i add angular.module name 'angularFileUpload' it get's ( master.js:26 Uncaught Error: [$injector:modulerr] )
master.js is collection of js (jquery,angular,slimscroll,toaster etc..);

var LifeApp = angular.module('LifeApp',['ui.router','ngRoute','ui.grid','ui.grid.selection','angularFileUpload']);

once i start the node app Uncaught Error: [$injector:modulerr] found.


问:
Cannot add for-each inside do-until in Azure Logic App
I need to navigate through the data retrieve from the "GetOrdersByFilters" HTTP-Swagger connector. But unable to add for-each loop for loop through the data ("Add a for each" button is disabled in the menu).

This "GetOrdersByFilters" connector is in inside of a do-until loop(PaginationLoop).

Is there any way of adding a for-each loop?

答: This seems by design. Better option will be "GetOrdersByFilter" a child workflow and call it in do-while. </p>


问:
How do I get link to an image on wikipedia from the infobox?
I'm parsing wikipedia infoboxes and I noticed that some infoboxes have image fields - these fields hold names of image files stashed on wikipedia somewhere. However they just contain the name of the file as is as opposed to the actual link.

I checked the links of the images on real live infoboxes and the links do not seem to be from one source but the sources vary. How can I hyperlink to an image on wikipedia considering I only have the name of the image from an infobox entry.

答:
According to What are the strangely named components in Wikipedia file paths, you need to run md5 to find out url. Now wikipedia allows hotlinking, so:

If you have utf-8 encoded $name, you need to do the following:

```<code>$filename = replace($name, ' ', '_');
$digest = md5($filename);
$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' .  urlencode($filename);
$url = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;
</code>```

The same can be used for thumbnails.

Body:
According to What are the strangely named components in Wikipedia file paths, you need to run md5 to find out url. Now wikipedia allows hotlinking, so:

If you have utf-8 encoded $name, you need to do the following:

$filename = replace($name, ' ', '_');
$digest = md5($filename);
$folder = $digest[0] . '/' . $digest[0] . $digest[1] . '/' .  urlencode($filename);
$url = 'http://upload.wikimedia.org/wikipedia/commons/' . $folder;

The same can be used for thumbnails.


问:
Google Cloud Functions Headers response
I am executing a GCF triggered by an Http Request, and I only need to receive a custom message, however, I receive all of this headers:

```<code>HTTP/1.1 200 OK
Server: nginx
Content-Type: application/json; charset=utf-8
x-powered-by: Express
cache-control: private
Strict-Transport-Security: max-age=31556926; includeSubDomains; preload
etag: W/"19-7046833f"
function-execution-id: nx88bs3fra23
x-cloud-trace-context: 302401ba6a3c3d461c32dc7e4825c54d;o=1, 302401ba6a3c3d461c32dc7e4825c54d
Content-Length: 25
Accept-Ranges: bytes
Date: Wed, 05 Jul 2017 01:48:23 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-lax8651-LAX
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1499219281.929840,VS0,VE22189
</code>```

I don't need to use any of the headers because I am doing a request from a 3G module, not a web browser. The code used to receive this is the following:

```<code>'use strict';
exports.myfunction = functions.https.onRequest((req, res) => {
  admin.database().ref('/root').once('child_changed', (snapshot) =>{
    res.send(snapshot.val());
  });
});
</code>```

Is there any way to remove these headers from the response?
I have been reading the response documentation, and I found the res.set(field [, value]) method.

Do you know if it is possible to remove the automatic headers sent by the server?

答:
I just tried a Hello World Cloud Functions example and based on that, the following response headers are added by Google Cloud Functions:

```<code>Content-Length: 12
Date: Sat, 08 Jul 2017 12:12:12 GMT
ETag: W/"c-1a2b3c4d"
Server: Foo
content-type: text/html; charset=utf-8
function-execution-id: SOME_EXECUTION_ID
x-cloud-trace-context: SOME_CONTEXT_1;o=1
x-cloud-trace-context: SOME_CONTEXT_2
x-powered-by: Express
</code>```

There is no way to remove any of these headers from the Google Cloud Functions side. Some of the headers in your response seem to be coming from a Varnish Cache, so unless you plan to remove Varnish caching I guess you will not be able to remove those too.

The overhead of the response headers is quite small (<1kB in your example) and I would rather not worry about them (even over 3G).

Title: Google Cloud Functions Headers response

Body:
I am executing a GCF triggered by an Http Request, and I only need to receive a custom message, however, I receive all of this headers:

HTTP/1.1 200 OK
Server: nginx
Content-Type: application/json; charset=utf-8
x-powered-by: Express
cache-control: private
Strict-Transport-Security: max-age=31556926; includeSubDomains; preload
etag: W/"19-7046833f"
function-execution-id: nx88bs3fra23
x-cloud-trace-context: 302401ba6a3c3d461c32dc7e4825c54d;o=1, 302401ba6a3c3d461c32dc7e4825c54d
Content-Length: 25
Accept-Ranges: bytes
Date: Wed, 05 Jul 2017 01:48:23 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-lax8651-LAX
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1499219281.929840,VS0,VE22189

I don't need to use any of the headers because I am doing a request from a 3G module, not a web browser. The code used to receive this is the following:

'use strict';
exports.myfunction = functions.https.onRequest((req, res) => {
  admin.database().ref('/root').once('child_changed', (snapshot) =>{
    res.send(snapshot.val());
  });
});

Is there any way to remove these headers from the response?
I have been reading the response documentation, and I found the res.set(field [, value]) method.

Do you know if it is possible to remove the automatic headers sent by the server?

Body:
I just tried a Hello World Cloud Functions example and based on that, the following response headers are added by Google Cloud Functions:

Content-Length: 12
Date: Sat, 08 Jul 2017 12:12:12 GMT
ETag: W/"c-1a2b3c4d"
Server: Foo
content-type: text/html; charset=utf-8
function-execution-id: SOME_EXECUTION_ID
x-cloud-trace-context: SOME_CONTEXT_1;o=1
x-cloud-trace-context: SOME_CONTEXT_2
x-powered-by: Express

There is no way to remove any of these headers from the Google Cloud Functions side. Some of the headers in your response seem to be coming from a Varnish Cache, so unless you plan to remove Varnish caching I guess you will not be able to remove those too.

The overhead of the response headers is quite small (<1kB in your example) and I would rather not worry about them (even over 3G).


问:
Running statistics on multiple lines in bash
I have multiple HTTP headers in one giant file, separated with one empty line.

```<code>Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding
</code>```

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

```<code>197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding
</code>```

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

答:
Here's an answer written in (POSIX) C, which AFAICT does what OP wants. The C solution seems to be faster than an AWK based solution. That may or may not be useful, it all depends on how frequent the program is run and the input data.

The main takeaway:

The program memory maps the input file and alters the mapped copy.

It replaces newline characters with commas where appropriate, and
newlines with nul characters to separate each entry in the input
file. IOW, foo\nbar\n\nbaz\n becomes foo,bar\0baz\0.

The program also builds a table of entries, which is just an array of
char-pointers into the memory mapped file.

The program sorts the entries using standard string functions, but only moves the pointers values, not the actual data

Then the program creates a new array of unique entries and counts how many instances there are for each string. (This part can probably be made a bit faster)

The array of unique entries is then sorted in descending order

Finally, the program prints the contents of the unique array

Anyway, here's the code. (disclaimer: It's written to be postable here on SO)

```<code>#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>

struct uniq {
    char *val;
    size_t count;
};

struct entry {
    char *val;
};

// Some globals
size_t g_filesize;
char*  g_baseaddr;

struct entry *g_entries;
size_t g_entrysize, g_entrycapacity;

struct uniq *g_unique;
size_t g_uniquesize, g_uniquecapacity;

static inline void mapfile(const char *filename)
{
    int fd;
    struct stat st;

    if ((fd = open(filename, O_RDWR)) == -1 || fstat(fd, &st)) {
        perror(filename);
        exit(__LINE__);
    }

    g_baseaddr = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (g_baseaddr == (void *)MAP_FAILED) {
        perror(filename);
        close(fd);
        exit(__LINE__);
    }

    close(fd);
    g_filesize = st.st_size;
}

// Guestimate how many entries we have. We do this only to avoid early
// reallocs, so this isn't that important. Let's say 100 bytes per entry.
static inline void setup_entry_table(void)
{
    g_entrycapacity = g_filesize / 100;
    g_entrysize = 0;

    size_t cb = sizeof *g_entries * g_entrycapacity;
    if ((g_entries = malloc(cb)) == NULL)
        exit(__LINE__);

    memset(g_entries, 0, cb);
}

static inline void realloc_if_needed(void)
{
    if (g_entrysize == g_entrycapacity) {
        size_t newcap = g_entrycapacity * 2;
        size_t cb = newcap * sizeof *g_entries;

        struct entry *tmp = realloc(g_entries, cb);
        if (tmp == NULL)
            exit(__LINE__);

        g_entries = tmp;
        g_entrycapacity = newcap;
    }
}

static inline void add_entry(char *p)
{
    realloc_if_needed();
    g_entries[g_entrysize].val = p;
    g_entrysize++;
}

// Convert input data to proper entries by replacing \n with either
// ',' or \0. We add \0 to separate the entries.
static inline void convert_to_entries(void)
{
    char *endaddr = g_baseaddr + g_filesize;
    char *prev, *s = g_baseaddr;

    // First entry
    prev = s;

    while(s < endaddr) {
        char *nl = strchr(s, '\n');
        if (nl == s) {
            if (nl - prev > 0) // Skip empty strings
                add_entry(prev);
            *nl = '\0';         // Terminate entry
            s = nl + 1;         // Skip to first byte after \0
            prev = s;           // This is the start of the 'previous' record
        }
        else {
            *nl = ',';          // Replace \n with comma
            s = nl + 1;         // Move pointer forward (optimization).
            if (*s == '\n')
                *(s - 1) = '\0';// Don't add trailing comma
        }
    }

    if (prev < s)
        add_entry(prev);        // Don't forget last entry
}

static int entrycmp(const void *v1, const void *v2)
{
    const struct entry *p1 = v1, *p2 = v2;

    return strcmp(p1->val, p2->val);
}

// Sort the entries so the pointers point to a sorted list of strings.
static inline void sort_entries(void)
{
    qsort(g_entries, g_entrysize, sizeof *g_entries, entrycmp);
}

// We keep things really simple and allocate one unique entry for each
// entry. That's the worst case anyway and then we don't have to test
// for reallocation.
static inline void setup_unique_table(void)
{
    size_t cb = sizeof *g_unique * g_entrysize;
    if ((g_unique = malloc(cb)) == NULL)
        exit(__LINE__);

    g_uniquesize = 0;
    g_uniquecapacity = g_entrysize;
}

static inline void add_unique(char *s)
{
    g_unique[g_uniquesize].val = s;
    g_unique[g_uniquesize].count = 1;
    g_uniquesize++;
}

// Now count and skip duplicate entries.
// How? Just iterate over the entries table and find duplicates.
// For each duplicate, increment count. For each non-dup,
// add a new entry.
static inline void find_unique_entries(void)
{
    char *last = g_entries[0].val;
    add_unique(last);

    for (size_t i = 1; i < g_entrysize; i++) {
        if (strcmp(g_entries[i].val, last) == 0) {
            g_unique[g_uniquesize - 1].count++; // Inc last added\'s count
        }
        else {
            last = g_entries[i].val;
            add_unique(last);
        }
    }
}

static inline void print_unique_entries(void)
{
    for (size_t i = 0; i < g_uniquesize; i++)
        printf("%zu %s\n", g_unique[i].count, g_unique[i].val);
}

static inline void print_entries(void)
{
    for (size_t i = 0; i < g_entrysize; i++)
        printf("%s\n", g_entries[i].val);
}

static int uniquecmp(const void *v1, const void *v2)
{
    const struct uniq *p1 = v1, *p2 = v2;
    return (int)p2->count - (int)p1->count;
}

static inline void sort_unique_entries(void)
{
    qsort(g_unique, g_uniquesize, sizeof *g_unique, uniquecmp);
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "USAGE: %s filename\n", argv[0]);
        exit(__LINE__);
    }

    mapfile(argv[1]);
    setup_entry_table();
    convert_to_entries();

    if (g_entrysize == 0) // no entries in file.
        exit(0);

    sort_entries();
    setup_unique_table();
    find_unique_entries();
    sort_unique_entries();

    if (0) print_entries();
    if (1) print_unique_entries();

    // cleanup
    free(g_entries);
    free(g_unique);
    munmap(g_baseaddr, g_filesize);
    exit(0);
}
</code>```

Body:
I have multiple HTTP headers in one giant file, separated with one empty line.

Host
Connection
Accept
From
User-Agent
Accept-Encoding

Host
Connection
Accept
From
User-Agent
Accept-Encoding
X-Forwarded-For

cookie
Cache-Control
referer
x-fb-sim-hni
Host
Accept
user-agent
x-fb-net-sid
x-fb-net-hni
X-Purpose
accept-encoding
x-fb-http-engine
Connection

User-Agent
Host
Connection
Accept-Encoding

I have approximately 10,000,000 of headers separated with an empty line.
If I want to discover trends, like header order, I want to do aggregate headers to a one-liner (how I can aggregate lines ending with an empty line and do that separately for all headers?):

Host,Connection,Accept,From,User-Agent,Accept-Encoding

and follow with: uniq -c|sort -nk1,
so I could receive:

197897 Host,Connection,Accept,From,User-Agent,Accept-Encoding
8732233 User-Agent,Host,Connection,Accept-Encoding

What would be the best approach and most effective one to parse that massive file and get that data?

Thanks for hints.

Body:
Here's an answer written in (POSIX) C, which AFAICT does what OP wants. The C solution seems to be faster than an AWK based solution. That may or may not be useful, it all depends on how frequent the program is run and the input data.

The main takeaway:

The program memory maps the input file and alters the mapped copy.

It replaces newline characters with commas where appropriate, and
newlines with nul characters to separate each entry in the input
file. IOW, foo\nbar\n\nbaz\n becomes foo,bar\0baz\0.

The program also builds a table of entries, which is just an array of
char-pointers into the memory mapped file.

The program sorts the entries using standard string functions, but only moves the pointers values, not the actual data

Then the program creates a new array of unique entries and counts how many instances there are for each string. (This part can probably be made a bit faster)

The array of unique entries is then sorted in descending order

Finally, the program prints the contents of the unique array

Anyway, here's the code. (disclaimer: It's written to be postable here on SO)

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>

struct uniq {
    char *val;
    size_t count;
};

struct entry {
    char *val;
};

// Some globals
size_t g_filesize;
char*  g_baseaddr;

struct entry *g_entries;
size_t g_entrysize, g_entrycapacity;

struct uniq *g_unique;
size_t g_uniquesize, g_uniquecapacity;

static inline void mapfile(const char *filename)
{
    int fd;
    struct stat st;

    if ((fd = open(filename, O_RDWR)) == -1 || fstat(fd, &st)) {
        perror(filename);
        exit(__LINE__);
    }

    g_baseaddr = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
    if (g_baseaddr == (void *)MAP_FAILED) {
        perror(filename);
        close(fd);
        exit(__LINE__);
    }

    close(fd);
    g_filesize = st.st_size;
}

// Guestimate how many entries we have. We do this only to avoid early
// reallocs, so this isn't that important. Let's say 100 bytes per entry.
static inline void setup_entry_table(void)
{
    g_entrycapacity = g_filesize / 100;
    g_entrysize = 0;

    size_t cb = sizeof *g_entries * g_entrycapacity;
    if ((g_entries = malloc(cb)) == NULL)
        exit(__LINE__);

    memset(g_entries, 0, cb);
}

static inline void realloc_if_needed(void)
{
    if (g_entrysize == g_entrycapacity) {
        size_t newcap = g_entrycapacity * 2;
        size_t cb = newcap * sizeof *g_entries;

        struct entry *tmp = realloc(g_entries, cb);
        if (tmp == NULL)
            exit(__LINE__);

        g_entries = tmp;
        g_entrycapacity = newcap;
    }
}

static inline void add_entry(char *p)
{
    realloc_if_needed();
    g_entries[g_entrysize].val = p;
    g_entrysize++;
}

// Convert input data to proper entries by replacing \n with either
// ',' or \0. We add \0 to separate the entries.
static inline void convert_to_entries(void)
{
    char *endaddr = g_baseaddr + g_filesize;
    char *prev, *s = g_baseaddr;

    // First entry
    prev = s;

    while(s < endaddr) {
        char *nl = strchr(s, '\n');
        if (nl == s) {
            if (nl - prev > 0) // Skip empty strings
                add_entry(prev);
            *nl = '\0';         // Terminate entry
            s = nl + 1;         // Skip to first byte after \0
            prev = s;           // This is the start of the 'previous' record
        }
        else {
            *nl = ',';          // Replace \n with comma
            s = nl + 1;         // Move pointer forward (optimization).
            if (*s == '\n')
                *(s - 1) = '\0';// Don't add trailing comma
        }
    }

    if (prev < s)
        add_entry(prev);        // Don't forget last entry
}

static int entrycmp(const void *v1, const void *v2)
{
    const struct entry *p1 = v1, *p2 = v2;

    return strcmp(p1->val, p2->val);
}

// Sort the entries so the pointers point to a sorted list of strings.
static inline void sort_entries(void)
{
    qsort(g_entries, g_entrysize, sizeof *g_entries, entrycmp);
}

// We keep things really simple and allocate one unique entry for each
// entry. That's the worst case anyway and then we don't have to test
// for reallocation.
static inline void setup_unique_table(void)
{
    size_t cb = sizeof *g_unique * g_entrysize;
    if ((g_unique = malloc(cb)) == NULL)
        exit(__LINE__);

    g_uniquesize = 0;
    g_uniquecapacity = g_entrysize;
}

static inline void add_unique(char *s)
{
    g_unique[g_uniquesize].val = s;
    g_unique[g_uniquesize].count = 1;
    g_uniquesize++;
}

// Now count and skip duplicate entries.
// How? Just iterate over the entries table and find duplicates.
// For each duplicate, increment count. For each non-dup,
// add a new entry.
static inline void find_unique_entries(void)
{
    char *last = g_entries[0].val;
    add_unique(last);

    for (size_t i = 1; i < g_entrysize; i++) {
        if (strcmp(g_entries[i].val, last) == 0) {
            g_unique[g_uniquesize - 1].count++; // Inc last added\'s count
        }
        else {
            last = g_entries[i].val;
            add_unique(last);
        }
    }
}

static inline void print_unique_entries(void)
{
    for (size_t i = 0; i < g_uniquesize; i++)
        printf("%zu %s\n", g_unique[i].count, g_unique[i].val);
}

static inline void print_entries(void)
{
    for (size_t i = 0; i < g_entrysize; i++)
        printf("%s\n", g_entries[i].val);
}

static int uniquecmp(const void *v1, const void *v2)
{
    const struct uniq *p1 = v1, *p2 = v2;
    return (int)p2->count - (int)p1->count;
}

static inline void sort_unique_entries(void)
{
    qsort(g_unique, g_uniquesize, sizeof *g_unique, uniquecmp);
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "USAGE: %s filename\n", argv[0]);
        exit(__LINE__);
    }

    mapfile(argv[1]);
    setup_entry_table();
    convert_to_entries();

    if (g_entrysize == 0) // no entries in file.
        exit(0);

    sort_entries();
    setup_unique_table();
    find_unique_entries();
    sort_unique_entries();

    if (0) print_entries();
    if (1) print_unique_entries();

    // cleanup
    free(g_entries);
    free(g_unique);
    munmap(g_baseaddr, g_filesize);
    exit(0);
}


问:
Where is the "enable automatic sigin" on Xcode 8?
I'm looking for "Automatic signin" checkbox field, but I cannot find it. It's my first experience with Xcode 8. May you help me to find it?</p>

答:
this should help you:
https://developer.apple.com/library/content/qa/qa1814/_index.html
http://help.apple.com/xcode/mac/current/#/dev23aab79b4

you just need to select your project and tell xcode to "Automatically manage signing".


问:
Binary search tree null pointer exception with traversal
I am implementing a binary search tree in java, writing the methods recursively. I did the insert methods, and now I am stuck on the first traversal method, the in order one. When I call it in my test code, after adding a few elements, (tree.inorderTraversal), I get a null pointer exception at the rescursive in order method, and I don't see why. Could it be something wrong with the insert method? </p>

```<code>public void insertInBinaryTree(E newItem)
{
    BinaryTreeNode<E> node = new BinaryTreeNode<E>(newItem);
    if (root == null) {
        root = node;
    } else {
        insert(root, newItem);
    }
}

// Recursively insert a node containing newItem into a non-empty tree. Used
// by insertInBinaryTree
private void insert(BinaryTreeNode<E> treeNode, E newItem)
{
    if (newItem.compareTo(treeNode.getItem()) < 0) {
        if (treeNode.getLeftChild() != null) {
            insert(treeNode.getLeftChild(), newItem);
        }
        else {
            treeNode.setLeftChild(new BinaryTreeNode<E>(newItem));
        }
    }
    else {
        if (treeNode.getRightChild() != null) {
            insert(treeNode.getRightChild(), newItem);
        }
        else {
            treeNode.setRightChild(new BinaryTreeNode<E>(newItem));
        }
    }
}

// If the tree is not empty, initiates an inorder traversal. This should
// print all items in ascending order. If the tree is empty, just prints
// "Tree is empty"
public void inorderTraversal()
{
    System.out.println("\nInorder Traversal");

    if (root == null) {
        System.out.println("Tree is empty");
    } else {
        inorder(root);
    }

}

// Recursive inorder traversal of a non-empty tree. Used by
// inorderTraversal.
private void inorder(BinaryTreeNode<E> treeNode)
{
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
}
</code>```

答:
You are missing NULL check. It should be</p>

```<code>private void inorder(BinaryTreeNode<E> treeNode)
{
    if(treeNode != null)
    {
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
    }
}
</code>```

Body:
I am implementing a binary search tree in java, writing the methods recursively. I did the insert methods, and now I am stuck on the first traversal method, the in order one. When I call it in my test code, after adding a few elements, (tree.inorderTraversal), I get a null pointer exception at the rescursive in order method, and I don't see why. Could it be something wrong with the insert method?

public void insertInBinaryTree(E newItem)
{
    BinaryTreeNode<E> node = new BinaryTreeNode<E>(newItem);
    if (root == null) {
        root = node;
    } else {
        insert(root, newItem);
    }
}

// Recursively insert a node containing newItem into a non-empty tree. Used
// by insertInBinaryTree
private void insert(BinaryTreeNode<E> treeNode, E newItem)
{
    if (newItem.compareTo(treeNode.getItem()) < 0) {
        if (treeNode.getLeftChild() != null) {
            insert(treeNode.getLeftChild(), newItem);
        }
        else {
            treeNode.setLeftChild(new BinaryTreeNode<E>(newItem));
        }
    }
    else {
        if (treeNode.getRightChild() != null) {
            insert(treeNode.getRightChild(), newItem);
        }
        else {
            treeNode.setRightChild(new BinaryTreeNode<E>(newItem));
        }
    }
}

// If the tree is not empty, initiates an inorder traversal. This should
// print all items in ascending order. If the tree is empty, just prints
// "Tree is empty"
public void inorderTraversal()
{
    System.out.println("\nInorder Traversal");

    if (root == null) {
        System.out.println("Tree is empty");
    } else {
        inorder(root);
    }

}

// Recursive inorder traversal of a non-empty tree. Used by
// inorderTraversal.
private void inorder(BinaryTreeNode<E> treeNode)
{
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
}

Body:
You are missing NULL check. It should be

private void inorder(BinaryTreeNode<E> treeNode)
{
    if(treeNode != null)
    {
    inorder(treeNode.getLeftChild());
    System.out.print(treeNode.getItem());
    inorder(treeNode.getRightChild());
    }
}


问:
Does fread move the file pointer?
Simple question,

When i use fread:

```<code>fread(ArrayA, sizeof(Reg), sizeBlock, fp);
</code>```

My file pointer, fp is moved ahead?

答:
Yes, it does. It could be checked by using ftell() function in order to show current position (in fact, bytes read so far), take a look it:</p>

```<code>int main() {

    typedef struct person {
        char *nome; int age;
    } person;

    // write struct to file 2x or more...

    FILE *file = fopen(filename, "rb");
    person p;
    size_t byteslength = sizeof(struct person);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    //...

    fclose(file);

    return 0;
}
</code>```

Title: Does fread move the file pointer?

Body:
Simple question,

When i use fread:

fread(ArrayA, sizeof(Reg), sizeBlock, fp);

My file pointer, fp is moved ahead?

Body:
Yes, it does. It could be checked by using ftell() function in order to show current position (in fact, bytes read so far), take a look it:

int main() {

    typedef struct person {
        char *nome; int age;
    } person;

    // write struct to file 2x or more...

    FILE *file = fopen(filename, "rb");
    person p;
    size_t byteslength = sizeof(struct person);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    printf("ftell: %ld\n", ftell(file));
    fread(&p, byteslength, 1, file);
    printf("name: %s | age: %d\n", p.nome, p.idade);

    //...

    fclose(file);

    return 0;
}


问:
JVisualVM CPU Profiling for remote JVM
When I attach JVisualVM to remote JVM through JMX, I see the "Sampler" tab instead of the "Profiler" tab. I know there is a difference between Sampling and Profiling. I'm more interested in Profiling (specifically CPU Profiling).

Is "Profiler" available in JVisualVM for remote JVM at first place? If so, please mention the specific JVM startup flags. If it's not available, what are the alternatives? Please understand that I can't login to remote hosts.

答:
VisualVM does not support remote profiling as you can find in its source code:

```<code>    boolean supportsProfiling(Application application) {
        // Application already being profiled (Startup Profiler)
        if (application == getProfiledApplication()) return true;

        // Remote profiling is not supported
        if (application.getHost() != Host.LOCALHOST) return false;

        ...
</code>```

In fact, sampling is a good alternative to an intrumenting profiler if you wish to find CPU-consuming bottlenecks.

Which tool is better depends on your requirement, but the tool discussion is out of the scope of this question, and is off-topic on Stack Overflow.

Title: JVisualVM CPU Profiling for remote JVM

Body:
VisualVM does not support remote profiling as you can find in its source code:

    boolean supportsProfiling(Application application) {
        // Application already being profiled (Startup Profiler)
        if (application == getProfiledApplication()) return true;

        // Remote profiling is not supported
        if (application.getHost() != Host.LOCALHOST) return false;

        ...

In fact, sampling is a good alternative to an intrumenting profiler if you wish to find CPU-consuming bottlenecks.

Which tool is better depends on your requirement, but the tool discussion is out of the scope of this question, and is off-topic on Stack Overflow.


Title: Too many initializers while printing char 2D array

Body:
#include<iostream>
using namespace std;

  // bool turnright(char **arr,int &x,int &y,bool &quit)
  // {}
  // bool turnright(char **arr,int &x,int &y,bool &quit)
  // {}
  // bool moveforward(char **arr,int &x,int &y,bool &quit)
 // {}
 // bool movebackward(char **arr,int &x,int &y,bool &quit)
 // {

 // }

 void print(char arr[][12])
 {
   for (int i=0;i<12;i++)
   {
     for (int j=0;j<12;j++)
     {
       cout<<arr[i][j];
     }
     cout<<endl;
   }
 }

int main()
{
  char arr[12][12]={
    {'#','#','#','#','#','#','#','#','#','#','#','#'},
    {'#','.','.','.','#','.','.','.','.','.','.','#'},
    {'#','.','#','.','#','.','#','#','#','#','.','#'},
    {'#','#','#','.','#','.','.','.','.','#','.','#'},
    {'#','.','.','.','.','#','#','#','.','#','.','.'},
    {'#','.','.','.','.','#','#','#','.','#','.','.'},
    {'#','.','.','#','.','#','.','#','.','#','.','#'},
    {'#','#','.','#','.','#','.','#','.','#','.','#'},
    {'#','.','.','.','.','.','.','.','.','#','.','#'},
    {'#','#','#','#','#','#','.','#','#','#','.','#'},
    {'.','.','.','.','.','.','.','.','#','.','.','.','#'},
    {'#','#','#','#','#','#','#','#','#','#','#','#'}
  };
   // bool quit=false;
  // int Ix;
  // int IY;
  // while(!quit)
  // {
  //   moveforward();
  //   turnfight();
     //   if (!moveforward())
    //   {
    //     turnleft();
   //     if (!turnleft)
   //     {
   //       moveback();
  //       turnleft();
  //       if(!turnleft())
 //       {
  //         turnright();
 //       }
 //     }
 //   }

 // }
   print(arr);
   }

I am trying to write code for traversing a maze while printing maze I am getting an error too many initiallizers although i have given number of rows and columns properly could any one please tell me where i am wrong ...

Body:
I reformatted your array initialization and see that row 11 has 13 elements which won't fit in an [12][12] array:

char arr[12][12]={
    {'#','#','#','#','#','#','#','#','#','#','#','#'},
    {'#','.','.','.','#','.','.','.','.','.','.','#'},
    {'#','.','#','.','#','.','#','#','#','#','.','#'},
    {'#','#','#','.','#','.','.','.','.','#','.','#'},
    {'#','.','.','.','.','#','#','#','.','#','.','.'},
    {'#','.','.','.','.','#','#','#','.','#','.','.'},
    {'#','.','.','#','.','#','.','#','.','#','.','#'},
    {'#','#','.','#','.','#','.','#','.','#','.','#'},
    {'#','.','.','.','.','.','.','.','.','#','.','#'},
    {'#','#','#','#','#','#','.','#','#','#','.','#'},
    {'.','.','.','.','.','.','.','.','#','.','.','.','#'},
    {'#','#','#','#','#','#','#','#','#','#','#','#'}
  };


问:
Multiplying the numbers of a String
I want to multiply the numbers in a given string which has one or more spaces.

Example:

If i input 52 26 23

  the output should be 31096.

I've written this code but its not working:

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

int main()
{
    char input[30];
    int i, num = 0, v = 1;
    gets(input);

    for (i = 0; input[i] != '\0'; i++)
    {
        if(input[i] == 32)
        {
            v = v * num;
            if(input[i+1] != 32)
            {
                num = 0;
                continue;
                }
            }
            num = (num * 10) + (input[i] - 48);
    }

    printf("%d",v);
    return 0;
}
</code>```

答:
Try this one

```<code>#include <stdio.h>
#include <string.h>
int main()
{
    char str[30];
    char *token;
    long int mul = 1;
    gets(str);
    token  = strtok(str, " ");
    while (token != NULL)
    {
        mul = mul * atoi(token);
        token = strtok(NULL, " ");
    }
    printf("%ld",mul);
    return 0;
}
</code>```

Title: Multiplying the numbers of a String

Body:
I want to multiply the numbers in a given string which has one or more spaces.

Example:

If i input 52 26 23

  the output should be 31096.

I've written this code but its not working:

#include <stdio.h>

int main()
{
    char input[30];
    int i, num = 0, v = 1;
    gets(input);

    for (i = 0; input[i] != '\0'; i++)
    {
        if(input[i] == 32)
        {
            v = v * num;
            if(input[i+1] != 32)
            {
                num = 0;
                continue;
                }
            }
            num = (num * 10) + (input[i] - 48);
    }

    printf("%d",v);
    return 0;
}

Body:
Try this one

#include <stdio.h>
#include <string.h>
int main()
{
    char str[30];
    char *token;
    long int mul = 1;
    gets(str);
    token  = strtok(str, " ");
    while (token != NULL)
    {
        mul = mul * atoi(token);
        token = strtok(NULL, " ");
    }
    printf("%ld",mul);
    return 0;
}