问:
Make processes like a binary tree and make each child do a different thing
I'm doing the following program where I create various processes like they were a binary tree, I want the child from "the left" to do a different thing from the child of the "right" but it's outputting me 2 children at the right or 2 children at the left and I don't want that.

```<code>void slice(int dir){
    if (dir == 1) {
        printf("izq ");
        printf("child pid %d   parent pid %d\n",getpid(),getppid());fflush(stdout);
    }
    else if (dir == 2){
        printf("der ");
        printf("child pid %d   parent pid %d\n",getpid(),getppid());fflush(stdout);
    }
}

void vector(int vector[], int length, int niveles){
    for(int i=1;i<=niveles;i++)
    {
    int error = 0;
pid_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
    child_pid[dir] = fork();
    if (child_pid[dir] == -1) {
        error = 1;
        perror("fork");
    }

    if (child_pid[dir] == 0) {
       // Here is where you place the code the child should execute.
       slice(dir);
       exit(0);
    }
}

for (int dir=0; dir<=1; ++dir) {
    if (child_pid[dir] == -1)
       continue;

    int status;
    pid_t pid = waitpid(child_pid[dir], &status, 0);
    if (pid == -1) {
        error = 1;
        perror("waitpid");
    }
    else if (WIFSIGNALED(status)) {
        error = 1;
        fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(status));
    }
    else if (WEXITSTATUS(status) != 0) {
        error = 1;
        fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(status));
    }
}

if (error)
   exit(1);
   }
}
</code>```

My goal is to call a function for "izq" that does a different thing from "der" while keeping the whole binary tree idea.

答:
Remember that both the parent and the child proceed to execute from the fork, so you need something like the following:

```<code>int error = 0;
pit_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
    child_pid[dir] = fork();
    if (child_pid[dir] == -1) {
        error = 1;
        perror("fork");
    }

    if (child_pid[dir] == 0) {
       // Here is where you place the code the child should execute.
       exit(0);
    }
}

for (int dir=0; dir<=1; ++dir) {
    if (child_pid[dir] == -1)
       continue;

    int status;
    pid_t pid = waitpid(child_pid[dir], &status, 0);
    if (pid == -1) {
        error = 1;
        perror("waitpid");
    }
    else if (WIFSIGNALED(status)) {
        error = 1;
        fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(wstatus));
    }
    else if (WEXITSTATUS(status) != 0) {
        error = 1;
        fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(wstatus));
    }
}

if (error)
   exit(1);
</code>```

Body:
I'm doing the following program where I create various processes like they were a binary tree, I want the child from "the left" to do a different thing from the child of the "right" but it's outputting me 2 children at the right or 2 children at the left and I don't want that.

void slice(int dir){
    if (dir == 1) {
        printf("izq ");
        printf("child pid %d   parent pid %d\n",getpid(),getppid());fflush(stdout);
    }
    else if (dir == 2){
        printf("der ");
        printf("child pid %d   parent pid %d\n",getpid(),getppid());fflush(stdout);
    }
}

void vector(int vector[], int length, int niveles){
    for(int i=1;i<=niveles;i++)
    {
    int error = 0;
pid_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
    child_pid[dir] = fork();
    if (child_pid[dir] == -1) {
        error = 1;
        perror("fork");
    }

    if (child_pid[dir] == 0) {
       // Here is where you place the code the child should execute.
       slice(dir);
       exit(0);
    }
}

for (int dir=0; dir<=1; ++dir) {
    if (child_pid[dir] == -1)
       continue;

    int status;
    pid_t pid = waitpid(child_pid[dir], &status, 0);
    if (pid == -1) {
        error = 1;
        perror("waitpid");
    }
    else if (WIFSIGNALED(status)) {
        error = 1;
        fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(status));
    }
    else if (WEXITSTATUS(status) != 0) {
        error = 1;
        fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(status));
    }
}

if (error)
   exit(1);
   }
}

My goal is to call a function for "izq" that does a different thing from "der" while keeping the whole binary tree idea.

Body:
Remember that both the parent and the child proceed to execute from the fork, so you need something like the following:

int error = 0;
pit_t child_pid[2] = { -1, -1 };
for (int dir=0; dir<=1; ++dir) {
    child_pid[dir] = fork();
    if (child_pid[dir] == -1) {
        error = 1;
        perror("fork");
    }

    if (child_pid[dir] == 0) {
       // Here is where you place the code the child should execute.
       exit(0);
    }
}

for (int dir=0; dir<=1; ++dir) {
    if (child_pid[dir] == -1)
       continue;

    int status;
    pid_t pid = waitpid(child_pid[dir], &status, 0);
    if (pid == -1) {
        error = 1;
        perror("waitpid");
    }
    else if (WIFSIGNALED(status)) {
        error = 1;
        fprintf(stderr, "Child was killed by signal %d\n", WTERMSIG(wstatus));
    }
    else if (WEXITSTATUS(status) != 0) {
        error = 1;
        fprintf(stderr, "Child exited with error %d\n", WEXITSTATUS(wstatus));
    }
}

if (error)
   exit(1);


来源: stackexchange

问:
How can I get the value of a radio button inside a google visualization table
I have a table that I build using a chart wrapper as follows:

```<code>var rightWrapper;
function drawVisualization() {
  rightWrapper = new google.visualization.ChartWrapper({
  "chartType": "Table",
  'dataSourceUrl':'https://docs.google.com/spreadsheets/d/1I3N5DtdXGWFootaOCQM201K_ao2ZPWSWyw9_l7QcwQg/gviz/tq?sheet=User_my_crew&headers=1',
  'containerId':'target_table_div',
  'query':'SELECT A,B,C,D',
  'options': { 'width': 700, 'height': 500, 'allowHtml': true }
  });

  google.visualization.events.addListener(rightWrapper, 'ready', onRightReady);

  rightWrapper.draw();

  function onRightReady() {
    google.visualization.events.addListener(rightWrapper.getChart(), 'select', rightSelectionHandler);
  }

  function rightSelectionHandler() {
    var selection = rightWrapper.getChart().getSelection();
    if (selection.length == 1) {
      var item = selection[0];
      if (item.row != null) {
        alert("selected row " + item.row);
        var value = (rightWrapper.getSnapshot().getDataTable().getValue(item.row,3));
        alert(value);
      }
    }
  }
}
</code>```

And in that column 3, I have html to build radio buttons.  Unfortunately, the actual html is stored, and I don't seem to have a way of polling to find out which radio button is now checked (the getValue listed in the code above always shows me just the html that was used to build the radio buttons, not which one is now "checked").

Unfortunately, it appears any clicks inside that table have to be picked up with the select listener, and the select listener doesn't relay any information beyond the row and column selected.  I tried building in change and click functions, and putting s around my radio buttons, too.  For instance:

```<code>$("#radio").click(function(){  //also tried with .change
  alert("working");
});
</code>```

That never fires, even if I disable my original listener.

So, how can I know what radio button my user selected?

Note: I do need the radio buttons inside the table, as every single row of the table has its own radio buttons to provide me different information on each.

答:
I figured out something that works

I can add a form around my radio buttons with the event.preventdefault code and call a function:

```<code><form name="myForm" onchange="event.preventDefault(); calcForm2(this);">...radiobuttons...</form>
</code>```

Then in my function I do whatever I want with "this".  It comes across as "name=value" so it's pretty easy to split and parse.

ContentLicense: CC BY-SA 4.0

Body:
I have a table that I build using a chart wrapper as follows:

var rightWrapper;
function drawVisualization() {
  rightWrapper = new google.visualization.ChartWrapper({
  "chartType": "Table",
  'dataSourceUrl':'https://docs.google.com/spreadsheets/d/1I3N5DtdXGWFootaOCQM201K_ao2ZPWSWyw9_l7QcwQg/gviz/tq?sheet=User_my_crew&headers=1',
  'containerId':'target_table_div',
  'query':'SELECT A,B,C,D',
  'options': { 'width': 700, 'height': 500, 'allowHtml': true }
  });

  google.visualization.events.addListener(rightWrapper, 'ready', onRightReady);

  rightWrapper.draw();

  function onRightReady() {
    google.visualization.events.addListener(rightWrapper.getChart(), 'select', rightSelectionHandler);
  }

  function rightSelectionHandler() {
    var selection = rightWrapper.getChart().getSelection();
    if (selection.length == 1) {
      var item = selection[0];
      if (item.row != null) {
        alert("selected row " + item.row);
        var value = (rightWrapper.getSnapshot().getDataTable().getValue(item.row,3));
        alert(value);
      }
    }
  }
}

And in that column 3, I have html to build radio buttons.  Unfortunately, the actual html is stored, and I don't seem to have a way of polling to find out which radio button is now checked (the getValue listed in the code above always shows me just the html that was used to build the radio buttons, not which one is now "checked").

Unfortunately, it appears any clicks inside that table have to be picked up with the select listener, and the select listener doesn't relay any information beyond the row and column selected.  I tried building in change and click functions, and putting s around my radio buttons, too.  For instance:

$("#radio").click(function(){  //also tried with .change
  alert("working");
});

That never fires, even if I disable my original listener.

So, how can I know what radio button my user selected?

Note: I do need the radio buttons inside the table, as every single row of the table has its own radio buttons to provide me different information on each.

