问:
Calculated columns as axis & value
I have a bunch of calculated DAX columns that I want to show as a visual. If I use a normal bar chart I get the following image, Barchart 1, where because I do not have any fields in the axis field. The titles of each of the calculated columns are what I want the x-axis to be similar to how it is in the funnel chart below.

The funnel chart only requires the value field to be filled in and it creates the following image which is kind of what I want but it needs to be vertical similar to the last image.

This final image, Barchart 3 is what I want to achieve with my calculated columns but so far I have had no luck in figuring this out. This visual was created using a different file which is irrelevant to the project I am working on now.  I believe that if I could unpivot the calculated columns then it would create the graph I am looking for but I can't figure out how to unpivot columns that are created in DAX. Is there a way to unpivot DAX columns or a visual on the marketplace to accomplish what I am trying to do? Or would I need to create my own custom visual to accomplish this?  Other ideas/thoughts?

Sample data file

答:
I ended up finding a solution to this. It doesn't maintain relationships but it works. </p>

```<code>Totals Table =
UNION(
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[January 2020]),"Month","January 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[February 2020]), "Month", "February 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[March 2020]),"Month","March 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[April 2020]), "Month", "April 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[May 2020]),"Month","May 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[June 2020]), "Month", "June 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[July 2020]),"Month","July 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[August 2020]), "Month", "August 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[September 2020]),"Month","September 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[October 2020]), "Month", "October 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[November 2020]),"Month","November 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[December 2020]), "Month", "December 2020"))
</code>```

Title: Calculated columns as axis & value

Body:
I ended up finding a solution to this. It doesn't maintain relationships but it works.

Totals Table =
UNION(
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[January 2020]),"Month","January 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[February 2020]), "Month", "February 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[March 2020]),"Month","March 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[April 2020]), "Month", "April 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[May 2020]),"Month","May 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[June 2020]), "Month", "June 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[July 2020]),"Month","July 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[August 2020]), "Month", "August 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[September 2020]),"Month","September 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[October 2020]), "Month", "October 2020"),
    SUMMARIZE(Sheet4,"Cost",SUM(Sheet4[November 2020]),"Month","November 2020"),
    SUMMARIZE(Sheet4, "Cost", SUM(Sheet4[December 2020]), "Month", "December 2020"))


来源: stackexchange

问:
Angular 8 Async call not waiting for promise to complete and results as bad request
i want my async call not to go to next statements until its completed, but its still going and also after completion of the request it results error as bad request even though the url path and http headers are correct.if i do it using observable and subscribe way its working but going to next statements before completing the request, so i thought promise async/await could help but am i doing anything wrong, any help is very much appreciable. Here is my code.

myapp.service.ts

```<code>//Because we are not using a type checker, so the response should be extracted. Add this function after the constructor for extract it.
private extractData(res: Response) {
    let body = res;
    return body || {};
  }
private handleError(error) {
    return throwError(error);
  }
async getEntityDependencies(entitytype: string) {
    try {
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return await this.http.get(this.endpoint, authheader).pipe(map(this.extractData), catchError(this.handleError)).toPromise();
    }
    catch (error) {
      console.log(error);
    }
  }
</code>```

newform.component.ts

```<code>async CreateForm() {
  // const data = await this.rest.getEntityDependencies(this.dataservice.entitytype)
  await this.rest.getEntityDependencies(this.dataservice.entitytype).then((data: {}) => { // data is getting undefined since request results Bad request
    // my stuff using data...
  }, error => {
    console.log(error, "Error from API");
  });
}
</code>```

答:
there are two issues in the code

first you don't need to return await

```<code>async getEntityDependencies(entitytype: string) {
    try {
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return this.http.get(this.endpoint, authheader)
         .pipe(
            map(this.extractData),
            tap(data => console.log('data in service', data))
            catchError(this.handleError)
         ).toPromise();
    }
    catch (error) {
      console.log(error);
    }
  }

</code>```

second this method

```<code>async CreateForm() {
  try
  {
     const data = await this.rest.getEntityDependencies(this.dataservice.entitytype);
     console.log('data', data);
  }
  catch(ex) {
     console.error(ex);
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i want my async call not to go to next statements until its completed, but its still going and also after completion of the request it results error as bad request even though the url path and http headers are correct.if i do it using observable and subscribe way its working but going to next statements before completing the request, so i thought promise async/await could help but am i doing anything wrong, any help is very much appreciable. Here is my code.

myapp.service.ts

//Because we are not using a type checker, so the response should be extracted. Add this function after the constructor for extract it.
private extractData(res: Response) {
    let body = res;
    return body || {};
  }
private handleError(error) {
    return throwError(error);
  }
async getEntityDependencies(entitytype: string) {
    try {
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return await this.http.get(this.endpoint, authheader).pipe(map(this.extractData), catchError(this.handleError)).toPromise();
    }
    catch (error) {
      console.log(error);
    }
  }

newform.component.ts

async CreateForm() {
  // const data = await this.rest.getEntityDependencies(this.dataservice.entitytype)
  await this.rest.getEntityDependencies(this.dataservice.entitytype).then((data: {}) => { // data is getting undefined since request results Bad request
    // my stuff using data...
  }, error => {
    console.log(error, "Error from API");
  });
}

Body:
there are two issues in the code

first you don't need to return await

async getEntityDependencies(entitytype: string) {
    try {
      var authheader = { headers: new HttpHeaders({ 'accesstoken': this.accesstoken, 'Content-Type': 'application/json', })};

      return this.http.get(this.endpoint, authheader)
         .pipe(
            map(this.extractData),
            tap(data => console.log('data in service', data))
            catchError(this.handleError)
         ).toPromise();
    }
    catch (error) {
      console.log(error);
    }
  }

second this method

async CreateForm() {
  try
  {
     const data = await this.rest.getEntityDependencies(this.dataservice.entitytype);
     console.log('data', data);
  }
  catch(ex) {
     console.error(ex);
  }
}


问:
How do I utilize a WHERE clause with a MONEY data type?
So to keep it simple, I'm working on a problem that requires a simple case of utilizing the WHERE clause to bring back records that have the field (we'll call it 'tax') equal to $0.00

So as per usual, I thought I could do:

WHERE tax = 0;

But I keep getting an error. And I'm pretty sure it's because of this weird MONEY data type. Now, just to be clear, I can't convert or change the datatype. I'm just looking for how I should be formatting that WHERE clause to make it grab those values in a data type like that. I've tried WHERE tax = 0.00, WHERE tax = $0.00, etc. etc..

Thanks in advance

答:
You need to cast the value to money:

```<code>where tax = 0::money
</code>```

or cast the money type to numeric:

```<code>where tax::numeric = 1.23
</code>```

or use a string value:

```<code>where tax = '0'
</code>```

But you should really try to convert that column to a different type

Body:
You need to cast the value to money:

where tax = 0::money

or cast the money type to numeric:

where tax::numeric = 1.23

or use a string value:

where tax = '0'

But you should really try to convert that column to a different type


问:
How to disable user input for materialize autocomplete
Essentially, I want to force the user to be able to only select from the given values.

E.g when the user either selects or clicks inside the text box then it should display him/her some of the values (e.g Microsoft and google) and then he should be able to select either one of them or type a and then select apple but under no circumstances, he should be able to input or select anything that's not in the data/values.

CodePen: https://codepen.io/textech/pen/WNvrLMp

```<code>  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },

    });
  });
</code>```

答:
Passing 'minLength: 0' into the initialisation brings up the options as soon as you click into the text field:

```<code>document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },
      minLength: 0,

    });
  });