Body:
I figured out something that works

I can add a form around my radio buttons with the event.preventdefault code and call a function:

<form name="myForm" onchange="event.preventDefault(); calcForm2(this);">...radiobuttons...</form>

Then in my function I do whatever I want with "this".  It comes across as "name=value" so it's pretty easy to split and parse.


问:
Can I import modules from thread in Python?
It all began last night when I was making a script that required 8 or so packages including pygame.mixer which on my computer importing this takes a few seconds.

This meant that before the script even started I had to wait 10 or so seconds for all the imports to load.  Because I want the script to obviously be as fast as possible could I start running the script while getting the imports with something like this:

```<code>import threading

def import_modules():
    import tkinter as tk
    from pygame import mixer
    import json
    import webbrowser
    print('imports finished')

a = threading.Thread(target=import_modules)
a.start()
for i in range(10000):
    print('Getting Modules')
</code>```

So my question is:

Is this considered bad practice and will it cause problems?

If so are there alternatives I could use?

Or is it OK to do this?

答:
I understand this is an old thread but i was looking for a way to minimize the loading time of my application, and wanted the user to see the gui so he can interact with it while other module being imported in background

i have read some answers suggesting a lazy import techniques, which i found complicated "for me", then i stumbled here with a suggest to use threading to import modules in background, then i gave it a shot, and found out it is the most brilliant idea that fits my needs

below is a code for an example gui application using PySimpleGUI which ask the user to enter a url and it will open it in the default browser window, the only module required to do so is webbrowser, so this job could be done while other modules loading

I added comments in this code to explain mostly all parts, hope it will help someone,
tested on python 3.6, windows10.

please note: this is just a dummy code as a showcase.

```<code># import essentials first
import PySimpleGUI as sg
import time, threading

# global variable names to reference to the imported modules, this way will
# solve the problem of importing inside a function local namespace
pg = None
js = None
wb = None

progress = 0  # for our progress bar

def importer():
    # we will simulate a time consuming modules by time.sleep()
    global progress
    progress = 10
    start = time.time()
    global pg, js, wb
    import pygame as pg
    time.sleep(3)
    print(f'done importing pygame mixer in {time.time()-start} seconds')
    progress = 40

    start = time.time()
    import webbrowser as wb
    time.sleep(2)
    print(f'done importing webbrowser in {time.time()-start} seconds')
    progress = 70

    start = time.time()
    import json as js
    time.sleep(10)
    print(f'done importing json in {time.time()-start} seconds')

    progress = 100
    print('imports finished')

# start our importer in a separate thread
threading.Thread(target=importer).start()

# main app
def main():
    # window layout
    layout = [[sg.Text('Enter url:', size=(15,1)), sg.Input(default_text='https://google.com', size=(31, 1), key='url')],
            [sg.Text('Loading modules:', size=(15,1), key='status'),
            sg.ProgressBar(max_value=100, orientation='horizontal', size=(20,10), key='progress')],
            [sg.Button('Open url', disabled=True, key='open_url'), sg.Button('joysticks', disabled=True, key='joysticks'), sg.Cancel()]]
    window = sg.Window('test application for lazy imports', layout=layout) # our window

    while True:  # main application loop
        event, values = window.Read(timeout=10)  # non blocking read from our gui
        if event in [None, 'Cancel']:
            window.Close()
            break

        elif event == 'open_url':
            wb.open(values['url'])
            print('helllooooooooooooo')

        elif event == 'joysticks':
            # show joystics number currently connected
            pg.init()
            n = pg.joystick.get_count()  # Get count of joysticks
            sg.Popup(f'joysticks number currently connected to computer = {n}')

        # open url button is disabled by default and will be enabled once our webbrowser module imported
        if wb:
            window.Element('open_url').Update(disabled= False)

        if pg:
            window.Element('joysticks').Update(disabled= False)

        # progress bar
        window.Element('progress').UpdateBar(progress)
        if progress >= 100:
            window.Element('status').Update('Loading completed', background_color='green')

main()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It all began last night when I was making a script that required 8 or so packages including pygame.mixer which on my computer importing this takes a few seconds.

This meant that before the script even started I had to wait 10 or so seconds for all the imports to load.  Because I want the script to obviously be as fast as possible could I start running the script while getting the imports with something like this:

import threading

def import_modules():
    import tkinter as tk
    from pygame import mixer
    import json
    import webbrowser
    print('imports finished')

a = threading.Thread(target=import_modules)
a.start()
for i in range(10000):
    print('Getting Modules')

So my question is:

Is this considered bad practice and will it cause problems?

If so are there alternatives I could use?

Or is it OK to do this?

Body:
I understand this is an old thread but i was looking for a way to minimize the loading time of my application, and wanted the user to see the gui so he can interact with it while other module being imported in background

i have read some answers suggesting a lazy import techniques, which i found complicated "for me", then i stumbled here with a suggest to use threading to import modules in background, then i gave it a shot, and found out it is the most brilliant idea that fits my needs

below is a code for an example gui application using PySimpleGUI which ask the user to enter a url and it will open it in the default browser window, the only module required to do so is webbrowser, so this job could be done while other modules loading

I added comments in this code to explain mostly all parts, hope it will help someone,
tested on python 3.6, windows10.

please note: this is just a dummy code as a showcase.

# import essentials first
import PySimpleGUI as sg
import time, threading

# global variable names to reference to the imported modules, this way will
# solve the problem of importing inside a function local namespace
pg = None
js = None
wb = None

progress = 0  # for our progress bar

def importer():
    # we will simulate a time consuming modules by time.sleep()
    global progress
    progress = 10
    start = time.time()
    global pg, js, wb
    import pygame as pg
    time.sleep(3)
    print(f'done importing pygame mixer in {time.time()-start} seconds')
    progress = 40

    start = time.time()
    import webbrowser as wb
    time.sleep(2)
    print(f'done importing webbrowser in {time.time()-start} seconds')
    progress = 70

    start = time.time()
    import json as js
    time.sleep(10)
    print(f'done importing json in {time.time()-start} seconds')

    progress = 100
    print('imports finished')

# start our importer in a separate thread
threading.Thread(target=importer).start()

# main app
def main():
    # window layout
    layout = [[sg.Text('Enter url:', size=(15,1)), sg.Input(default_text='https://google.com', size=(31, 1), key='url')],
            [sg.Text('Loading modules:', size=(15,1), key='status'),
            sg.ProgressBar(max_value=100, orientation='horizontal', size=(20,10), key='progress')],
            [sg.Button('Open url', disabled=True, key='open_url'), sg.Button('joysticks', disabled=True, key='joysticks'), sg.Cancel()]]
    window = sg.Window('test application for lazy imports', layout=layout) # our window

    while True:  # main application loop
        event, values = window.Read(timeout=10)  # non blocking read from our gui
        if event in [None, 'Cancel']:
            window.Close()
            break

        elif event == 'open_url':
            wb.open(values['url'])
            print('helllooooooooooooo')

        elif event == 'joysticks':
            # show joystics number currently connected
            pg.init()
            n = pg.joystick.get_count()  # Get count of joysticks
            sg.Popup(f'joysticks number currently connected to computer = {n}')

        # open url button is disabled by default and will be enabled once our webbrowser module imported
        if wb:
            window.Element('open_url').Update(disabled= False)

        if pg:
            window.Element('joysticks').Update(disabled= False)

        # progress bar
        window.Element('progress').UpdateBar(progress)
        if progress >= 100:
            window.Element('status').Update('Loading completed', background_color='green')

main()


问:
what follows after clustering
I am trying to cluster images based on their similarities with SIFT and Affinity Propagation, I did the clustering but I just don't want to visualize the results. How can I test with a random image from the obtained labels? Or maybe there's more to it?

Other than data visualization, I just don't know what follows after clustering. How do I verify the 'clustering'

答:
If you have ground-truth cluster labels, you can measure Jacquad-Index or something in that line to get an error score. Then, you can tweak your distance measure or parameters etc. to minimize the error score. </p>

<p>You can also do some clustering in order to group your data as the divide step in divide-and-conquer algorithms/applications. </p>

Title: what follows after clustering

Body:
If you have ground-truth cluster labels, you can measure Jacquad-Index or something in that line to get an error score. Then, you can tweak your distance measure or parameters etc. to minimize the error score.

You can also do some clustering in order to group your data as the divide step in divide-and-conquer algorithms/applications.


问:
Filter on Date with PowerQuery for first and last day of month
In Excel 2019, using PowerQuery, how would you filter dates such that:

only the rows with only with the 1st day of the month remain?

only the rows with only with the last day of the month remain?

The date is format is: mm/d/yyyy

答:
Found the solution:

For a table with column Date:

Table.SelectRows(#"Filtered Rows", each Date.Day([Date]) = 1)

Table.SelectRows(#"Filtered Rows", each Date.Day([Date]) = EOMONTH([Date]).Day


问:
Linq - how to convert this code to linq
My Linq-fu is not good enough to translate the following into hopefully one or two lines.</p>

```<code> var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });
</code>```

答:
The exact translation would be:

```<code>var errors = ModelState.Keys.Select(k => ModelState[k].Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });
</code>```

Provided ModelState is a Dictionary<TKey,TValue> or similar, you could use the values directly:

```<code>var errors = ModelState.Values.Select(v => v.Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });
</code>```

Title: Linq - how to convert this code to linq

Body:
My Linq-fu is not good enough to translate the following into hopefully one or two lines.

 var errors = new List<string>();
 foreach (var key in ModelState.Keys)
 {
   errors.Add(ModelState[key].Errors.FirstOrDefault().ErrorMessage);
 }

 return Json(new { success = false, errors = errors });

Body:
The exact translation would be:

var errors = ModelState.Keys.Select(k => ModelState[k].Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });

Provided ModelState is a Dictionary<TKey,TValue> or similar, you could use the values directly:

var errors = ModelState.Values.Select(v => v.Errors.First().ErrorMessage);
return Json(new { success = false, errors = errors.ToList() });


问:
Multiple nested elements inside div with fixed height
```<code><div id=“maincontainer”>
    <div>Some data</div>
    <div id = "imagecontainer"> My image is here</div>
    <div id = “button-row”>
        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>
    </div>
</div>
</code>```

My parent div #maincontainer has fixed height - 200 px and width.
It is probably not a good practice to make height fixed, however, this is required for me to resolve another issue.

How can I make all child elements to fit into this container?

Before setting the size to 200 px, all child elements fitted well into #maincontainer. However, after setting fixed height, I can see that my #imagecontainer and #button-row overflowing my parent container.

Do I need to set height to all child elements?

What if I have multiple nested child containers inside of my main container?

答:
You could make it a flex container;

```<code>.maincontainer{
  display: flex;
  flex-flow: column nowrap;
}
</code>```

Then adjust the flex-shrink on the three divs inside based on which you want to shrink to fit.

For example maybe you want all the images to be the same size. If so you could do:

```<code>.img-container{
  flex: 0 0 75px;
}
.img-container img{
  height: 100%;
}
</code>```

But the first div to shrink to fit:

```<code>.some-data-div{
  flex: 1 1 auto;
}
</code>```

The nested divs inside you could make flex containers, too, depending on what they are and what they contain. You could also make the whole thing a CSS grid. If you are creating a defined space (as opposed to letting it flow to the space it needs) you will probably need to define how exactly that limited space will be used. So yes, you may have to define the height, or max-height, of several elements.

Body:
Some data

 My image is here

        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>

My parent div #maincontainer has fixed height - 200 px and width.
It is probably not a good practice to make height fixed, however, this is required for me to resolve another issue.

How can I make all child elements to fit into this container?

Before setting the size to 200 px, all child elements fitted well into #maincontainer. However, after setting fixed height, I can see that my #imagecontainer and #button-row overflowing my parent container.

Do I need to set height to all child elements?

What if I have multiple nested child containers inside of my main container?

Body:
You could make it a flex container;

.maincontainer{
  display: flex;
  flex-flow: column nowrap;
}

Then adjust the flex-shrink on the three divs inside based on which you want to shrink to fit.

For example maybe you want all the images to be the same size. If so you could do:

.img-container{
  flex: 0 0 75px;
}
.img-container img{
  height: 100%;
}

But the first div to shrink to fit:

.some-data-div{
  flex: 1 1 auto;
}

The nested divs inside you could make flex containers, too, depending on what they are and what they contain. You could also make the whole thing a CSS grid. If you are creating a defined space (as opposed to letting it flow to the space it needs) you will probably need to define how exactly that limited space will be used. So yes, you may have to define the height, or max-height, of several elements.


问:
I want format phone number column while selecting from oracle
I am trying to add +1 while trying to get data from a phone number column. example data(1234567890)</p>

```<code>select phone_number from table1;

result
1234567880

desired result
+11234567880
</code>```

答:
use concat() or || operator

```<code>select concat('+1',phone_number) as phoneNumber from table1
</code>```

OR

if data type of your phone_number column is number/int then you can use

```<code>select concat('+1',TO_CHAR(phone_number)) as phoneNumber from table1
</code>```

Body:
I am trying to add +1 while trying to get data from a phone number column. example data(1234567890)

select phone_number from table1;

result
1234567880

desired result
+11234567880

Body:
use concat() or || operator

select concat('+1',phone_number) as phoneNumber from table1

OR

if data type of your phone_number column is number/int then you can use

select concat('+1',TO_CHAR(phone_number)) as phoneNumber from table1


问:
Picasso not working with drawable resource in Android
```<code>ImageView img = findViewById(R.id.img);
int resId = R.drawable.coffee;
Picasso.get().load(resId).into(img);
</code>```

Why it is not working. but the following worked fine:

```<code>ImageView img = findViewById(R.id.img);
String path= "https://images.pexels.com/photos/434213/pexels-photo-434213.jpeg";
Picasso.get().load(path).into(img);
</code>```

答:
Try to use following code (this is context):

```<code>Picasso.with(this)
.load(R.drawable.coffee)
.into(img);
</code>```

You can also ged rid of Picasso:

```<code>img.setImageResource(R.drawable.coffee);
</code>```

Body:
ImageView img = findViewById(R.id.img);
int resId = R.drawable.coffee;
Picasso.get().load(resId).into(img);

Why it is not working. but the following worked fine:

ImageView img = findViewById(R.id.img);
String path= "https://images.pexels.com/photos/434213/pexels-photo-434213.jpeg";
Picasso.get().load(path).into(img);

Body:
Try to use following code (this is context):

Picasso.with(this)
.load(R.drawable.coffee)
.into(img);

You can also ged rid of Picasso:

img.setImageResource(R.drawable.coffee);


问:
Is there a java client for Google Dataflow to start a job from template?
I am looking up the way to start a Google dataflow job from template. I found the rest api to do so and dig into the api page
https://cloud.google.com/dataflow/docs/apis
and only found the rest api to do so. I am wondering if there is some java client like what we can do in Storage such as

Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

Maybe I overlooked. But the Api for Java and Python looked like all about Beam pipeline not starting a job.

答: Closest thing would be the Google Cloud Java API Client used with the Dataflow REST API.</p>


问:
Simulate a time interval
I am working on a homework project where I need to simulate a time interval (4 minutes specifically) with the python time library.

I have to use the time.time() function, so I tried with that function but It only returns the seconds since the epoch.

答: time.time() gives you the time now expressed as seconds since the epoch. You want 4 minutes from now. So add 4 minutes. But you have to add seconds not minutes. So, time.time() + 4 * 60.

Title: Simulate a time interval


问:
How can I Upgrade CS-Cart from 4.9.3.SP1 to 4.10.1
My host is AWS and I need to update my cs-cart from 4.9.3.SP1 to 4.10.1 and I tried to execute the update but get below error for FTP:

Permissions issue These files require write permissions set (manually
  or automatically via FTP)

答: Some directories do not have write access, please enter the FTP account in the cs-cart settings to configure.</p>


问:
navigation.xml : activities missing, preview and linking unavailable
I've just learned about the whole navigation feature in Android, how you can draw a graph and link fragments or activities in order to visualize the flow and pass intents parameters safely through a navigation.xml file.

I have 3 different issues right from the start :

Not all activities can be added to the graph through the editor (I'm aware I can write the XML in the text tab but I believe there's some kind of issue)

All previews are missing (not a big deal again but still intriguing)

I cannot link the activities

Do you have any clues of what could've caused this ?

答:
Not all activities can be added to the graph through the editor (I'm aware I can write the XML in the text tab but I believe there's some kind of issue)

You should file a bug against the Navigation Editor if you're able to reproduce this in a sample project using the latest Android Studio as all activities should be listed. Note that activities you've already added to your graph are filtered out from the Add Destination list (as you've already added it).

All previews are missing (not a big deal again but still intriguing)

The Navigation Editor relies on some layout in your project having a tools:context pointing to your activity (i.e., tools:context="com.example.MainActivity") to automatically populate a layout. This check is only done when first adding the destination to your graph - after the fact, you'd need to add a tools:layout="@layout/main_activity" attribute to your destination manually.

I cannot link the activities

As per the Getting Started guide for Navigation:

Note: The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph.

In Navigation, an <activity> destination serves as an exit point - linking the graph of one activity to another activity, which would have its own navigation graph. The Navigation Editor prevents you from creating actions (the lines between destinations) from <activity> destinations because they can never be triggered - by starting an <activity> destination, you've left the old activity (and its graph) behind.

As per the Migrate to the Navigation component documentation, you should focus on converting one activity at a time to Navigation by building out the graph for just that activity (whether it contains just a single screen or multiple Fragments). <activity> destinations then allow you to link the separate activities together, replacing calls to startActivity() in a way that would allow you to seamlessly combine activities together if you so choose.


问:
pointer & array conflict
let

```<code>int*p ,b = 5;
p = &b;
</code>```

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

```<code>printf("%d",p);
</code>```

is it an address? if it is an address then tell me which element it belongs,please explain clearly

答:
```<code>p = &b
</code>```

This doesn't denote an array! As I explained here, they're not the same thing. b is just an integer value. If you declare b as int b[] = {1, 2, 3}; then p will point to b's first element.

```<code>printf("%d",p);
</code>```

This will print p's value, and since p is a pointer and points to b,  this will print b's address. printf("%d", &b); will give the same result.

By the way, if b was an array, b[5] would be translated into *(p + 5), so you can read (and write) values by adding the number of elements to the beginning of the array. And b[5] == p[5] == *(b + 5) == *(p + 5)!!! But not because arrays and pointers are the same thing, just because an array's name translates to its first element's address.

As a side note, compilers always use pointers notation (*(base + offset)) when compiling to assembly.

Title: pointer & array conflict

Body:
let

int*p ,b = 5;
p = &b;

denotes a ONE DIMENSIONAL array, then what is the output given by following statement

printf("%d",p);

is it an address? if it is an address then tell me which element it belongs,please explain clearly

Body:
p = &b

This doesn't denote an array! As I explained here, they're not the same thing. b is just an integer value. If you declare b as int b[] = {1, 2, 3}; then p will point to b's first element.

printf("%d",p);

This will print p's value, and since p is a pointer and points to b,  this will print b's address. printf("%d", &b); will give the same result.

By the way, if b was an array, b[5] would be translated into *(p + 5), so you can read (and write) values by adding the number of elements to the beginning of the array. And b[5] == p[5] == *(b + 5) == *(p + 5)!!! But not because arrays and pointers are the same thing, just because an array's name translates to its first element's address.

As a side note, compilers always use pointers notation (*(base + offset)) when compiling to assembly.


问:
How to refer to other things in R loop
Say that I have this data:

```<code>library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))
</code>```

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

```<code>data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)
</code>```

Then, how to make this loop work and simplified?

```<code>for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}
</code>```

答:
There is probably a much better way to solve this problem than how you are trying to do it, but to make your idea work you just need to get the data frames in a list, and iterate over its indices.</p>

```<code>library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))