</code>```

Forked codepen:

https://codepen.io/doughballs/pen/XWbXQZY

Documentation:

https://materializecss.com/autocomplete.html#options

EDIT

I've added a listener to the autocomplete (jQuery but you can rework if necessary) - it hooks into the instance to check 'count', which is how many options are currently being returned. If this is 0 - ie no match - we clear the autocomplete.

I'll update the codepen :D

```<code>$('#autocomplete-input').on('keyup',function(){
  console.log('keyup')
   if ( instances[0].count === 0 ) {
     console.log('no matches');
     $('#autocomplete-input').val('');
   }
})
</code>```

Body:
Essentially, I want to force the user to be able to only select from the given values.

E.g when the user either selects or clicks inside the text box then it should display him/her some of the values (e.g Microsoft and google) and then he should be able to select either one of them or type a and then select apple but under no circumstances, he should be able to input or select anything that's not in the data/values.

CodePen: https://codepen.io/textech/pen/WNvrLMp

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },

    });
  });

Body:
Passing 'minLength: 0' into the initialisation brings up the options as soon as you click into the text field:

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },
      minLength: 0,

    });
  });

Forked codepen:

https://codepen.io/doughballs/pen/XWbXQZY

Documentation:

https://materializecss.com/autocomplete.html#options

EDIT

I've added a listener to the autocomplete (jQuery but you can rework if necessary) - it hooks into the instance to check 'count', which is how many options are currently being returned. If this is 0 - ie no match - we clear the autocomplete.

I'll update the codepen :D

$('#autocomplete-input').on('keyup',function(){
  console.log('keyup')
   if ( instances[0].count === 0 ) {
     console.log('no matches');
     $('#autocomplete-input').val('');
   }
})


问:
RegEx find string containing numbers with one space, two spaces or no space at all followed by / and four numbers
I need to use RegEx to find a string in Word document. The string contains numbers{1;5} with one space, two spaces or no space at all followed by / and four numbers{4} which denotes a year in which the document was created.

The strings I need to find are like these:

45 /2017

125 /2019

1245 /2018

12577 /2019

37589 /2017

but sometimes there is no space in between:

45/2017

125/2019

1245/2018

12577/2019

37589/2017

and sometimes there is two spaces:

45  /2017

125  /2019

1245  /2018

12577  /2019

37589  /2017

but it's always in the same place - the space or two spaces. It's always after the first string of numbers, which are never more than 5 digits - therefore I type [0-9]{1;5} in RegEx.

But when I tried to build this RegEx expression in Word's Ctrl+H find and replace dialog box, and I test it against the Word's document I cannot build universal expression to find these strings with space and no space. The ? is not working for me. I've read here that ? should find one space or no space, but when I'm testing it in my Word document it finds a string with two spaces inside, but not the one with one space or no space at all.

Here are the RegExs I've tried, which failed to match both strings with no space inside like 4125/2019, as well as similar strings with one or two spaces:

[0-9]{1;5} ?/[0-9]{4}

[0-9]{1;5}\s?/[0-9]{4}

[0-9]{1;5}[ ]{0;2}/[0-9]{4}    this gives an error but [0-9]{1;5}[ ]{1;2}/[0-9]{4} finds 125 /2019 but doesn't find 125/2019 and 12577/2019.

In Polish version of MS Word/Excel we use ; instead of , in formulas, but I tried it all with colon or semi-colon interchangeably.

I've read these sources: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

and

Regex- Space or no space

Analyst_Cave

Regular Expression Tester

答:
You can use a Word wildcard Find expression like:

```<code><[0-9 ]{1;7}/[0-9]{4}>
</code>```

without the need to involve the RegEx library.

Body:
You can use a Word wildcard Find expression like:

<[0-9 ]{1;7}/[0-9]{4}>

without the need to involve the RegEx library.


问:
Does setting a passed in array in JS to null at the end of the function have any benefit?
I recently came across a bit of code at work that has me stumped what the original coder was thinking. The gist of the code was this:

```<code>function func1(array1) {
   var returnVal = false;

   try
   {
      // Do something. (No effect on array1)
   }

   catch (e)
   {
      CallDebugger(e.description);
   }

   finally
   {
      // Clean up the memory?
      array1 = null;
   }

   return returnVal;
}

function func2() {
   var arr = [1,2,3]
   var ret = func1(arr)
}
</code>```

My question is: what exactly does setting array1 to null at the end of func1 do? Does it change arr to null in func2? Or does changing array1 to null create a new reference to a null variable? Something else?

Does this have any potential benefits as far as memory leak is concerned?

答:
It seems quite unreasonable to do array1 = null in that case.

What exactly does setting array1 to null at the end of func1 do? Does it change arr to null in func2?

Basically, array1 is a copy of reference to arr in func2. So that assignment will change variable only in func1 scope and nowhere else, so arr in func2 stays unchanged. And doing so in finally statement at the end of a function, is not useful, because func1 ends right after finnaly statement and reference to array1 will be garbage collected and no one will ever know that it was set to null(expect if it was in a closure before finally, but you say it's not).

Or does changing array1 to null create a new reference to a null variable?

It just sets array1's value to null, and as I said before: arr in func2 won't be changed in that case.

:)

Body:
I recently came across a bit of code at work that has me stumped what the original coder was thinking. The gist of the code was this:

function func1(array1) {
   var returnVal = false;

   try
   {
      // Do something. (No effect on array1)
   }

   catch (e)
   {
      CallDebugger(e.description);
   }

   finally
   {
      // Clean up the memory?
      array1 = null;
   }

   return returnVal;
}

function func2() {
   var arr = [1,2,3]
   var ret = func1(arr)
}

My question is: what exactly does setting array1 to null at the end of func1 do? Does it change arr to null in func2? Or does changing array1 to null create a new reference to a null variable? Something else?

Does this have any potential benefits as far as memory leak is concerned?


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答:
The error is in your conditional expression. When you negate the first expression

```<code>!(c== ' ' || c== '\n' ||c == '\t')
</code>```

you get:

```<code>c!= ' ' && c!= '\n' &&c != '\t'
</code>```

and not you defined in your question.

Remember:

(A && B) is the same as (!A || !B)

ContentLicense: CC BY-SA 3.0

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}

Body:
The error is in your conditional expression. When you negate the first expression

!(c== ' ' || c== '\n' ||c == '\t')

you get:

c!= ' ' && c!= '\n' &&c != '\t'

and not you defined in your question.

Remember:

(A && B) is the same as (!A || !B)


问:
Redshift: Convert text to timestamp
I have a score column with json value -

```<code>{"Choices":null,
"timestamp":"1579650266955",
"scaledScore":null}
</code>```

I am using the below sql to retrive the timestamp value --

```<code>select json_extract_path_text(score, 'timestamp') from schema.table limit 10;
</code>```

Now I need to convert it to actual timestamp. I have been trying few things, but all of them is failing with

```<code>ERROR:  Invalid data
DETAIL:
  -----------------------------------------------
  error:  Invalid data
  code:      8001
  context:   Invalid format or data given: 1579650266955
  query:     2057693
  location:  funcs_timestamp.cpp:261
  process:   query1_120_2057693 [pid=6659]
  -----------------------------------------------
</code>```

SQLs I have tried --

```<code>select cast(json_extract_path_text(score, 'timestamp') as timestamp) from schema.table limit 10;

select cast(replace(json_extract_path_text(score, 'timestamp'), 'T','') as timestamp) from schema.table limit 10;

</code>```

```<code>select timestamp 'epoch' + json_extract_path_text(score, 'timestamp') * interval '1 second' from schema.table limit 10;
ERROR:  operator does not exist: text * interval
HINT:  No operator matches the given name and argument type(s). You may need to add explicit type casts.
Time: 451.429 ms
</code>```

答:
Below SQL worked --</p>

```<code>select timestamp 'epoch' + cast(json_extract_path_text(score, 'timestamp') as bigint)/1000 * interval '1 second' from schema.table limit 10;
</code>```

Title: Redshift: Convert text to timestamp

Body:
I have a score column with json value -

{"Choices":null,
"timestamp":"1579650266955",
"scaledScore":null}

I am using the below sql to retrive the timestamp value --

select json_extract_path_text(score, 'timestamp') from schema.table limit 10;

Now I need to convert it to actual timestamp. I have been trying few things, but all of them is failing with

ERROR:  Invalid data
DETAIL:
  -----------------------------------------------
  error:  Invalid data
  code:      8001
  context:   Invalid format or data given: 1579650266955
  query:     2057693
  location:  funcs_timestamp.cpp:261
  process:   query1_120_2057693 [pid=6659]
  -----------------------------------------------

SQLs I have tried --

select cast(json_extract_path_text(score, 'timestamp') as timestamp) from schema.table limit 10;

select cast(replace(json_extract_path_text(score, 'timestamp'), 'T','') as timestamp) from schema.table limit 10;

select timestamp 'epoch' + json_extract_path_text(score, 'timestamp') * interval '1 second' from schema.table limit 10;
ERROR:  operator does not exist: text * interval
HINT:  No operator matches the given name and argument type(s). You may need to add explicit type casts.
Time: 451.429 ms

Body:
Below SQL worked --

select timestamp 'epoch' + cast(json_extract_path_text(score, 'timestamp') as bigint)/1000 * interval '1 second' from schema.table limit 10;


问:
UIButton setImage not working
I'm losing my mind over this one. I have UIButton connected as Outlet. I want to change it's image. In the viewDidLoad function, I try to set the image like so:

```<code>[button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];
</code>```

Nothing happens. However, if I use ImagePicker, it somehow works. In the ImagePickers function "didFinishPickingImage", I repeat the exactly same command as above for setting image and it works, the image is displayed normally.

I've been thinking that maybe the button's image is not refreshing itself, but trying to call [button1 setNeedsDisplay], or [button1.imageView setNeedsDisplay] or even [button1.imageView.image setNeedsDisplay] does nothing.

Does anyone have any idea about this? I've wasted two hours by now and I'm really getting frustrated, because I'm certain that the reason must be so stupid it's unbelivable.

答:
With images, you have to import them into the project not as references but as copies. So when you go to add files to project, choose "Create groups" instead of "Create folder references". Also make sure "Copy items if needed" is checked.

This is confusing because importing as references works when you are using images as textures (e.g. for Sprites). However, it doesn't work when you want to use images for buttons (e.g. for using image name in [UIImage imageNamed:@"house.png"]

Title: UIButton setImage not working

Body:
I'm losing my mind over this one. I have UIButton connected as Outlet. I want to change it's image. In the viewDidLoad function, I try to set the image like so:

[button1 setImage:[UIImage imageNamed:@"house.png"] forState:UIControlStateNormal];

Nothing happens. However, if I use ImagePicker, it somehow works. In the ImagePickers function "didFinishPickingImage", I repeat the exactly same command as above for setting image and it works, the image is displayed normally.

I've been thinking that maybe the button's image is not refreshing itself, but trying to call [button1 setNeedsDisplay], or [button1.imageView setNeedsDisplay] or even [button1.imageView.image setNeedsDisplay] does nothing.

Does anyone have any idea about this? I've wasted two hours by now and I'm really getting frustrated, because I'm certain that the reason must be so stupid it's unbelivable.


问:
Trying to sum the values of a dynamic HTML table column
I'm trying to sum the values in the second column (title heading='Value'), however it currently always outputs 0. What am I missing??

(Also the table is populated from a javascript function, which I have included at the bottom of this question).

HTML:

```<code><table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>
</code>```

JS:

```<code>// code to sum CPC column
        var sum1 = 0;
        $("#output_table Value").each(function() {
          sum1 +=  getnum($(this).find("td:eq(1)").text());
          function getnum(t){
            if(isNumeric(t)){
                return parseInt(t,10);
            }
            return 0;
                function isNumeric(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
                }
          }
        });
        $("#sum1").text(sum1);
</code>```

JS which populates table:

```<code> $('#sales_order_form_button').click(function(){
    let table_info = [];
    $('.campaignstrategy input[type=checkbox]').each(
        function(index, value){
        if($(this).is(':checked')){
            table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                }
            );
        }
    });
    let base64str=btoa(JSON.stringify(table_info));

    window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i=0;i<data_from_page_1.length;i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }
</code>```

答:
If you have a tbody, it will make things easier to select:

var total = $('tbody td:nth-child(2)').toArray().reduce(function (sum, el) {
  var value = isNaN($(el).text()) ? 0 : parseInt($(el).text(), 10);
  return sum + value;
}, 0);

$('#sum1').text(total);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr> <th>Name</th><th>Value</th> </tr>
  </thead>
  <tbody>
    <tr> <td>A</td><td>2</td> </tr>
    <tr> <td>B</td><td>5</td> </tr>
    <tr> <td>C</td><td>3</td> </tr>
  </tbody>
  <tfoot>
    <tr> <td>Total CPC:</td><td id="sum1"></td> </tr>
  </tfoot>
</table></code>```

Body:
I'm trying to sum the values in the second column (title heading='Value'), however it currently always outputs 0. What am I missing??

(Also the table is populated from a javascript function, which I have included at the bottom of this question).

HTML:

            Name
            Value

                Total CPC:

JS:

// code to sum CPC column
        var sum1 = 0;
        $("#output_table Value").each(function() {
          sum1 +=  getnum($(this).find("td:eq(1)").text());
          function getnum(t){
            if(isNumeric(t)){
                return parseInt(t,10);
            }
            return 0;
                function isNumeric(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
                }
          }
        });
        $("#sum1").text(sum1);