data_lst <- list(
  data03 = filter(data, num<=1),
  data04 = filter(data, num<=2),
  data05 = filter(data, num<=3),
  data06 = filter(data, num<=4),
  data07 = filter(data, num<=5),
  data08 = filter(data, num<=6))

for (i in seq_along(data_lst)) {
  print(i)
  title = data[2][-1]
  print(title)
  df <- data_lst[[i]]
  plot(df$num, main=title)
}
</code>```

Title: How to refer to other things in R loop

Body:
Say that I have this data:

library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))

I then have several things that would be useful to figures out, mainly about how the values in a loop refer to other values and how to automate this process.

It would be best to put this in a loop. How to do so with data frame names? In other words, how to refer to the name of a data.frame in a loop?

data03 <- filter(data, num<=1)
data04 <- filter(data, num<=2)
data05 <- filter(data, num<=3)
data06 <- filter(data, num<=4)
data07 <- filter(data, num<=5)
data08 <- filter(data, num<=6)

Then, how to make this loop work and simplified?

for (i in c(03, 04, 05, 06, 07, 08)) {
    #I want to print the number corresponding to i
    if(i=="03") print(1)
    if(i=="04") print(2)
    if(i=="05") print(3)
    if(i=="06") print(4)
    if(i=="07") print(5)
    if(i=="08") print(6)
    #I want to get the value corresponding to i for the plot title
    if(i=="03") title="1998-99"
    if(i=="04") title="1999-00"
    if(i=="05") title="2000-01"
    if(i=="06") title="2001-02"
    if(i=="07") title="2002-03"
    if(i=="08") title="2003-04"
    #I want to open the data frame, data+i
    df <- paste(data,i)
    #I want to plot, using the title saved above
    plot(df$num, main=title)
}

Body:
There is probably a much better way to solve this problem than how you are trying to do it, but to make your idea work you just need to get the data frames in a list, and iterate over its indices.

library(dplyr)
data <- data.frame(num=c(1:6), val=c('1998-99', '1999-00', '2000-01', '2001-02', '2002-03', '2003-04'))

data_lst <- list(
  data03 = filter(data, num<=1),
  data04 = filter(data, num<=2),
  data05 = filter(data, num<=3),
  data06 = filter(data, num<=4),
  data07 = filter(data, num<=5),
  data08 = filter(data, num<=6))

for (i in seq_along(data_lst)) {
  print(i)
  title = data[2][-1]
  print(title)
  df <- data_lst[[i]]
  plot(df$num, main=title)
}


问:
I can't get emails to my inbox, even though i can see a successful transaction in mailtrap
i just sent an email using mailtrap on laravel, i can get the notifications on mailtrap, but the email does not get to the intended user emails. What could be the problem and how can i obtain a solution

I've tried changing the default "from" parameter to a real email address and yet the mails do not drop.

答: Mailtrap is a fake dev server for testing your emails. It traps the email and doesn't forward it on to the intended user. Once you can see that it works and it looks correct, change to a real service like mailgun, reset your config, and it should get to the right place.</p>


问:
Why doesn't this code work? And how to make it work?
To determine the steps it'll take for "y" to catch up with "z."

var z = 50;
var y = 1;
do {
  document.write(z, "-");
  z++
} while (z >= y);
do {
  document.write(y, "/");
  y = y + 2
} while (y <= z);```

答:
```<code>var z = 50;
var y = 1;
function test(z,y){
    z++;
    y=y+2;
    console.log(z,y,'try');
    if(y>z){
        console.log(z,y,'you do it');
        return false;
    }else{
        test(z,y);
    }
}
test(z,y);
</code>```


问:
.gitlab-ci.yml error: "apk: command not found"
I have the following .gitlab-ci.yml file:

```<code>image: docker

services:
  - docker:dind

stages:
  - test
  - build
  - deploy

test:
  stage: test
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Testing the app"
    - docker-compose run app sh -c "python manage.py test && flake8"

build:
  stage: build
  only:
    - develop
    - production
    - feature/deploy-debug-gitlab
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Building the app"
    - docker-compose build

deploy:
  stage: deploy
  only:
    - master
    - develop
    - feature/deploy
    - feature/deploy-debug-gitlab
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Deploying the app"
    - docker-compose up -d
  environment: production
  when: manual

</code>```

When the Gitlab runner executes it, I get the following error:

```<code>$ apk add --update -y python-pip
bash: line 82: apk: command not found
ERROR: Job failed: exit status 1
</code>```

How am I supposed to install apk? Or what image other than docker should I be using to run this gitlab-ci.yml file?

答:
The alternative is to set your installation on step above test, as in this issue

```<code>image: docker:latest

services:
- docker:dind

before_script:
- apk add --update python-pip
</code>```

Body:
I have the following .gitlab-ci.yml file:

image: docker

services:
  - docker:dind

stages:
  - test
  - build
  - deploy

test:
  stage: test
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Testing the app"
    - docker-compose run app sh -c "python manage.py test && flake8"

build:
  stage: build
  only:
    - develop
    - production
    - feature/deploy-debug-gitlab
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Building the app"
    - docker-compose build

deploy:
  stage: deploy
  only:
    - master
    - develop
    - feature/deploy
    - feature/deploy-debug-gitlab
  before_script:
    - apk add --update -y python-pip
    - pip install docker-compose
  script:
    - echo "Deploying the app"
    - docker-compose up -d
  environment: production
  when: manual

When the Gitlab runner executes it, I get the following error:

$ apk add --update -y python-pip
bash: line 82: apk: command not found
ERROR: Job failed: exit status 1

How am I supposed to install apk? Or what image other than docker should I be using to run this gitlab-ci.yml file?

Body:
The alternative is to set your installation on step above test, as in this issue

image: docker:latest

services:
- docker:dind

before_script:
- apk add --update python-pip


问:
Is there a way to mount Android .img to access the AVD (Android Virtual Device) contents?
I feel a bit blind developing on an emulator for Android and not being able to see the file system on the AVD (.img).

Is there a way to mount it in Windows or Linux, so that I could at least see the file listing and maybe contents?

Bonus if it's mounted with write permissions as well.

Thank you.

答:
You can just mount the device in Linux:</p>

```<code>sudo mount -o loop ~/.android/avd/<myvirt>/sdcard.img <destdir>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can just mount the device in Linux:

sudo mount -o loop ~/.android/avd/<myvirt>/sdcard.img <destdir>


问:
How to connect applications with services created through Kubernetes operators?
I am looking for best practices to connect applications with services. I have a database operator which creates a service, and there is an application pod which needs to connect to it. Is the following approach going to work?

The operator injects the access details into the pods as Secret and ConfigMap.

The operator identifies application pods through label selectors (e.g., connects-to: mysql).

The application pod receives service access details through environment variables.

The operator can document the environment variables and the label selectors.

If the above flow is going to work, how can I inject values into pods?
I can see a few mechanisms. Which one would be better?

PodPreset (alpha since 2017)

Initializer

MutatingAdmissionWebhook

This is the expected interaction between controllers and actors (PodPreset can be substituted with other choices):

答:
your question is not completely clear.

if I understand your question , you can use helm with multiple values file to it.

```<code>helm install ./repo/ --name repo --values ./values.file
</code>```

you can also --set command to the help to add values that are not in the values file for some reason

Body:
your question is not completely clear.

if I understand your question , you can use helm with multiple values file to it.

helm install ./repo/ --name repo --values ./values.file

you can also --set command to the help to add values that are not in the values file for some reason


问:
VSIX - include other application in package
How can we include a separate .NET application inside a VSIX package?  Preferably in a subdirectory so that it doesn't interfere with DLLs of the Visual Studio extension itself (different versions). The application is available in the same solution, but for the same reason I van also not add a reference to it in the main project.

The intention is to run that application as a separate process, started by the extension. The extension will then connect to that application through WCF.

答:
I'm pretty certain you just need to include the .EXE in your .VSIX. A .VSIX is just a .zip file, and you can include additional files into it by simply adding them to your project and setting the Include in VSIX property to true.

To confirm, try downloading something like the Azure Data Lake and Stream Analytics Tools VSIX to disk. (I mention this one because I noticed it installed a number of .EXE's under my C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\Extensions directory).

Once you have the .VSIX on disk, rename it as a .zip file and unzip, or view its contents with the windows explorer. Note that the extensions.vsixmanifest file contained in that .zip has no references or entries for any of the .exe files installed by that .VSIX. Which means, all you really need to do is include it in the .zip file.

Add a subfolder to your .VSIX project, copy the .exe there, add it to your project, set the Include In VISX property to true, and I suspect you'll be all set.

Sincerely,


问:
How to add environment variable in C++?
Is there any way I can add environment variable in Windows via C++?

They have to be added in "My computer->properties->advanced->environment variables"

Thank you

答:
```<code>#include <iostream>
#include <windows.h>
#include <cstring>
#include "tchar.h"