JS which populates table:

 $('#sales_order_form_button').click(function(){
    let table_info = [];
    $('.campaignstrategy input[type=checkbox]').each(
        function(index, value){
        if($(this).is(':checked')){
            table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                }
            );
        }
    });
    let base64str=btoa(JSON.stringify(table_info));

    window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i=0;i<data_from_page_1.length;i++){
            let row = $("

");
            let recordName = $("	").text(data_from_page_1[i].name);
            let recordValue = $("	").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

Body:
If you have a tbody, it will make things easier to select:

var total = $('tbody td:nth-child(2)').toArray().reduce(function (sum, el) {
  var value = isNaN($(el).text()) ? 0 : parseInt($(el).text(), 10);
  return sum + value;
}, 0);

$('#sum1').text(total);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr> <th>Name</th><th>Value</th> </tr>
  </thead>
  <tbody>
    <tr> <td>A</td><td>2</td> </tr>
    <tr> <td>B</td><td>5</td> </tr>
    <tr> <td>C</td><td>3</td> </tr>
  </tbody>
  <tfoot>
    <tr> <td>Total CPC:</td><td id="sum1"></td> </tr>
  </tfoot>
</table>


问:
Bash: Spurious "command not found" messages (I think)
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

```<code>inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}
</code>```

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

```<code>$ inDir "/tmp" "touch hi"
</code>```

correctly creates the file /tmp/hi, but also gives the error:

```<code>[2: command not found
</code>```

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

答:
Life is simpler if you use sub-shells

```<code>( cd "$dir"; $action )
</code>```

Has no effect on the current shell.

Body:
I am trying to write a simple utility function in Bash, which will perform an "action" in the given directory.  So I am basically abstracting the "go to a directory, do something, and come back" pattern.

inDir() {
    if [$# -le 1]; then
        return;
    else
        local dir="$1";
        local action="$2";
        local cwd=`pwd`;

        if [ -d "$dir" ]; then
            cd "$dir";
            $action;
            cd "$cwd";
        else
            return;
        fi
    fi
}

Unfortunately, I get what I think is a spurious error when I run this, and I'm not sure where it is coming from.  For example:

$ inDir "/tmp" "touch hi"

correctly creates the file /tmp/hi, but also gives the error:

[2: command not found

I'm not sure if this matters to reading the error, but my prompt starts off with a "[".

Any help?

Body:
Life is simpler if you use sub-shells

( cd "$dir"; $action )

Has no effect on the current shell.


问:
Horizontal scrollbar on tabPage
Working in Design mode on Visual Studio 2010...

I am trying to get an horizontal scrollbar on a tabPage. From what I understood by reading here and there, setting the AutoScroll property of the tabPage to True should be enough to get scrollbars.

When I place a element on my tabPage that exceeds the bottom limit of the tabPage, I get an vertical scrollbar. But when I make an element exceed the right limit of the tabPage, no horizontal scrollbar appears.

What am I doing wrong?

答:
Horizontal scrollbar problem can be caused Also if Dock = Fill .
It should be Dock = None with Anchor= Right or Anchor= Left but not both.</p>

Title: Horizontal scrollbar on tabPage


问:
How to automatically sync s3 bucket to a local folder
Im trying to have a replica of my s3 bucket in a local folder. it should be updated when a change occurs on the bucket.
I see many options to do it using lambda functions but im asking about the usage of s3 cli command:

```<code>aws s3 sync s3://my-bucket . --delete
</code>```

which will download any files exists on the bucket, and also delete local files that exists locally but missing from the bucket (expected behavior).

Is there any problem to loop it forever with few sec of delay, like?

```<code>while true; do aws s3 sync s3://my-bucket . --delete; sleep 3s; done
</code>```

Is there any limitation of the number of api calls i can do per second ? is there a better solution ?

答:
Are you on linux? You could stick your command in a shell script and run it as a cronjob

```<code>* * * * * /path/to/your/script
</code>```

^ Runs every minute

```<code>*/10 * * * * /path/to/your/script
</code>```

^ Runs every 10 minutes

That would be much more reliable than a bash script in a loop.

Body:
Im trying to have a replica of my s3 bucket in a local folder. it should be updated when a change occurs on the bucket.
I see many options to do it using lambda functions but im asking about the usage of s3 cli command:

aws s3 sync s3://my-bucket . --delete

which will download any files exists on the bucket, and also delete local files that exists locally but missing from the bucket (expected behavior).

Is there any problem to loop it forever with few sec of delay, like?

while true; do aws s3 sync s3://my-bucket . --delete; sleep 3s; done

Is there any limitation of the number of api calls i can do per second ? is there a better solution ?

Body:
Are you on linux? You could stick your command in a shell script and run it as a cronjob

* * * * * /path/to/your/script

^ Runs every minute

*/10 * * * * /path/to/your/script

^ Runs every 10 minutes

That would be much more reliable than a bash script in a loop.


问:
comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

```<code>>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False
</code>```

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

答:
you can use regex matching for that.</p>

```<code>import re

def occurs_within(word1, word2):
    #build regex, basically inserting '.*' around any character in word2. In a regex, '.*' means any character any amount of time (even 0)
    regex = '.*{}.*'.format('.*'.join(list(word2)))

    #matching
    return bool(re.match(regex, word1))
</code>```

Body:
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

Body:
you can use regex matching for that.

import re

def occurs_within(word1, word2):
    #build regex, basically inserting '.*' around any character in word2. In a regex, '.*' means any character any amount of time (even 0)
    regex = '.*{}.*'.format('.*'.join(list(word2)))

    #matching
    return bool(re.match(regex, word1))


问:
What is limit of Nested IF statement in MS Word?
Is there any limit on how many nesting we can use in Nested IF statement in Microsoft Word?

Also, if limit can be different based on office version?

答: The nesting limit is 20 in all Word versions.</p>


问:
How to detect save and tab change event using angular8 with bootstrap4
i have used bootstrap4 tabs in angular8. Now if i have not filled details in first tab, (i.e) user tab and click on submit, then the other tab must be disabled, once the submit button is click then the other tab must be enabled.
Here based on click of other tab, the contents in the other tab must be loaded, if other tab is not clicked, then the details in others tab must not be filled. I have tried by using click event and tabChange event, but everything works in app.component but the data doesnt come to the user or other tab based on click on other tab.

I am not getting anyway to move forward, i have even used event emitters and storage inside the app, through service files, but nothing worked for me.

Demo

答:
I looked at your Demo and I think I understand your problem. I personally am a fan of using ReplaySubjects, and EventEmitters to pass data up and down through my components. Here is a working demo :
 Working Demo

Let me know if it is not what you were looking for.


问:
How to fix 'handleWindowVisibility: no activity for token android.os.BinderProxy'?
I'm working on a small app, that was tested and was working great along the way. When I added new code to have the app send info to my Firebase Realtime Database, it just won't launch my app. It will flash the MainActivity for a split second then goes black.

When I remove the code I entered, itenter code here keeps on doing the same. Although the same code (after removal of what I thought was bad) was working before. I've digged through forums, and I haven't found any piece of code that references a dialog box before the activity has finished

```<code>,,,
/com.fromfire.fantastysurvivor W/ActivityThread: handleWindowVisibility:
no activity for token android.os.BinderProxy@356e9f5
2019-05-08 07:46:47.891 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:47.998 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@c10e219
2019-05-08 07:46:48.014 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.108 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@2818389
2019-05-08 07:46:48.116 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.238 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@b4e046d
2019-05-08 07:46:48.254 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.359 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@685e2dd
2019-05-08 07:46:48.383 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
,,,

,,,java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class SetupActivity extends AppCompatActivity
{

    private EditText UserName, FullName, CountryName;
    private Button SaveInformationButton;
    private CircleImageView ProfileImage;
    private FirebaseAuth mAuth;
    private DatabaseReference UsersRef;
    private ProgressDialog loadingBar;

    String currentUserID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);

        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);

        UserName = (EditText) findViewById(R.id.setup_username);
        FullName = (EditText) findViewById(R.id.set_full_name);
        CountryName = (EditText) findViewById(R.id.setup_country_name);
        SaveInformationButton = (Button) findViewById(R.id.setup_information_button);
        ProfileImage = (CircleImageView) findViewById(R.id.setup_profile_image);
        loadingBar = new ProgressDialog(this);

        SaveInformationButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                SaveAccountSetupInformation();
            }
        });

    }

    private void SaveAccountSetupInformation()
    {
        String username = UserName.getText().toString();
        String fullname = FullName.getText().toString();
        String country = CountryName.getText().toString();

        if(TextUtils.isEmpty(username))
        {
            Toast.makeText(SetupActivity.this, "Please enter Username", Toast.LENGTH_SHORT).show();
        }
        if(TextUtils.isEmpty(fullname))
        {
            Toast.makeText(SetupActivity.this, "Please enter your full name", Toast.LENGTH_SHORT).show();
        }
        if(TextUtils.isEmpty(country))
        {
            Toast.makeText(SetupActivity.this, "Please enter you country", Toast.LENGTH_SHORT).show();
        }
        else
        {

            loadingBar.setTitle("Saving information...");
            loadingBar.setMessage("Please wait...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            HashMap userMap = new HashMap();
            userMap.put("username", username);
            userMap.put("fullname", fullname);
            userMap.put("country", country);
            userMap.put("status", "Hey There");
            UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if(task.isSuccessful())
                    {
                        SendUserToMainActivity();
                        Toast.makeText(SetupActivity.this, "Account created successfully", Toast.LENGTH_LONG).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(SetupActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }
            });
        }
    }

    private void SendUserToMainActivity()
    {
        Intent mainIntent = new Intent(SetupActivity.this, MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);

    }
}
,,,
Build Gradle (App)
,,,
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.fromfire.fantastysurvivor"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.google.firebase:firebase-auth:16.2.1'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
    implementation 'com.google.firebase:firebase-messaging:17.6.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
}
apply plugin: 'com.google.gms.google-services'
,,,

MainActivity
,,,java
package com.fromfire.fantastysurvivor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private FirebaseAuth mAuth;
    private DatabaseReference UsersRef;

    String currentUserID;

    List<AuthUI.IdpConfig> providers = Arrays.asList(
            new AuthUI.IdpConfig.EmailBuilder().build(),
            new AuthUI.IdpConfig.GoogleBuilder().build());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

        //Navigation Drawer
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        FirebaseUser currentUser = mAuth.getCurrentUser();

        if(currentUser == null)
        {
            SendUserToLoginActivity();
        }
        else
        {
            CheckUserExistence();
        }
    }

    private void CheckUserExistence()
    {
        final String current_user_id = mAuth.getCurrentUser().getUid();

        UsersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                if(!dataSnapshot.hasChild(current_user_id))
                {
                    SendUserToSetupActivity();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void SendUserToSetupActivity()
    {
        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
        setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(setupIntent);
        finish();
    }

    private void SendUserToLoginActivity()
    {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);
        finish();
    }

    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment;

        if (id == R.id.nav_leader) {

        } else if (id == R.id.nav_mypicks) {

        } else if (id == R.id.nav_tribe) {

        } else if (id == R.id.nav_results) {

        } else if (id == R.id.nav_chat) {

        } else if (id == R.id.nav_settings) {

        } else if (id == R.id.nav_about) {

        } else if (id == R.id.nav_donate) {

        } else if (id == R.id.nav_logout) {
            mAuth.signOut();
            SendUserToLoginActivity();

        } else if (id == R.id.nav_feedback) {

        } else if (id == R.id.nav_profile) {

        } else if (id == R.id.nav_home) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
,,,
</code>```

I am expecting to after I have logged in with a user, to have that uID reference to my firebase database, and if there is no user with that uID, that it would redirect them to the SetupActivity class for more info input.

Right now the screen flashes for a split second (Iguess showing my MainActivity) then goes black.

答: Check whether you have granted the permissions required by the app. This fixed the error on my end</p>

Body:
I'm working on a small app, that was tested and was working great along the way. When I added new code to have the app send info to my Firebase Realtime Database, it just won't launch my app. It will flash the MainActivity for a split second then goes black.

When I remove the code I entered, itenter code here keeps on doing the same. Although the same code (after removal of what I thought was bad) was working before. I've digged through forums, and I haven't found any piece of code that references a dialog box before the activity has finished

,,,
/com.fromfire.fantastysurvivor W/ActivityThread: handleWindowVisibility:
no activity for token android.os.BinderProxy@356e9f5
2019-05-08 07:46:47.891 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:47.998 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@c10e219
2019-05-08 07:46:48.014 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.108 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@2818389
2019-05-08 07:46:48.116 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.238 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@b4e046d
2019-05-08 07:46:48.254 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
2019-05-08 07:46:48.359 3306-3306/com.fromfire.fantastysurvivor
W/ActivityThread: handleWindowVisibility: no activity for token
android.os.BinderProxy@685e2dd
2019-05-08 07:46:48.383 3306-3306/com.fromfire.fantastysurvivor V/FA:
onActivityCreated
,,,

,,,java
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

import de.hdodenhof.circleimageview.CircleImageView;

public class SetupActivity extends AppCompatActivity
{

    private EditText UserName, FullName, CountryName;
    private Button SaveInformationButton;
    private CircleImageView ProfileImage;
    private FirebaseAuth mAuth;
    private DatabaseReference UsersRef;
    private ProgressDialog loadingBar;

    String currentUserID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);

        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID);

        UserName = (EditText) findViewById(R.id.setup_username);
        FullName = (EditText) findViewById(R.id.set_full_name);
        CountryName = (EditText) findViewById(R.id.setup_country_name);
        SaveInformationButton = (Button) findViewById(R.id.setup_information_button);
        ProfileImage = (CircleImageView) findViewById(R.id.setup_profile_image);
        loadingBar = new ProgressDialog(this);

        SaveInformationButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                SaveAccountSetupInformation();
            }
        });

    }

    private void SaveAccountSetupInformation()
    {
        String username = UserName.getText().toString();
        String fullname = FullName.getText().toString();
        String country = CountryName.getText().toString();

        if(TextUtils.isEmpty(username))
        {
            Toast.makeText(SetupActivity.this, "Please enter Username", Toast.LENGTH_SHORT).show();
        }
        if(TextUtils.isEmpty(fullname))
        {
            Toast.makeText(SetupActivity.this, "Please enter your full name", Toast.LENGTH_SHORT).show();
        }
        if(TextUtils.isEmpty(country))
        {
            Toast.makeText(SetupActivity.this, "Please enter you country", Toast.LENGTH_SHORT).show();
        }
        else
        {

            loadingBar.setTitle("Saving information...");
            loadingBar.setMessage("Please wait...");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            HashMap userMap = new HashMap();
            userMap.put("username", username);
            userMap.put("fullname", fullname);
            userMap.put("country", country);
            userMap.put("status", "Hey There");
            UsersRef.updateChildren(userMap).addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if(task.isSuccessful())
                    {
                        SendUserToMainActivity();
                        Toast.makeText(SetupActivity.this, "Account created successfully", Toast.LENGTH_LONG).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(SetupActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }
            });
        }
    }

    private void SendUserToMainActivity()
    {
        Intent mainIntent = new Intent(SetupActivity.this, MainActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mainIntent);

    }
}
,,,
Build Gradle (App)
,,,
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.fromfire.fantastysurvivor"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-core:16.0.8'
    implementation 'com.google.firebase:firebase-auth:16.2.1'
    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.firebaseui:firebase-ui-auth:4.3.1'
    implementation 'com.google.firebase:firebase-messaging:17.6.0'
    implementation 'de.hdodenhof:circleimageview:3.0.0'
}
apply plugin: 'com.google.gms.google-services'
,,,

MainActivity
,,,java
package com.fromfire.fantastysurvivor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;

import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private FirebaseAuth mAuth;
    private DatabaseReference UsersRef;

    String currentUserID;

    List<AuthUI.IdpConfig> providers = Arrays.asList(
            new AuthUI.IdpConfig.EmailBuilder().build(),
            new AuthUI.IdpConfig.GoogleBuilder().build());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

        //Navigation Drawer
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onStart()
    {
        super.onStart();

        FirebaseUser currentUser = mAuth.getCurrentUser();

        if(currentUser == null)
        {
            SendUserToLoginActivity();
        }
        else
        {
            CheckUserExistence();
        }
    }

    private void CheckUserExistence()
    {
        final String current_user_id = mAuth.getCurrentUser().getUid();

        UsersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                if(!dataSnapshot.hasChild(current_user_id))
                {
                    SendUserToSetupActivity();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void SendUserToSetupActivity()
    {
        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
        setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(setupIntent);
        finish();
    }

    private void SendUserToLoginActivity()
    {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);
        finish();
    }

    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment;

        if (id == R.id.nav_leader) {

        } else if (id == R.id.nav_mypicks) {

        } else if (id == R.id.nav_tribe) {

        } else if (id == R.id.nav_results) {

        } else if (id == R.id.nav_chat) {

        } else if (id == R.id.nav_settings) {

        } else if (id == R.id.nav_about) {

        } else if (id == R.id.nav_donate) {

        } else if (id == R.id.nav_logout) {
            mAuth.signOut();
            SendUserToLoginActivity();

        } else if (id == R.id.nav_feedback) {

        } else if (id == R.id.nav_profile) {

        } else if (id == R.id.nav_home) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}
,,,

I am expecting to after I have logged in with a user, to have that uID reference to my firebase database, and if there is no user with that uID, that it would redirect them to the SetupActivity class for more info input.

Right now the screen flashes for a split second (Iguess showing my MainActivity) then goes black.


问:
avformat code produce slightly different output than ffmpeg with same parameters - why?
I would like to achieve the exact same result as this ffmpeg command line call does from code:

```<code>ffmpeg -i CAMERARTSPLINK -c:v copy -an -movflags +frag_keyframe+empty_moov -f mp4
</code>```

When I run the above command it gives this binary result:

```<code>got 36 bytes:  0, 0, 0, 36, 102, 116, 121, 112, ..., 111, 54, 109, 112, 52, 49,
got 512 bytes: 0, 0, 3, 76, 109, 111, 111, 118, 0, 0, 0, ..., 132, 0, 0, 3, 0, 4, 0, 0, 3, 0, 202,
</code>```

The code can utilize ffmpeg libraries and includes, but I don't want to use ffmpeg as a program call (i.e. exec* functions are not preferred).

I have created a small demonstration code example with avformat for an RTSP H264 to MP4 remux.
The code is highly reuses horgh's nice videostreamer library.

I posted the sample code to pastebin.com (400 loc). It builds successfully but you need to link it against avformat, avdevice, avcodec and avutil.

I tried to do my best to reach the same result, however when I run this code, the first few bytes after byte #38 are different (maybe not just those, I did not compare anything after byte #548):

```<code>writeOutput: writing 36 bytes: 0, 0, 0, 36, 102, 116, 121, 112, ..., 111, 54, 109, 112, 52, 49,
writeOutput: writing 512 bytes: 0, 0, 0, 0, 109, 111, 111, 118, 0, 0, 0, ..., 132, 0, 0, 3, 0, 4, 0, 0, 3, 0, 202,
</code>```