void SetUserVariablePath(){
    HKEY hkey;
    long regOpenResult;
    const char key_name[] = "Environment";
    const char path[]="D:/custom_command";                                               //new_value path need to update
    regOpenResult = RegOpenKeyEx(HKEY_CURRENT_USER,key_name, 0, KEY_ALL_ACCESS, &hkey);
    LPCSTR stuff = "VVS_LOGGING_PATH";                                                   //Variable Name
    RegSetValueEx(hkey,stuff,0,REG_SZ,(BYTE*) path, strlen(path));
    RegCloseKey(hkey);
}

void GetUserVariablePath(){
    static const char path[] = "VVS_LOGGING_PATH" ;                                      //Variable Name
    static BYTE buffer1[1000000] ;
    DWORD buffsz1 = sizeof(buffer1) ;
    {
        //HKEY_CURRENT_USER\Environment
        const char key_name[] = "Environment";
        HKEY key ;

        if( RegOpenKeyExA( HKEY_CURRENT_USER, key_name, 0, KEY_QUERY_VALUE, std::addressof(key) ) == 0 &&
            RegQueryValueExA( key, path, nullptr, nullptr, buffer1, std::addressof(buffsz1) ) == 0 )
        {
            std::cout << "The updated value of the user variable is :  " << reinterpret_cast<const char*>(buffer1) << '\n' ;
        }
    }
}

int main()
{
    SetUserVariablePath();
    GetUserVariablePath();
    return 0;
}
</code>```

Title: How to add environment variable in C++?


问:
flask - preserve response header
This is how my login method looks like:

```<code>def login():
    if request.method == "GET":
        return render_template('user/login.html')
    else:
        jwt_token = "xxxx"
        resp = redirect(url_for('home.index'))
        resp.headers.set('Authorization', "JWT {}".format(jwt_token))
        return resp
</code>```

This works fine but the Authorization header does not make it to home.index page.

How do I tell flask to preserve this header on every request?

------Edit---------

This works if I add Token to Cookie as resp.set_cookie('Authorization', "JWT {}".format(json_data["access_token"])) but I would like to keep it in the Authorization Header.

答:
If you want to set Authorization header on all requests, you could do something like this:

@app.after_request
def after_request(response):
    my_jwt_token = 'xxxx'
    response.headers['Authorization'] = my_jwt_token
    return response
```

More information on documentation: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.after_request

Title: flask - preserve response header

Body:
This is how my login method looks like:

def login():
    if request.method == "GET":
        return render_template('user/login.html')
    else:
        jwt_token = "xxxx"
        resp = redirect(url_for('home.index'))
        resp.headers.set('Authorization', "JWT {}".format(jwt_token))
        return resp

This works fine but the Authorization header does not make it to home.index page.

How do I tell flask to preserve this header on every request?

------Edit---------

This works if I add Token to Cookie as resp.set_cookie('Authorization', "JWT {}".format(json_data["access_token"])) but I would like to keep it in the Authorization Header.

Body:
If you want to set Authorization header on all requests, you could do something like this:

@app.after_request
def after_request(response):
    my_jwt_token = 'xxxx'
    response.headers['Authorization'] = my_jwt_token
    return response

More information on documentation: http://flask.pocoo.org/docs/1.0/api/#flask.Flask.after_request


问:
Triple-nested form with Rails form_with and strong parameters
I'm running Rails 6.0.0.rc1 and having trouble getting a triple nested form working. I have products that have options that have option_values. So a Product might have an option called "Color" and an Option Value named "Red." I'd like to create all of these in a classic nested form in the Product form.

The form works and I can save Product with an Option, but not the Option Value on submit. I'm not sure why it's not working when I try to embed fields_for Option Values inside the fields_for Options.