You can see on the second line of my code's output starts with 0 0 0 0 109,

whereas the ffmpeg gave 0 0 3 76 109.

All the rest (even the bytes are not pasted here) data are totally the same (at least for the first 548 bytes).

What is wrong with my code? These 2 bytes seems super-important for decoding this stream.

答:
102, 116, 121, 112 in ascii is ftyp This is the mp4 format type box. 0, 0, 0, 36 is the size of the box

109, 111, 111, 118 in ascii is mdat This is the data box. 0, 0, 0, 0 is the size of the box.

In this case the size of the mdat box is unknown because we don't know the size of all the video and audio frames yet. So a placeholder of zero is used. When the file is finished the size value should be overwritten with the correct size

Body:
I would like to achieve the exact same result as this ffmpeg command line call does from code:

ffmpeg -i CAMERARTSPLINK -c:v copy -an -movflags +frag_keyframe+empty_moov -f mp4

When I run the above command it gives this binary result:

got 36 bytes:  0, 0, 0, 36, 102, 116, 121, 112, ..., 111, 54, 109, 112, 52, 49,
got 512 bytes: 0, 0, 3, 76, 109, 111, 111, 118, 0, 0, 0, ..., 132, 0, 0, 3, 0, 4, 0, 0, 3, 0, 202,

The code can utilize ffmpeg libraries and includes, but I don't want to use ffmpeg as a program call (i.e. exec* functions are not preferred).

I have created a small demonstration code example with avformat for an RTSP H264 to MP4 remux.
The code is highly reuses horgh's nice videostreamer library.

I posted the sample code to pastebin.com (400 loc). It builds successfully but you need to link it against avformat, avdevice, avcodec and avutil.

I tried to do my best to reach the same result, however when I run this code, the first few bytes after byte #38 are different (maybe not just those, I did not compare anything after byte #548):

writeOutput: writing 36 bytes: 0, 0, 0, 36, 102, 116, 121, 112, ..., 111, 54, 109, 112, 52, 49,
writeOutput: writing 512 bytes: 0, 0, 0, 0, 109, 111, 111, 118, 0, 0, 0, ..., 132, 0, 0, 3, 0, 4, 0, 0, 3, 0, 202,

You can see on the second line of my code's output starts with 0 0 0 0 109,

whereas the ffmpeg gave 0 0 3 76 109.

All the rest (even the bytes are not pasted here) data are totally the same (at least for the first 548 bytes).

What is wrong with my code? These 2 bytes seems super-important for decoding this stream.


问:
Simple Powershell: Output basic Text instead of formatted from Get-ADOrganizationalUnit
This really applies to almost any PS command but I'm running:

```<code>Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $strDomainDN -SearchScope OneLevel
</code>```

and the output looks like:

```<code>$_.Name
------
OU1
OU2
OU3
...
</code>```

And all I want is the actual list with not heading ($_.Name or the "------").  I know this is probably amazingly simple but also very frustrating when trying to format strings.  Any help would be appreciated.

答:
There are a bunch of ways to do this but one way is to pick off what you want with a foreach-object cmdlet. Assuming you want just the Name column you can do something like this:

```<code>13 >  dir | select name | foreach-object {$_.Name} | out-string
Contacts
Desktop
Documents
Downloads
Favorites
Links
Lync Recordings
Music
NetApp
Pictures
Podcasts
PowerShellASP
Saved Games
Searches
Tracing
Videos
Virtual Machines
</code>```

The Out-String forces it to output to a string instead of an array of strings for each line of the output.

Body:
This really applies to almost any PS command but I'm running:

Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase $strDomainDN -SearchScope OneLevel

and the output looks like:

$_.Name
------
OU1
OU2
OU3
...

And all I want is the actual list with not heading ($_.Name or the "------").  I know this is probably amazingly simple but also very frustrating when trying to format strings.  Any help would be appreciated.

Body:
There are a bunch of ways to do this but one way is to pick off what you want with a foreach-object cmdlet. Assuming you want just the Name column you can do something like this:

13 >  dir | select name | foreach-object {$_.Name} | out-string
Contacts
Desktop
Documents
Downloads
Favorites
Links
Lync Recordings
Music
NetApp
Pictures
Podcasts
PowerShellASP
Saved Games
Searches
Tracing
Videos
Virtual Machines

The Out-String forces it to output to a string instead of an array of strings for each line of the output.


问:
Laravel CKEditor5 - ClassicEditor is not Defined
I'm trying to replace an old version of CKEditor in a Laravel app due to dependency incompatibility with unisharp/laravel-ckeditor and Laravel 6. I've found the CKEditor 5 page with NPM installation instructions, but haven't been able to get it working. Here is my code:

resources/main.js

```<code>require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});
</code>```

webpack.mix.js

```<code>mix.js('resources/assets/js/main.js', 'public/js');
</code>```

layouts/master.blade.php

```<code><!doctype html>
<html>
  <head></head>
<body>
  <script src="{{ asset('js/main.js') }}"></script>
</body>
</html>
</code>```

jQuery is included (somehow; somewhat unfamiliar with webpack), but running a page that extends @extends('layouts.master') results in the following:

Uncaught ReferenceError: ClassicEditor is not defined

If I remove the require() statement from main.js and simply use the CDN link, everything works as expected:

```<code><script src="https://cdn.ckeditor.com/ckeditor5/16.0.0/classic/ckeditor.js"></script>
<script src="{{ asset('js/main.js') }}"></script>
</code>```

I'm doing something wrong, but I'm at a loss... Has anyone seen this issue before?

答:
Quite a simple solution that the documentation fails to reference, but you need to assign the value of require() to ClassicEditor:

```<code>var ClassicEditor = require('@ckeditor/ckeditor5-build-classic');
</code>```

Doing so allows correct reference in code.

Body:
I'm trying to replace an old version of CKEditor in a Laravel app due to dependency incompatibility with unisharp/laravel-ckeditor and Laravel 6. I've found the CKEditor 5 page with NPM installation instructions, but haven't been able to get it working. Here is my code:

resources/main.js

require('@ckeditor/ckeditor5-build-classic');

$(document).ready(function(){
  ClassicEditor.create($('#edit_about_text').get()[0]);
});

webpack.mix.js

mix.js('resources/assets/js/main.js', 'public/js');

layouts/master.blade.php

<!doctype html>

jQuery is included (somehow; somewhat unfamiliar with webpack), but running a page that extends @extends('layouts.master') results in the following:

Uncaught ReferenceError: ClassicEditor is not defined

If I remove the require() statement from main.js and simply use the CDN link, everything works as expected:

I'm doing something wrong, but I'm at a loss... Has anyone seen this issue before?

Body:
Quite a simple solution that the documentation fails to reference, but you need to assign the value of require() to ClassicEditor:

var ClassicEditor = require('@ckeditor/ckeditor5-build-classic');

Doing so allows correct reference in code.


问:
How to define class in Jenkinsfie
I'm trying to set up a jenkins pipeline in order to do some continuous integration and automated deployement.
Since I'm using Gitea, I have installed gitea plugin and configured it to execute my jenkins file pipeline.
So far, so good.

I have managed to code something that "work" but the code is horrible and I have to heavely use global variable and other "bad" thing.

So I thougth that rewrite the pipeline but using class in order to keep thing clean was a good idea, but I ended up running into one problem after another !
The problem is that I'm not reallu use to code in Groovy and I'm currently discovering Jenkins.

First, I failed to know where to declare the class, so I just put it outside the pipeline.

```<code>pipeline {
    agent any

    stages {

        stage('blabla') {
            steps {
                script {
                    def var = new MyClass()

                }
            }
        }
    }
}

class MyClass {

    /* Some propeties, methods ... */
}
</code>```

Is this the rigth place or are there any other one ?

Secondly, when the class is declared like in my previous example, the security plugin / jenkins sandbox will stop my pipeline if I'm using "echo" or "println" in my class method.

```<code>    pipeline {
        agent any

        stages {

            stage('blabla') {
                steps {
                    script {
                        def var = new MyClass()

                    }
                }
            }
        }
    }

    class MyClass {

        def MyClass()
        {
            echo "This echo will make my pipeline fail"
        }
    }
</code>```

give me

Scripts not permitted to use method groovy.lang.GroovyObject
  invokeMethod java.lang.String java.lang.Object (MyClass echo
  java.lang.String). Administrators can decide whether to approve or
  reject this signature.

I don't understand why I can't call su a basic function, I'm guessing it's a matter of scope (since the class declaration is outside the "pipeline" block) but I haven't find a way to make it work cleanly.
I'm not a fan of approuving this security exception througth Jenkins, nor I'm a fan about disabling Jenkins sandbox.
Why can't I use a simple "echo" ??? It's the same thing about "println" ...

Lastly, it seem I'm not able to call my own function declared at the same level ...

```<code>pipeline {
    agent any

    stages {

        stage('blabla') {
            steps {
                script {

                    MyFunc() // This work

                    def var = new MyClass()

                }
            }
        }
    }
}

def MyFunc()
{
    return sh(returnStdout: true, script: 'ls -lsa')
}

class MyClass {

    def MyClass()
    {
        MyFunc() // This doesn't work ...
    }
}
</code>```

Scripts not permitted to use method groovy.lang.GroovyObject
  invokeMethod java.lang.String java.lang.Object (MyClass MyFunc).
  Administrators can decide whether to approve or reject this signature.

The heck ? What I am missing so badly that I can't even use basic function or my own function in the pipeline ??

答:
The error message is highly misleading.

When you get a "Scripts not permitted to use" error that is specifically about groovy.lang.GroovyObject invokeMethod, it doesn't mean what it seems to mean. (Unless you're actually literally using invokeMethod because you want to do some weird dynamic method call stuff)

Almost always, when you see this error what it means is that you tried to invoke a method on a class that doesn't have that method. Here, the error should really tell you "MyClass doesn't have a method called MyFunc", but the security system got in the way and threw up a the error you got instead.

The general issue of "how do I invoke a top-level function from inside a groovy-defined class" is covered here: Call top level function from groovy method

Short version: yes, you should put the function in a shared library, but the security error is just a red herring.

(Note: if you get a "Scripts not permitted to use" error that is not about groovy.lang.GroovyObject invokeMethod, that is an honest permissions error and you'll likely need an admin of your Jenkins instance to approve your script or blanket approve the method it's talking about)

Title: How to define class in Jenkinsfie

Body:
I'm trying to set up a jenkins pipeline in order to do some continuous integration and automated deployement.
Since I'm using Gitea, I have installed gitea plugin and configured it to execute my jenkins file pipeline.
So far, so good.

I have managed to code something that "work" but the code is horrible and I have to heavely use global variable and other "bad" thing.

So I thougth that rewrite the pipeline but using class in order to keep thing clean was a good idea, but I ended up running into one problem after another !
The problem is that I'm not reallu use to code in Groovy and I'm currently discovering Jenkins.

First, I failed to know where to declare the class, so I just put it outside the pipeline.

pipeline {
    agent any

    stages {

        stage('blabla') {
            steps {
                script {
                    def var = new MyClass()

                }
            }
        }
    }
}

class MyClass {

    /* Some propeties, methods ... */
}

Is this the rigth place or are there any other one ?

Secondly, when the class is declared like in my previous example, the security plugin / jenkins sandbox will stop my pipeline if I'm using "echo" or "println" in my class method.

    pipeline {
        agent any

        stages {

            stage('blabla') {
                steps {
                    script {
                        def var = new MyClass()

                    }
                }
            }
        }
    }

    class MyClass {

        def MyClass()
        {
            echo "This echo will make my pipeline fail"
        }
    }

give me

Scripts not permitted to use method groovy.lang.GroovyObject
  invokeMethod java.lang.String java.lang.Object (MyClass echo
  java.lang.String). Administrators can decide whether to approve or
  reject this signature.

I don't understand why I can't call su a basic function, I'm guessing it's a matter of scope (since the class declaration is outside the "pipeline" block) but I haven't find a way to make it work cleanly.
I'm not a fan of approuving this security exception througth Jenkins, nor I'm a fan about disabling Jenkins sandbox.
Why can't I use a simple "echo" ??? It's the same thing about "println" ...

Lastly, it seem I'm not able to call my own function declared at the same level ...

pipeline {
    agent any

    stages {

        stage('blabla') {
            steps {
                script {

                    MyFunc() // This work

                    def var = new MyClass()

                }
            }
        }
    }
}

def MyFunc()
{
    return sh(returnStdout: true, script: 'ls -lsa')
}

class MyClass {

    def MyClass()
    {
        MyFunc() // This doesn't work ...
    }
}

Scripts not permitted to use method groovy.lang.GroovyObject
  invokeMethod java.lang.String java.lang.Object (MyClass MyFunc).
  Administrators can decide whether to approve or reject this signature.

The heck ? What I am missing so badly that I can't even use basic function or my own function in the pipeline ??


问:
How to merge two lists of maps in Clojure
I have data in below format.

```<code>'(({:nums {:test number?, :data (1)}})
  {:Other ()}
  ({:nums {:test number?, :data (2)}})
  ({:nums {:test number?, :data (3 4)}}))
</code>```

But I would like to get data in below format.

```<code>'(({:nums {:test number?, :data (1 2 3 4)}})
  {:Other ()})
</code>```

Tried with merge, union functions, but not worked.
Could you please help here as I am beginner to Closure.

Doing tests on below code

```<code>(split '(1 2 (3 4 [1 2 3])) {:nums {:test number?}})
=>
((({:nums {:test number?, :data (1)}}) {:Other ()})
  (({:nums {:test number?, :data (2)}}) {:Other ()})
  (({:nums {:test number?, :data (3 4)}}) {:Other (([1 2 3]))}))
</code>```

But The target result I am expecting as below

```<code>(split '(1 2 (3 4 [1 2 3])) {:nums {:test number?}})
=>
(({:nums {:test number?, :data (1 2 3 4)}})
 {:Other ([1 2 3])})
</code>```

Code used:

```<code>(defn test
  [list1 filter1]
  ;(get-in (first (first (split list1 filter1))) [:nums :test])
  (first (first (split list1 filter1))))

(defn split [list1 filter_map]
  (if (empty? list1)
    ()
    (cons (split_list
            (if (sequential? (first list1))
              (first list1)
              (list (first list1)))
            filter_map)
      (split (rest list1) filter_map))))

(defn split_list [list1 filter_map]
  (let [var_in_filter (remove nil? (in-filter filter_map))
        var_out_filter (remove nil? (out-filter filter_map))]
    ;var_out_filter
    (list (in_filter_recur list1 var_in_filter)
      ;(in_filter_recur list1  var_in_filter)
      (hash-map :Other (remove nil?
                         (out_filter_recur list1 var_out_filter))))))

(defn in_filter_recur [lis in_filt]
  (if (empty? in_filt)
    nil
    (cons (hash-map
            (if ((first in_filt) 1)
              :nums
              ;"{:nums {:test number?}"
              (if ((first in_filt) 'a)
                :syms
                (if ((first in_filt) [1])
                  :vects
                  'others)))

            ;(set (merge [:data] (filter (first in_filt) lis))))
            (hash-map :test
              (if ((first in_filt) 1)
                'number?
                ;"{:nums {:test number?}"
                (if ((first in_filt) 'a)
                  'symbols?
                  (if ((first in_filt) [1])
                    'vector?
                    'others)))
              :data (filter (first in_filt) lis)))
      (in_filter_recur lis (rest in_filt)))))

(defn out_filter_recur [lis out_filt]
  (if (empty? out_filt)
    nil
    (cons ;(hash-map nil
      (if (empty? (filter (first out_filt) lis))
        nil
        (filter (first out_filt) lis))
      (out_filter_recur lis (rest out_filt)))))

(defn out-filter [filt]
  (difference
    (set
      (All-filter
        {:nums {:test number?}
         :syms {:test symbol?}
         :vects {:test vector?}
         :other {:test string?}})) (set (in-filter filt))))

(defn in-filter [filt]
  (list (when
          (and (> (count (str (get-in filt [:nums :test]))) 0)
            ((get-in filt [:nums :test]) 1))
          number?)
    (when
      (and (> (count (str (get-in filt [:syms :test]))) 0)
        ((get-in filt [:syms :test]) 'a))
      symbol?)
    (when
      (and (> (count (str (get-in filt [:vects :test]))) 0)
        ((get-in filt [:vects :test]) [1]))
      vector?)))

(defn All-filter [filt]
  (list (when
          (and (> (count (str (get-in filt [:nums :test]))) 0)
            ((get-in filt [:nums :test]) 1))
          number?)
    (when
      (and (> (count (str (get-in filt [:syms :test]))) 0)
        ((get-in filt [:syms :test]) 'a))
      symbol?)
    (when
      (and (> (count (str (get-in filt [:vects :test]))) 0)
        ((get-in filt [:vects :test]) [1]))
      vector?)
    (when
      (and (> (count (str (get-in filt [:other :test]))) 0)
        ((get-in filt [:other :test]) "1"))
      string?)))

(defn difference
  ([s1] s1)
  ([s1 s2]
   (if (< (count s1) (count s2))
     (reduce (fn [result item]
               (if (contains? s2 item)
                 (disj result item)
                 result))
       s1 s1)
     (reduce disj s1 s2)))
  ([s1 s2 & sets]
   (reduce difference s1 (conj sets s2))))
</code>```