What am I doing wrong here? I feel like I'm missing something obvious, but can't figure it out. (Probably not relevant, but note that I need to scope each object to account_id and my User has_one :account that's the reason for the hidden field.)

Here is my product model:

```<code>class Product < ApplicationRecord
  belongs_to :account

  has_many :options, dependent: :destroy
  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

Option model:

```<code>class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy
  accepts_nested_attributes_for :option_values, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

OptionValue model:

```<code>class OptionValue < ApplicationRecord
  belongs_to :account
  belongs_to :option

  validates :account_id,  presence: true
  validates :name,        presence: true
end
</code>```

Here's the Product form:

```<code><%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= f.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>
</code>```

ProductsController:

```<code>class ProductsController < ApplicationController
  def new
    @product = Product.new
    @product.options.build
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def product_params
      params.require(:product).permit(
        :account_id, :name,
        options_attributes: [
          :id, :account_id, :name, :_destroy,
          option_values_attributes:[:id, :account_id, :name, :_destroy ]
        ]
      )
    end
end
</code>```

答:
At first, you need to change the form to nest option_values inside option, and add account_id field to option values:

```<code><%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= options_form.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.hidden_field :account_id, value: current_user.account.id %>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>
</code>```

Also you need to build nested records in the controller. Another option is to build them dynamically via javascript (look at the cocoon gem, for example). To build 3 options with 3 values each:

```<code>def new
  @account = current_user.account
  # it is better to create associated product
  @product = @account.products.new
  3.times do
    option = @product.options.build
    3.times { option.option_values.build }
  end
end
</code>```

Body:
I'm running Rails 6.0.0.rc1 and having trouble getting a triple nested form working. I have products that have options that have option_values. So a Product might have an option called "Color" and an Option Value named "Red." I'd like to create all of these in a classic nested form in the Product form.

The form works and I can save Product with an Option, but not the Option Value on submit. I'm not sure why it's not working when I try to embed fields_for Option Values inside the fields_for Options.

What am I doing wrong here? I feel like I'm missing something obvious, but can't figure it out. (Probably not relevant, but note that I need to scope each object to account_id and my User has_one :account that's the reason for the hidden field.)

Here is my product model:

class Product < ApplicationRecord
  belongs_to :account

  has_many :options, dependent: :destroy
  accepts_nested_attributes_for :options, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end

Option model:

class Option < ApplicationRecord
  belongs_to :account
  belongs_to :product

  has_many :option_values, dependent: :destroy
  accepts_nested_attributes_for :option_values, allow_destroy: true

  validates :account_id,  presence: true
  validates :name,        presence: true
end

OptionValue model:

class OptionValue < ApplicationRecord
  belongs_to :account
  belongs_to :option

  validates :account_id,  presence: true
  validates :name,        presence: true
end

Here's the Product form:

<%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= f.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>

ProductsController:

class ProductsController < ApplicationController
  def new
    @product = Product.new
    @product.options.build
  end

  def create
    @account = current_user.account
    @product = @account.products.build(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    def product_params
      params.require(:product).permit(
        :account_id, :name,
        options_attributes: [
          :id, :account_id, :name, :_destroy,
          option_values_attributes:[:id, :account_id, :name, :_destroy ]
        ]
      )
    end
end

Body:
At first, you need to change the form to nest option_values inside option, and add account_id field to option values:

<%= form_with(model: product, local: true) do |f| %>
  <%= f.fields_for :options do |options_form| %>
    <fieldset class='form-group'>
      <%= options_form.hidden_field :account_id, value: current_user.account.id %>
      <%= options_form.label :name, 'Option' %>
      <%= options_form.text_field :name, class: 'form-control' %>
    </fieldset>

    <%= options_form.fields_for :option_values do |values_form| %>
      <fieldset class='form-group'>
        <%= values_form.hidden_field :account_id, value: current_user.account.id %>
        <%= values_form.label :name, 'Value' %>
        <%= values_form.text_field :name, class: 'form-control' %>
      </fieldset>
    <% end %>
  <% end %>
<% end %>

Also you need to build nested records in the controller. Another option is to build them dynamically via javascript (look at the cocoon gem, for example). To build 3 options with 3 values each:

def new
  @account = current_user.account
  # it is better to create associated product
  @product = @account.products.new
  3.times do
    option = @product.options.build
    3.times { option.option_values.build }
  end
end


问:
How to run tasks with OS-specific variables?
How to run the tasks below with OS-specific variables in the files?

Debian-6-certificates.yaml

Debian-7-certificates.yaml

Debian-8-certificates.yaml

Debian-9-certificates.yaml

.

```<code>   - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
      - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh
</code>```

Current Playbook:

```<code>- hosts: debian_hosts
  gather_facts: yes  # collect info about host incl. ansible_distribution_*
  tasks:
    - include_vars:
        file: "vars/{{ ansible_distribution: Debian }}-{{ ansible_distribution_version: 6 }}-certificates.yml"
    - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
        - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh

Output:

PLAY [debian_hosts] ********************************************************************************
skipping: no hosts matched
</code>```

答:
Find out ansible_distribution and ansible_distribution_version for Debian-6,7,8,9

```<code>$ ansible -m setup host | grep ansible_distribution
</code>```

Let's assume (pick variables that fit your needs)

```<code>"ansible_distribution": "Debian"
"ansible_distribution_version": "6"
</code>```

Create directory var and put there the files with the variables. The name of the files combines the variables. See the example below. Fit the names and variables to your needs.

```<code>"vars/{{ ansible_distribution }}-{{ ansible_distribution_version }}-certificates.yml"
</code>```

Create inventory group debian_hosts and run the playbook below

```<code>- hosts: debian_hosts
  gather_facts: yes  # collect info about host incl. ansible_distribution_*
  tasks:
    - include_vars:
        file: "vars/{{ ansible_distribution }}-{{ ansible_distribution_version }}-certificates.yml"
    - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
        - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh
</code>```

(not tested)

Body:
How to run the tasks below with OS-specific variables in the files?

Debian-6-certificates.yaml

Debian-7-certificates.yaml

Debian-8-certificates.yaml

Debian-9-certificates.yaml

.

   - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
      - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh

Current Playbook:

- hosts: debian_hosts
  gather_facts: yes  # collect info about host incl. ansible_distribution_*
  tasks:
    - include_vars:
        file: "vars/{{ ansible_distribution: Debian }}-{{ ansible_distribution_version: 6 }}-certificates.yml"
    - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
        - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh

Output:

PLAY [debian_hosts] ********************************************************************************
skipping: no hosts matched

Body:
Find out ansible_distribution and ansible_distribution_version for Debian-6,7,8,9

$ ansible -m setup host | grep ansible_distribution

Let's assume (pick variables that fit your needs)

"ansible_distribution": "Debian"
"ansible_distribution_version": "6"

Create directory var and put there the files with the variables. The name of the files combines the variables. See the example below. Fit the names and variables to your needs.

"vars/{{ ansible_distribution }}-{{ ansible_distribution_version }}-certificates.yml"

Create inventory group debian_hosts and run the playbook below

- hosts: debian_hosts
  gather_facts: yes  # collect info about host incl. ansible_distribution_*
  tasks:
    - include_vars:
        file: "vars/{{ ansible_distribution }}-{{ ansible_distribution_version }}-certificates.yml"
    - name: Copy the proxy CA to /etc/ssl/certs/
      copy:
        src: library/{{ item }}.crt
        dest: /usr/local/share/ca-certificates/{{ item }}.crt
      with_items:
        - "{{ proxy_ca_certificate }}"
    - name: Update system CA certificates
      command: update-ca-certificates --fresh

(not tested)


问:
Maven + Git Bash: Root directory path is being appended to Environment Variable value beginning with '/'
I'm setting an environment variable with the value /abc/, and then using that environment variable's value inside a Maven pom.xml.

When I run any Maven goal, eg. mvn test, inside Git Bash, the value of that environment variable is being translated to C:/Users/<user>/AppData/Local/Programs/Git/abc/.

As you can see, the / at the beginning is being replaced with the root directory's path. The /at the end is not being affected, so this only happens if the / occurs at the beginning.

Is there any way to prevent this? I just want to be able to use the environment variable's value as /abc/ in the actual automated test being executed by Maven.

This is how I'm setting the env variable:
export TEST="/abc/"

This is how I'm using the env variable in pom.xml:

```<code><properties>
    <testProp>${env.TEST}</testProp>
</properties>
</code>```

Versions:
Maven: 3.6.0
Java: 1.8.0_212
Git Bash: 2.9.2
Mintty: 2.0.3

答:
git bash is designed only for git (and a few quirk like openssl etc). It is not meant for everyday bash shell.

I was also quite upset when I learnt that.

For Windows 7, just use Windows cmd (or powershell). Cygwin also can't help much either but babun (now un-maintained) works pretty well.

For Windows 10, just use Windows Subsystem for Linux and use Ubuntu shell.

Body:
I'm setting an environment variable with the value /abc/, and then using that environment variable's value inside a Maven pom.xml.

When I run any Maven goal, eg. mvn test, inside Git Bash, the value of that environment variable is being translated to C:/Users/<user>/AppData/Local/Programs/Git/abc/.

As you can see, the / at the beginning is being replaced with the root directory's path. The /at the end is not being affected, so this only happens if the / occurs at the beginning.

Is there any way to prevent this? I just want to be able to use the environment variable's value as /abc/ in the actual automated test being executed by Maven.

This is how I'm setting the env variable:
export TEST="/abc/"

This is how I'm using the env variable in pom.xml:

<properties>
    <testProp>${env.TEST}</testProp>
</properties>

Versions:
Maven: 3.6.0
Java: 1.8.0_212
Git Bash: 2.9.2
Mintty: 2.0.3


问:
Schema Registry container: Server died unexpectedly when launching using docker-compose
I have written docker-compose.yml file to create the following containers:

Confluent-Zookeeper

Confluent-Kafka

Confluent-Schema Registry

I want a single docker-compose file to spun up the necessary containers, expose required ports and interconnect the dependent containers. The goal is to have
I am using the official confluent images from Docker Hub.
My docker-compose file looks like this:

```<code>zookeeper:
  image: confluent/zookeeper
  container_name: confluent-zookeeper
  hostname: zookeeper
  environment:
    ZOOKEEPER_CLIENT_PORT: 2181
  ports:
    - "2181:2181"

kafka:
  environment:
    KAFKA_ZOOKEEPER_CONNECTION_STRING: zookeeper:2181
    KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
  image: confluent/kafka
  container_name: confluent-kafka
  hostname: kafka
  links:
    - zookeeper
  ports:
    - "9092:9092"

schema-registry:
  image: confluent/schema-registry
  container_name: confluent-schema_registry
  environment:
    SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: zookeeper:2181
    SCHEMA_REGISTRY_HOSTNAME: schema-registry
    SCHEMA_REGISTRY_LISTENERS: http://schema-registry:8081
    SCHEMA_REGISTRY_DEBUG: 'true'
    SCHEMA_REGISTRY_KAFKASTORE_TOPIC_REPLICATION_FACTOR: '1'
  links:
    - kafka
    - zookeeper
  ports:
    - "8081:8081"
</code>```

Now when I run docker-compose up, all these containers will be created and launched. But Schema Registry container exits immediately. docker logs gives the following output:

```<code> (io.confluent.kafka.schemaregistry.rest.SchemaRegistryConfig:135)
[2017-05-17 06:06:33,415] ERROR Server died unexpectedly:  (io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain:51)
org.apache.kafka.common.config.ConfigException: Only plaintext and SSL Kafka endpoints are supported and none are configured.
        at io.confluent.kafka.schemaregistry.storage.KafkaStore.getBrokerEndpoints(KafkaStore.java:254)
        at io.confluent.kafka.schemaregistry.storage.KafkaStore.<init>(KafkaStore.java:111)
        at io.confluent.kafka.schemaregistry.storage.KafkaSchemaRegistry.<init>(KafkaSchemaRegistry.java:136)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication.setupResources(SchemaRegistryRestApplication.java:53)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication.setupResources(SchemaRegistryRestApplication.java:37)
        at io.confluent.rest.Application.createServer(Application.java:117)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain.main(SchemaRegistryMain.java:43)
</code>```

I searched for this issue but nothing helped. I tried various other configurations like providing KAFKA_ADVERTISED_HOSTNAME, changing SCHEMA_REGISTRY_LISTENERS value, etc. but no luck.
Can anybody point out the exact configuration issue why Schema Registry container is failing?

答:
The question is old, though it might be helpful to leave a solution that worked for me. I am using docker-compose:</p>

```<code>version: '3.3'

services:
  zookeeper:
    image: confluent/zookeeper:3.4.6-cp1
    hostname: "zookeeper"
    networks:
      - test-net
    ports:
      - 2181:2181
    environment:
      zk_id: "1"

  kafka:
    image: confluent/kafka:0.10.0.0-cp1
    hostname: "kafka"
    depends_on:
      - zookeeper
    networks:
      - test-net
    ports:
      - 9092:9092
    environment:
      KAFKA_ADVERTISED_HOST_NAME: "kafka"
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_BROKER_ID: "0"
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"

  schema-registry:
    image: confluent/schema-registry:3.0.0
    hostname: "schema-registry"
    depends_on:
      - kafka
      - zookeeper
    networks:
      - test-net
    ports:
      - 8081:8081
    environment:
      SR_HOSTNAME: schema-registry
      SR_LISTENERS: http://schema-registry:8081
      SR_DEBUG: 'true'
      SR_KAFKASTORE_TOPIC_REPLICATION_FACTOR: '1'
      SR_KAFKASTORE_TOPIC_SERVERS: PLAINTEXT://kafka:9092

networks:
  test-net:
    driver: bridge`
</code>```

Body:
I have written docker-compose.yml file to create the following containers:

Confluent-Zookeeper

Confluent-Kafka

Confluent-Schema Registry

I want a single docker-compose file to spun up the necessary containers, expose required ports and interconnect the dependent containers. The goal is to have
I am using the official confluent images from Docker Hub.
My docker-compose file looks like this:

zookeeper:
  image: confluent/zookeeper
  container_name: confluent-zookeeper
  hostname: zookeeper
  environment:
    ZOOKEEPER_CLIENT_PORT: 2181
  ports:
    - "2181:2181"

kafka:
  environment:
    KAFKA_ZOOKEEPER_CONNECTION_STRING: zookeeper:2181
    KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
  image: confluent/kafka
  container_name: confluent-kafka
  hostname: kafka
  links:
    - zookeeper
  ports:
    - "9092:9092"

schema-registry:
  image: confluent/schema-registry
  container_name: confluent-schema_registry
  environment:
    SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL: zookeeper:2181
    SCHEMA_REGISTRY_HOSTNAME: schema-registry
    SCHEMA_REGISTRY_LISTENERS: http://schema-registry:8081
    SCHEMA_REGISTRY_DEBUG: 'true'
    SCHEMA_REGISTRY_KAFKASTORE_TOPIC_REPLICATION_FACTOR: '1'
  links:
    - kafka
    - zookeeper
  ports:
    - "8081:8081"

Now when I run docker-compose up, all these containers will be created and launched. But Schema Registry container exits immediately. docker logs gives the following output:

 (io.confluent.kafka.schemaregistry.rest.SchemaRegistryConfig:135)
[2017-05-17 06:06:33,415] ERROR Server died unexpectedly:  (io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain:51)
org.apache.kafka.common.config.ConfigException: Only plaintext and SSL Kafka endpoints are supported and none are configured.
        at io.confluent.kafka.schemaregistry.storage.KafkaStore.getBrokerEndpoints(KafkaStore.java:254)
        at io.confluent.kafka.schemaregistry.storage.KafkaStore.<init>(KafkaStore.java:111)
        at io.confluent.kafka.schemaregistry.storage.KafkaSchemaRegistry.<init>(KafkaSchemaRegistry.java:136)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication.setupResources(SchemaRegistryRestApplication.java:53)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication.setupResources(SchemaRegistryRestApplication.java:37)
        at io.confluent.rest.Application.createServer(Application.java:117)
        at io.confluent.kafka.schemaregistry.rest.SchemaRegistryMain.main(SchemaRegistryMain.java:43)

I searched for this issue but nothing helped. I tried various other configurations like providing KAFKA_ADVERTISED_HOSTNAME, changing SCHEMA_REGISTRY_LISTENERS value, etc. but no luck.
Can anybody point out the exact configuration issue why Schema Registry container is failing?

Body:
The question is old, though it might be helpful to leave a solution that worked for me. I am using docker-compose:

version: '3.3'

services:
  zookeeper:
    image: confluent/zookeeper:3.4.6-cp1
    hostname: "zookeeper"
    networks:
      - test-net
    ports:
      - 2181:2181
    environment:
      zk_id: "1"

  kafka:
    image: confluent/kafka:0.10.0.0-cp1
    hostname: "kafka"
    depends_on:
      - zookeeper
    networks:
      - test-net
    ports:
      - 9092:9092
    environment:
      KAFKA_ADVERTISED_HOST_NAME: "kafka"
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
      KAFKA_BROKER_ID: "0"
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"

  schema-registry:
    image: confluent/schema-registry:3.0.0
    hostname: "schema-registry"
    depends_on:
      - kafka
      - zookeeper
    networks:
      - test-net
    ports:
      - 8081:8081
    environment:
      SR_HOSTNAME: schema-registry
      SR_LISTENERS: http://schema-registry:8081
      SR_DEBUG: 'true'
      SR_KAFKASTORE_TOPIC_REPLICATION_FACTOR: '1'
      SR_KAFKASTORE_TOPIC_SERVERS: PLAINTEXT://kafka:9092

networks:
  test-net:
    driver: bridge`


问:
How can GHC convert a polymorphic numeric literal into an arbitrary type with an instance of Num?
As far as I can tell, GHC can convert any numeric literal with default polymorphic type Num a => a into any type with an instance of Num. I'd like to know whether this is true and a little about the underlying mechanism.

To explore this, I have written a datatype called MySum which replicates (part of) the functionality of Sum from Data.Monoid. The most important part is that it contains instance Num a => Num (MySum a).

Note - This just so happens to be where my question go its start. The Monoid is not specifically relevant. I've included a portion of that code at the bottom of this question, just in case it is useful for an answer to refer to the contents.

It seems that GHCi will happily comply with an input of the form "v :: MySum t", under the following conditions:

v is a polymorphic value of type Num a => a

t is a (possibly polymorphic) type under Num

As far as I can tell, the only numeric literals compatible with the type Num a => a are ones that look like integers. Is this always the case? It seems to imply that a value can instantiated to any type under Num exactly when that value is integral. If this is correct, then I understand how something like 5 :: MySum Int might work, given the function fromInteger in Num.

With all of that said, I can't figure out how something like this works:

```<code>*Main Data.Monoid> 5 :: Fractional a => MySum a
MySum {getMySum = 5.0}
</code>```

If it's possible to explain this in a novice-friendly way, I would appreciate it.

The instance Num a => Num (MySum a), as promised:

```<code>import Control.Applicative

newtype MySum a = MySum {getMySum :: a}
  deriving Show

instance Functor MySum where
  fmap f (MySum a) = MySum (f a)

instance Applicative MySum where
  pure = MySum
  (MySum f) <*> (MySum a) = MySum (f a)

instance Num a => Num (MySum a) where
  (+) = liftA2 (+)
  (-) = liftA2 (-)
  (*) = liftA2 (*)
  negate = fmap negate
  abs = fmap abs
  signum = fmap signum
  fromInteger = pure . fromInteger
</code>```

答:
You mostly have it correct: an integer literal 5 is equivalent to fromInteger (5 :: Integer), and thus has type Num a => a; and a floating-point literal 5.0 is equivalent to fromRational (5.0 :: Rational) and has type Fractional a => a. This does indeed explain 5 :: MySum Int. 5 :: Fractional a => MySum a isn't that much trickier. Per the above rule, this expands to:

```<code>fromInteger (5 :: Integer) :: Fractional a => MySum a
</code>```

fromInteger has type Num b => Integer -> b. So for the above expression to type check, GHC has to unify b with MySum a. So now GHC has to solve Num (MySum a) given Fractional a. Num (MySum a) is solved by your instance, producing the constraint Num a. Num is a superclass of Fractional, so any solution to Fractional a will also be a solution to Num a. So everything checks out.

You might be wondering though, if 5 gets passed through fromInteger here, why does the value that ends up inside MySum look like a Double in GHCi? This is because, after type checking, Fractional a => MySum a is still ambiguous—when GHCi goes to print that value, it needs to actually choose an a in order to select an appropriate Fractional instance, after all. If we weren't dealing with numbers, we might end up with GHC complaining about this ambiguity in a.

But there's a special case in the Haskell standard for this. The brief overview is, if you have an ambiguity issue like the above that involves only numeric type classes, Haskell in its wisdom will pick either Integer or Double for the ambiguous type and run with the first one that type checks. In this case, that's Double. If you'd like to know more about this feature, this blog post does a decent job of motivating and elaborating on what the standard says.

Body:
As far as I can tell, GHC can convert any numeric literal with default polymorphic type Num a => a into any type with an instance of Num. I'd like to know whether this is true and a little about the underlying mechanism.

To explore this, I have written a datatype called MySum which replicates (part of) the functionality of Sum from Data.Monoid. The most important part is that it contains instance Num a => Num (MySum a).

Note - This just so happens to be where my question go its start. The Monoid is not specifically relevant. I've included a portion of that code at the bottom of this question, just in case it is useful for an answer to refer to the contents.

It seems that GHCi will happily comply with an input of the form "v :: MySum t", under the following conditions:

v is a polymorphic value of type Num a => a

t is a (possibly polymorphic) type under Num

As far as I can tell, the only numeric literals compatible with the type Num a => a are ones that look like integers. Is this always the case? It seems to imply that a value can instantiated to any type under Num exactly when that value is integral. If this is correct, then I understand how something like 5 :: MySum Int might work, given the function fromInteger in Num.

With all of that said, I can't figure out how something like this works:

*Main Data.Monoid> 5 :: Fractional a => MySum a
MySum {getMySum = 5.0}

If it's possible to explain this in a novice-friendly way, I would appreciate it.

The instance Num a => Num (MySum a), as promised:

import Control.Applicative

newtype MySum a = MySum {getMySum :: a}
  deriving Show

instance Functor MySum where
  fmap f (MySum a) = MySum (f a)

instance Applicative MySum where
  pure = MySum
  (MySum f) <*> (MySum a) = MySum (f a)

instance Num a => Num (MySum a) where
  (+) = liftA2 (+)
  (-) = liftA2 (-)
  (*) = liftA2 (*)
  negate = fmap negate
  abs = fmap abs
  signum = fmap signum
  fromInteger = pure . fromInteger

Body:
You mostly have it correct: an integer literal 5 is equivalent to fromInteger (5 :: Integer), and thus has type Num a => a; and a floating-point literal 5.0 is equivalent to fromRational (5.0 :: Rational) and has type Fractional a => a. This does indeed explain 5 :: MySum Int. 5 :: Fractional a => MySum a isn't that much trickier. Per the above rule, this expands to:

fromInteger (5 :: Integer) :: Fractional a => MySum a

fromInteger has type Num b => Integer -> b. So for the above expression to type check, GHC has to unify b with MySum a. So now GHC has to solve Num (MySum a) given Fractional a. Num (MySum a) is solved by your instance, producing the constraint Num a. Num is a superclass of Fractional, so any solution to Fractional a will also be a solution to Num a. So everything checks out.

You might be wondering though, if 5 gets passed through fromInteger here, why does the value that ends up inside MySum look like a Double in GHCi? This is because, after type checking, Fractional a => MySum a is still ambiguous—when GHCi goes to print that value, it needs to actually choose an a in order to select an appropriate Fractional instance, after all. If we weren't dealing with numbers, we might end up with GHC complaining about this ambiguity in a.

But there's a special case in the Haskell standard for this. The brief overview is, if you have an ambiguity issue like the above that involves only numeric type classes, Haskell in its wisdom will pick either Integer or Double for the ambiguous type and run with the first one that type checks. In this case, that's Double. If you'd like to know more about this feature, this blog post does a decent job of motivating and elaborating on what the standard says.


问:
Android Java soundboard code only setting first button as ringtone/etc
I've been playing around with this code and I'm obviously trying to make a soundboard that will save ringtones on longclicks and etc.

Though, this is the basic code for one button. I've been duplicating the same code on top of each other, trying to make arrays, just everything.. I can't get this code to work the way I want it to.

When they are multiple buttons and more codes.

I can get the sounds to all play for the buttons.  I can get the menu to pop up for each button. Tho, the first button is always the one that gets saved, and the rest just fall off the map.

I assume that my data flow on the following code is not getting cut off and being picked up by the other sound buttons. Either way, it doesn't work. Please help me.

```<code>public class Soundboard extends Activity {
    private SoundManager mSoundManager;

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

        mSoundManager = new SoundManager();
        mSoundManager.initSounds(getBaseContext());
        mSoundManager.addSound(1, R.raw.sound1);

        Button SB = (Button)findViewById(R.id.sound1);

        SB.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
               mSoundManager.playSound(1);
            }
        });

        Button btn = (Button) findViewById(R.id.sound1);
        registerForContextMenu(btn);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Save as...");
        menu.add(0, v.getId(), 0, "Ringtone");
        menu.add(0, v.getId(), 0, "Notification");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
        else if(item.getTitle()=="Notification"){function2(item.getItemId());}
        else {return false;}
        return true;
    }

    public void function1(int id){
        if (savering(R.raw.sound1)) {
          // Code if successful
          Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
        }
        else
        {
          // Code if unsuccessful
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
        }

    }
    public void function2(int id){
        if (savenot(R.raw.sound1)) {
          // Code if successful
          Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
        }
        else
        {
          // Code if unsuccessful
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
        }
    }

    //Save into Ring tone Folder
    public boolean savering(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=50;

        try {
           size = fIn.available();
           buffer = new byte[size];
           fIn.read(buffer);
           fIn.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }

        String path="/sdcard/media/audio/ringtones/";

        String filename="ohhh"+".ogg";

        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}

        FileOutputStream save;
        try {
          save = new FileOutputStream(path+filename);
          save.write(buffer);
          save.flush();
          save.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          return false;
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }
        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
        ));

        File k = new File(path, filename);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, "Ohhh Ringtone");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        values.put(MediaStore.Audio.Media.ARTIST, "weee");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        //Insert it into the database
        this.getContentResolver().insert(
                MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

        return true;
    }

    //Save in Notification Folder
    public boolean savenot(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=0;

        try {
           size = fIn.available();
           buffer = new byte[size];
           fIn.read(buffer);
           fIn.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }

        String path="/sdcard/media/audio/notifications/";

        String filename="ohhh"+".ogg";

        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}

        FileOutputStream save;
        try {
          save = new FileOutputStream(path+filename);
          save.write(buffer);
          save.flush();
          save.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          return false;
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }
        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
        ));

        File k = new File(path, filename);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, "Ohhh Notification");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        values.put(MediaStore.Audio.Media.ARTIST, "weee");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        //Insert it into the database
        this.getContentResolver().insert(
                MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

        return true;
    }
}
</code>```

答:
I'm just learning Android programming myself, but it seems like this is why you're always saving the first sound:

```<code>savering(R.raw.sound1)
</code>```

and

```<code>savenot(R.raw.sound1)
</code>```

Both of those are explicitly saving the first sound.  Unless you've written a separate function1 and function2 for each button.   But there's got to be a better way to manage saving than that.

Body:
I've been playing around with this code and I'm obviously trying to make a soundboard that will save ringtones on longclicks and etc.

Though, this is the basic code for one button. I've been duplicating the same code on top of each other, trying to make arrays, just everything.. I can't get this code to work the way I want it to.

When they are multiple buttons and more codes.

I can get the sounds to all play for the buttons.  I can get the menu to pop up for each button. Tho, the first button is always the one that gets saved, and the rest just fall off the map.

I assume that my data flow on the following code is not getting cut off and being picked up by the other sound buttons. Either way, it doesn't work. Please help me.

public class Soundboard extends Activity {
    private SoundManager mSoundManager;

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

        mSoundManager = new SoundManager();
        mSoundManager.initSounds(getBaseContext());
        mSoundManager.addSound(1, R.raw.sound1);

        Button SB = (Button)findViewById(R.id.sound1);

        SB.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
               mSoundManager.playSound(1);
            }
        });

        Button btn = (Button) findViewById(R.id.sound1);
        registerForContextMenu(btn);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Save as...");
        menu.add(0, v.getId(), 0, "Ringtone");
        menu.add(0, v.getId(), 0, "Notification");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(item.getTitle()=="Ringtone"){function1(item.getItemId());}
        else if(item.getTitle()=="Notification"){function2(item.getItemId());}
        else {return false;}
        return true;
    }

    public void function1(int id){
        if (savering(R.raw.sound1)) {
          // Code if successful
          Toast.makeText(this, "Saved as Ringtone", Toast.LENGTH_SHORT).show();
        }
        else
        {
          // Code if unsuccessful
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
        }

    }
    public void function2(int id){
        if (savenot(R.raw.sound1)) {
          // Code if successful
          Toast.makeText(this, "Saved as Notification", Toast.LENGTH_SHORT).show();
        }
        else
        {
          // Code if unsuccessful
          Toast.makeText(this, "Failed - Check your SDCard", Toast.LENGTH_SHORT).show();
        }
    }

    //Save into Ring tone Folder
    public boolean savering(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=50;

        try {
           size = fIn.available();
           buffer = new byte[size];
           fIn.read(buffer);
           fIn.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }

        String path="/sdcard/media/audio/ringtones/";

        String filename="ohhh"+".ogg";

        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}

        FileOutputStream save;
        try {
          save = new FileOutputStream(path+filename);
          save.write(buffer);
          save.flush();
          save.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          return false;
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }
        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
        ));

        File k = new File(path, filename);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, "Ohhh Ringtone");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        values.put(MediaStore.Audio.Media.ARTIST, "weee");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        //Insert it into the database
        this.getContentResolver().insert(
                MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

        return true;
    }

    //Save in Notification Folder
    public boolean savenot(int ressound){
        byte[] buffer=null;
        InputStream fIn = getBaseContext().getResources().openRawResource(ressound);
        int size=0;

        try {
           size = fIn.available();
           buffer = new byte[size];
           fIn.read(buffer);
           fIn.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }

        String path="/sdcard/media/audio/notifications/";

        String filename="ohhh"+".ogg";

        boolean exists = (new File(path)).exists();
        if (!exists){new File(path).mkdirs();}

        FileOutputStream save;
        try {
          save = new FileOutputStream(path+filename);
          save.write(buffer);
          save.flush();
          save.close();
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          return false;
        } catch (IOException e) {
          // TODO Auto-generated catch block
          return false;
        }
        sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)
        ));

        File k = new File(path, filename);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, "Ohhh Notification");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
        values.put(MediaStore.Audio.Media.ARTIST, "weee");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        //Insert it into the database
        this.getContentResolver().insert(
                MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath()), values);

        return true;
    }
}

Body:
I'm just learning Android programming myself, but it seems like this is why you're always saving the first sound:

savering(R.raw.sound1)

and

savenot(R.raw.sound1)

Both of those are explicitly saving the first sound.  Unless you've written a separate function1 and function2 for each button.   But there's got to be a better way to manage saving than that.