答:
Here's what I came up with, it's kind of a specific data structure, so it's pretty specific code

The first step is to set up the data so that we can work with merge-with

```<code>(defn get-data [val]
  (as-> val ?
        (first ?)
        (:nums ?)
        (select-keys ? [:data])))
</code>```

Then the last step is to call merge-with and put it back together

```<code>(def x '(({:nums {:test number?, :data (1)}})
         {:Other ()}
         ({:nums {:test number?, :data (2)}})
         ({:nums {:test number?, :data (3 4)}}))

(as-> x ?
      (map get-data ?)
      (apply merge-with concat ?)
      (assoc ? :test 'number?)
      (list ?)
      (list ?)
      (conj ? {:Other '()})
      (reverse ?))
</code>```

If you were looking for something more generic, you'll have to come at me with a more generic data structure.

I think what you were looking for is mostly contained in the (apply merge-with concat ?) line which does most of the work.

This function takes a list of maps and applies the function, in this case concat to the values in those maps.

See (doc merge-with) in your REPL for more information.

As a last ditch effort, you may also be interested in the specter clojure library which excels at this sort of deeply nested data transformation.

Hope this helps!

Body:
I have data in below format.

'(({:nums {:test number?, :data (1)}})
  {:Other ()}
  ({:nums {:test number?, :data (2)}})
  ({:nums {:test number?, :data (3 4)}}))

But I would like to get data in below format.

'(({:nums {:test number?, :data (1 2 3 4)}})
  {:Other ()})

Tried with merge, union functions, but not worked.
Could you please help here as I am beginner to Closure.

Doing tests on below code

(split '(1 2 (3 4 [1 2 3])) {:nums {:test number?}})
=>
((({:nums {:test number?, :data (1)}}) {:Other ()})
  (({:nums {:test number?, :data (2)}}) {:Other ()})
  (({:nums {:test number?, :data (3 4)}}) {:Other (([1 2 3]))}))

But The target result I am expecting as below

(split '(1 2 (3 4 [1 2 3])) {:nums {:test number?}})
=>
(({:nums {:test number?, :data (1 2 3 4)}})
 {:Other ([1 2 3])})

Code used:

(defn test
  [list1 filter1]
  ;(get-in (first (first (split list1 filter1))) [:nums :test])
  (first (first (split list1 filter1))))

(defn split [list1 filter_map]
  (if (empty? list1)
    ()
    (cons (split_list
            (if (sequential? (first list1))
              (first list1)
              (list (first list1)))
            filter_map)
      (split (rest list1) filter_map))))

(defn split_list [list1 filter_map]
  (let [var_in_filter (remove nil? (in-filter filter_map))
        var_out_filter (remove nil? (out-filter filter_map))]
    ;var_out_filter
    (list (in_filter_recur list1 var_in_filter)
      ;(in_filter_recur list1  var_in_filter)
      (hash-map :Other (remove nil?
                         (out_filter_recur list1 var_out_filter))))))

(defn in_filter_recur [lis in_filt]
  (if (empty? in_filt)
    nil
    (cons (hash-map
            (if ((first in_filt) 1)
              :nums
              ;"{:nums {:test number?}"
              (if ((first in_filt) 'a)
                :syms
                (if ((first in_filt) [1])
                  :vects
                  'others)))

            ;(set (merge [:data] (filter (first in_filt) lis))))
            (hash-map :test
              (if ((first in_filt) 1)
                'number?
                ;"{:nums {:test number?}"
                (if ((first in_filt) 'a)
                  'symbols?
                  (if ((first in_filt) [1])
                    'vector?
                    'others)))
              :data (filter (first in_filt) lis)))
      (in_filter_recur lis (rest in_filt)))))

(defn out_filter_recur [lis out_filt]
  (if (empty? out_filt)
    nil
    (cons ;(hash-map nil
      (if (empty? (filter (first out_filt) lis))
        nil
        (filter (first out_filt) lis))
      (out_filter_recur lis (rest out_filt)))))

(defn out-filter [filt]
  (difference
    (set
      (All-filter
        {:nums {:test number?}
         :syms {:test symbol?}
         :vects {:test vector?}
         :other {:test string?}})) (set (in-filter filt))))

(defn in-filter [filt]
  (list (when
          (and (> (count (str (get-in filt [:nums :test]))) 0)
            ((get-in filt [:nums :test]) 1))
          number?)
    (when
      (and (> (count (str (get-in filt [:syms :test]))) 0)
        ((get-in filt [:syms :test]) 'a))
      symbol?)
    (when
      (and (> (count (str (get-in filt [:vects :test]))) 0)
        ((get-in filt [:vects :test]) [1]))
      vector?)))

(defn All-filter [filt]
  (list (when
          (and (> (count (str (get-in filt [:nums :test]))) 0)
            ((get-in filt [:nums :test]) 1))
          number?)
    (when
      (and (> (count (str (get-in filt [:syms :test]))) 0)
        ((get-in filt [:syms :test]) 'a))
      symbol?)
    (when
      (and (> (count (str (get-in filt [:vects :test]))) 0)
        ((get-in filt [:vects :test]) [1]))
      vector?)
    (when
      (and (> (count (str (get-in filt [:other :test]))) 0)
        ((get-in filt [:other :test]) "1"))
      string?)))

(defn difference
  ([s1] s1)
  ([s1 s2]
   (if (< (count s1) (count s2))
     (reduce (fn [result item]
               (if (contains? s2 item)
                 (disj result item)
                 result))
       s1 s1)
     (reduce disj s1 s2)))
  ([s1 s2 & sets]
   (reduce difference s1 (conj sets s2))))

Body:
Here's what I came up with, it's kind of a specific data structure, so it's pretty specific code

The first step is to set up the data so that we can work with merge-with

(defn get-data [val]
  (as-> val ?
        (first ?)
        (:nums ?)
        (select-keys ? [:data])))

Then the last step is to call merge-with and put it back together

(def x '(({:nums {:test number?, :data (1)}})
         {:Other ()}
         ({:nums {:test number?, :data (2)}})
         ({:nums {:test number?, :data (3 4)}}))

(as-> x ?
      (map get-data ?)
      (apply merge-with concat ?)
      (assoc ? :test 'number?)
      (list ?)
      (list ?)
      (conj ? {:Other '()})
      (reverse ?))

If you were looking for something more generic, you'll have to come at me with a more generic data structure.

I think what you were looking for is mostly contained in the (apply merge-with concat ?) line which does most of the work.

This function takes a list of maps and applies the function, in this case concat to the values in those maps.

See (doc merge-with) in your REPL for more information.

As a last ditch effort, you may also be interested in the specter clojure library which excels at this sort of deeply nested data transformation.

Hope this helps!