问:
Call method from main method?
Im trying to make 2 methods. The main method has the user input, and the other method called ShowNum should output the...output. Heres my original code with one main method:

```<code>public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int days;
int num;

System.out.print("Enter number of days: ");
days = keyboard.nextInt();

System.out.print("Enter number for first day: ");
num = keyboard.nextInt();

int half = days/2;
int newnum = num + 2;

      System.out.println("Day \t Number");

          for (int current_day = 1; current_day <= half; current_day++){
              newnum = newnum - 2;
              System.out.println(current_day + "\t" + (newnum + 2));
          }
          for (int current_day = half + 1; current_day <= days; current_day++){
              newnum++;
              System.out.println(current_day + "\t" + (newnum + 2));
          }
</code>```

Ive tried this:

```<code>public static void DisplayNum(){
   int half = days / 2;
   int newnum = num + 2;

   System.out.println("Day \t Num");

       for (int current_day = 1; current_day <= (days/2); current_day++){
            newnum = newnum - 2;
            System.out.println(current_day + "\t" + (num + 2));
              }
       for (int current_day = (days/2) + 1; current_day <= days; current_day++){
                  newnum++;
                  System.out.println(current_day + "\t" + (num + 2));
              }
}

public static void main(String[] args){

    Scanner keyboard = new Scanner(System.in);
        int days;
        int num;

          System.out.print("Enter number of days in the period of time: ");
            days = keyboard.nextInt();

          System.out.print("Enter number for first day: ");
            num = keyboard.nextInt();

           DisplayNum();
</code>```

Its a mess of errors because the variables aren't all defined in both methods but I don't know how to make them defined without just making it in one method. This is basically what my professor said to do yet I'm very confused. I'd appreciate help or any other advice. Thanks in advance.

答:
Add arguments into your function DisplayNum() like this DisplayNum(int days, int num) and then call this method into your main method
DisplayNum(days,num).

Title: Call method from main method?

Body:
Im trying to make 2 methods. The main method has the user input, and the other method called ShowNum should output the...output. Heres my original code with one main method:

public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int days;
int num;

System.out.print("Enter number of days: ");
days = keyboard.nextInt();

System.out.print("Enter number for first day: ");
num = keyboard.nextInt();

int half = days/2;
int newnum = num + 2;

      System.out.println("Day \t Number");

          for (int current_day = 1; current_day <= half; current_day++){
              newnum = newnum - 2;
              System.out.println(current_day + "\t" + (newnum + 2));
          }
          for (int current_day = half + 1; current_day <= days; current_day++){
              newnum++;
              System.out.println(current_day + "\t" + (newnum + 2));
          }

Ive tried this:

public static void DisplayNum(){
   int half = days / 2;
   int newnum = num + 2;

   System.out.println("Day \t Num");

       for (int current_day = 1; current_day <= (days/2); current_day++){
            newnum = newnum - 2;
            System.out.println(current_day + "\t" + (num + 2));
              }
       for (int current_day = (days/2) + 1; current_day <= days; current_day++){
                  newnum++;
                  System.out.println(current_day + "\t" + (num + 2));
              }
}

public static void main(String[] args){

    Scanner keyboard = new Scanner(System.in);
        int days;
        int num;

          System.out.print("Enter number of days in the period of time: ");
            days = keyboard.nextInt();

          System.out.print("Enter number for first day: ");
            num = keyboard.nextInt();

           DisplayNum();

Its a mess of errors because the variables aren't all defined in both methods but I don't know how to make them defined without just making it in one method. This is basically what my professor said to do yet I'm very confused. I'd appreciate help or any other advice. Thanks in advance.


来源: stackexchange

问:
FREETEXT problem on stored procedure
my problem is when i enter the text like "XXX" and click search button it shows the record for only "XXX". but i want to show all the records of the Uppercase and also the lower case of "XXX". then i try freetext but it shows "Incorrect syntax near the keyword 'Freetext'".

can anyone tell me the reason......

i'm using the below code for multiple search....

```<code>set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_searchdetails]
    @customervendortype varchar(30)=Null,
    @customervendorid   varchar(30)=Null,
    @customervendorname varchar(30)=Null,
    @state              varchar(30)=Null,
    @city               varchar(30)=Null
AS
BEGIN

if @customervendortype is not null and len(@customervendortype)=0 set @customervendortype = null
if @customervendorid is not null and len(@customervendorid)=0 set @customervendorid = null
if @customervendorname is not null and len(@customervendorname)=0 set @customervendorname = null
if @city is not null and len(@city)=0 set @city = null
if @state is not null and len(@state)=0 set @state = null

SELECT CustomerVendorDetails.customervendorid,CustomerVendorAddressDetails.customervendorname, CustomerVendorAddressDetails.doorno, CustomerVendorAddressDetails.street,
CustomerVendorAddressDetails.city, CustomerVendorAddressDetails.state, CustomerVendorAddressDetails.country,
CustomerVendorAddressDetails.pincode,  CustomerVendorDetails.decidingauthority,
CustomerVendorDetails.landlineno1, CustomerVendorDetails.landlineno2, CustomerVendorDetails.faxno, ContactPersonDetails.contactno,
ContactPersonDetails.designation

FROM
CustomerVendorDetails INNER JOIN
CustomerVendorAddressDetails ON CustomerVendorDetails.customervendorid = CustomerVendorAddressDetails.customervendorid INNER JOIN
ContactPersonDetails ON CustomerVendorAddressDetails.customervendorid = ContactPersonDetails.customervendorid

WHERE
(@customervendortype is null or CustomerVendorDetails.customervendortype like @customervendortype) and  (@customervendorid is null or CustomerVendorDetails.customervendorid like @customervendorid) and Freetext (@customervendorname is null or CustomerVendorDetails.customervendorname like @customervendorname ) and Freetext (@city is null or CustomerVendorAddressDetails.city like @city)and Freetext (@state is null or CustomerVendorAddressDetails.state like @state)

END
</code>```

答: in freetext function you needn't do some action just describe column(s) and parameters. see MSDN (second example describe variable usage)</p>

ContentLicense: CC BY-SA 2.5

Title: FREETEXT problem on stored procedure

Body:
my problem is when i enter the text like "XXX" and click search button it shows the record for only "XXX". but i want to show all the records of the Uppercase and also the lower case of "XXX". then i try freetext but it shows "Incorrect syntax near the keyword 'Freetext'".

can anyone tell me the reason......

i'm using the below code for multiple search....

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_searchdetails]
    @customervendortype varchar(30)=Null,
    @customervendorid   varchar(30)=Null,
    @customervendorname varchar(30)=Null,
    @state              varchar(30)=Null,
    @city               varchar(30)=Null
AS
BEGIN

if @customervendortype is not null and len(@customervendortype)=0 set @customervendortype = null
if @customervendorid is not null and len(@customervendorid)=0 set @customervendorid = null
if @customervendorname is not null and len(@customervendorname)=0 set @customervendorname = null
if @city is not null and len(@city)=0 set @city = null
if @state is not null and len(@state)=0 set @state = null

SELECT CustomerVendorDetails.customervendorid,CustomerVendorAddressDetails.customervendorname, CustomerVendorAddressDetails.doorno, CustomerVendorAddressDetails.street,
CustomerVendorAddressDetails.city, CustomerVendorAddressDetails.state, CustomerVendorAddressDetails.country,
CustomerVendorAddressDetails.pincode,  CustomerVendorDetails.decidingauthority,
CustomerVendorDetails.landlineno1, CustomerVendorDetails.landlineno2, CustomerVendorDetails.faxno, ContactPersonDetails.contactno,
ContactPersonDetails.designation

FROM
CustomerVendorDetails INNER JOIN
CustomerVendorAddressDetails ON CustomerVendorDetails.customervendorid = CustomerVendorAddressDetails.customervendorid INNER JOIN
ContactPersonDetails ON CustomerVendorAddressDetails.customervendorid = ContactPersonDetails.customervendorid

WHERE
(@customervendortype is null or CustomerVendorDetails.customervendortype like @customervendortype) and  (@customervendorid is null or CustomerVendorDetails.customervendorid like @customervendorid) and Freetext (@customervendorname is null or CustomerVendorDetails.customervendorname like @customervendorname ) and Freetext (@city is null or CustomerVendorAddressDetails.city like @city)and Freetext (@state is null or CustomerVendorAddressDetails.state like @state)

END


问:
Hide Registration form, show another form after success
Trying to hide the registration form, after submit and all checks comes success, then hide this form, then show another one for choose product form.
Been trying to see if the settimeout would do the trick, but only shows a white blank page after success.

Anyone got any idea? Thanks =)

```<code>setTimeout('$(".signin-form").fadeOut(500, function(){ $(".ChooseProductForm").fadein(500); }); ',2000);
</code>```

Sorry, i misunderstood the hole jQuery, so read my way up to understand a bit more and fixed this question while many other problems as well :-)

答:
Your code is not correct. See below, corrected code.

```<code>setTimeout(function() {
    $(".signin-form").fadeOut(500, function() {
        $(".ChooseProductForm").fadein(500);
    });
}, 2000);
</code>```

Note: I assume you call this code inside done() or success Ajax method.

ContentLicense: CC BY-SA 3.0

Body:
Trying to hide the registration form, after submit and all checks comes success, then hide this form, then show another one for choose product form.
Been trying to see if the settimeout would do the trick, but only shows a white blank page after success.

Anyone got any idea? Thanks =)

setTimeout('$(".signin-form").fadeOut(500, function(){ $(".ChooseProductForm").fadein(500); }); ',2000);

Sorry, i misunderstood the hole jQuery, so read my way up to understand a bit more and fixed this question while many other problems as well :-)

Body:
Your code is not correct. See below, corrected code.

setTimeout(function() {
    $(".signin-form").fadeOut(500, function() {
        $(".ChooseProductForm").fadein(500);
    });
}, 2000);

Note: I assume you call this code inside done() or success Ajax method.


问:
Decoding not working with Base64
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

```<code>document.write(atob("hi"));
</code>```

This does not:

```<code>var tempvar = "hello";
document.write(atob(tempvar));
</code>```

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.

答:
It's because it can't decode the string "hello", try an actual string that can be decoded from base64, here is an example;

```<code>var tempvar = "aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MzEyOTEzNi9kZWNvZGluZy1ub3Qtd29ya2luZy13aXRoLWJhc2U2NA==";
document.write(atob(tempvar));
</code>```

If you want to encode, use the btoa function instead,

```<code>var tempvar = "hello";
document.write(btoa(tempvar));
</code>```

You can use this website to test decoding and encoding base64, https://www.base64encode.org/

Title: Decoding not working with Base64

Body:
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

document.write(atob("hi"));

This does not:

var tempvar = "hello";
document.write(atob(tempvar));

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.

Body:
It's because it can't decode the string "hello", try an actual string that can be decoded from base64, here is an example;

var tempvar = "aHR0cDovL3N0YWNrb3ZlcmZsb3cuY29tL3F1ZXN0aW9ucy80MzEyOTEzNi9kZWNvZGluZy1ub3Qtd29ya2luZy13aXRoLWJhc2U2NA==";
document.write(atob(tempvar));

If you want to encode, use the btoa function instead,

var tempvar = "hello";
document.write(btoa(tempvar));

You can use this website to test decoding and encoding base64, https://www.base64encode.org/


问:
Digital Metaphors Report Builder 16.0 How can I assign shape visibility dynmically
I wish to make an area of a worksheet grey if it does not apply. I'm thinking of using a shape with visibility depending on some boolean value in the data pipeline. Can anyone describe how to access the visibility attribute of a shape, or suggest another method of dynamic shading?</p>

答:
If the area is (for example) in the DetailBand, you can set this up in the BeforePrint event.

I'm assuming you've set transparency and colour of Shape1 in designer.

```<code>procedure TSomeFormOrDM.ppDetailBand1BeforePrint(Sender: TObject);
var
  doGrey: boolean;
begin
  doGrey := ppDBPipeline1['SomeBooleanTrigger'];
  ppShape1.visible:=doGrey;
end;
</code>```

Instead of a shape, you could always drop a range in the band. If you did that, you'd need to change colour, not visible (because making the range not visible would of course also hide every element embedded/parented by the range).

EdB

Body:
If the area is (for example) in the DetailBand, you can set this up in the BeforePrint event.

I'm assuming you've set transparency and colour of Shape1 in designer.

procedure TSomeFormOrDM.ppDetailBand1BeforePrint(Sender: TObject);
var
  doGrey: boolean;
begin
  doGrey := ppDBPipeline1['SomeBooleanTrigger'];
  ppShape1.visible:=doGrey;
end;

Instead of a shape, you could always drop a range in the band. If you did that, you'd need to change colour, not visible (because making the range not visible would of course also hide every element embedded/parented by the range).

EdB


问:
Sampling video every N frames starting at n0 initial frame

Question

I am trying to figure out how to sample a video stream x[n] every N frames, starting at frame n_i, i < N, so that I end up with N new videos of length len(x) / N.

In formula this is simply: y_i[n] = x[n_i + n * N].

Here there is a diagram of what I am trying to achieve:

The greedy solution would be simply dumping the frames to a folder and then create new videos out of appropriately indexed frames.
I was hoping there were some more elegant solution with ffmpeg since I have to process hundreds of video.

Implementation

Finally, I managed to write the final implementation, which I am reporting here for completeness.

It does scale the minimum dimension to 256, does not process more than max_frames; performs the sampling every k frames, send the first k - 1 samples to one folder and the k-th one to another one. It also set the output frame rate to the input average frame rate, since otherwise some videos will go at 120 Hz...

```<code>k=5
kk=$(awk "BEGIN{print 1/$k}")
ffmpeg \
    -i $src_video_path \
    -an \
    -loglevel error \
    -filter_complex \
        "setpts=$kk*PTS, \
        scale=w=2*trunc(128*max(1\, iw/ih)):h=2*trunc(128*max(1\, ih/iw))[m]; \
        [m]select=n=$k:e=(mod(n\,$k)+1)*lt(n\,$max_frames) \
        $(for ((i=1; i<=$k; i++)); do
            echo -n "[a$i]"
        done)" \
    $(for ((i=1; i<$k; i++)); do
        echo -n "-r $fps -map [a$i] $dst_video_path/$i.mp4 "
    done
    echo -n "-r $fps -map [a$k] $val_video_path/$k.mp4"
    )
</code>```

答:
One-by-one solution

You can use ffmpeg's select filter, which allows you to evaluate an expression using the sequential frame number, and decide whether or not to skip it (and which output to send it to if it isn't skipped).

To generate, for example, the second video where you are splitting into four each time, you would do the following:

```<code>ffmpeg -i input_video -vf select='not(mod(n-1\,4)), setpts=0.25*PTS' -an output_video
</code>```

Change the 4 if you are splitting into a different number, and the 1 if you want a different selection (so for four you would run it four times, starting without subtracting anything, and ending with subtracting three.

The -vf ... -an segment is to get the video to play back at the right speed, and have the right length (which requires removing any audio tracks).

All-at-once solution

The select filter can also split the file and save each output separately. Here is a command that will split the file into k outputs, (change .mp4 if you want a different extension).

```<code>k=4;ffmpeg -i INPUT_FILE -an -filter_complex "setpts=`bc -l <<< 1/$k`*PTS[m];[m]select=n=$k:e=mod(n\,$k)+1`for ((i=1; i<=$k; i++)); do echo -n "[a$i]"; done`" `for ((i=1; i<=$k; i++)); do echo -n "-map [a$i] out$i.mp4 "; done`
</code>```

The loops within the command are just to write out [a1][a2]... and -map
[a1] out1.mp4.... Other than that the modification is to use filter_complex, which is required when dealing with multiple outputs, and changing the filter to direct each frame to its own output mod k.

Body:
Question

I am trying to figure out how to sample a video stream x[n] every N frames, starting at frame n_i, i < N, so that I end up with N new videos of length len(x) / N.

In formula this is simply: y_i[n] = x[n_i + n * N].

Here there is a diagram of what I am trying to achieve:

The greedy solution would be simply dumping the frames to a folder and then create new videos out of appropriately indexed frames.
I was hoping there were some more elegant solution with ffmpeg since I have to process hundreds of video.

Implementation

Finally, I managed to write the final implementation, which I am reporting here for completeness.

It does scale the minimum dimension to 256, does not process more than max_frames; performs the sampling every k frames, send the first k - 1 samples to one folder and the k-th one to another one. It also set the output frame rate to the input average frame rate, since otherwise some videos will go at 120 Hz...

k=5
kk=$(awk "BEGIN{print 1/$k}")
ffmpeg \
    -i $src_video_path \
    -an \
    -loglevel error \
    -filter_complex \
        "setpts=$kk*PTS, \
        scale=w=2*trunc(128*max(1\, iw/ih)):h=2*trunc(128*max(1\, ih/iw))[m]; \
        [m]select=n=$k:e=(mod(n\,$k)+1)*lt(n\,$max_frames) \
        $(for ((i=1; i<=$k; i++)); do
            echo -n "[a$i]"
        done)" \
    $(for ((i=1; i<$k; i++)); do
        echo -n "-r $fps -map [a$i] $dst_video_path/$i.mp4 "
    done
    echo -n "-r $fps -map [a$k] $val_video_path/$k.mp4"
    )

Body:
One-by-one solution

You can use ffmpeg's select filter, which allows you to evaluate an expression using the sequential frame number, and decide whether or not to skip it (and which output to send it to if it isn't skipped).

To generate, for example, the second video where you are splitting into four each time, you would do the following:

ffmpeg -i input_video -vf select='not(mod(n-1\,4)), setpts=0.25*PTS' -an output_video

Change the 4 if you are splitting into a different number, and the 1 if you want a different selection (so for four you would run it four times, starting without subtracting anything, and ending with subtracting three.

The -vf ... -an segment is to get the video to play back at the right speed, and have the right length (which requires removing any audio tracks).

All-at-once solution

The select filter can also split the file and save each output separately. Here is a command that will split the file into k outputs, (change .mp4 if you want a different extension).

k=4;ffmpeg -i INPUT_FILE -an -filter_complex "setpts=`bc -l <<< 1/$k`*PTS[m];[m]select=n=$k:e=mod(n\,$k)+1`for ((i=1; i<=$k; i++)); do echo -n "[a$i]"; done`" `for ((i=1; i<=$k; i++)); do echo -n "-map [a$i] out$i.mp4 "; done`

The loops within the command are just to write out [a1][a2]... and -map
[a1] out1.mp4.... Other than that the modification is to use filter_complex, which is required when dealing with multiple outputs, and changing the filter to direct each frame to its own output mod k.


问:
Update web api record with knockout.js
I have this method in controller:

```<code>// PUT: api/Books/5
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutBook(int id, Book book)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != book.Id)
            {
                return BadRequest();
            }

            db.Entry(book).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
</code>```

I have this method in Knockout.js

```<code>self.PutBook = function (item, book) {
        ajaxHelper(booksUri + item.Id, 'PUT').done(function (item) {
            self.books.put(item, book);

        });
    }
</code>```

I want to update record with values that are entered in frontend input fields. What is missing in knockout.js? I'm not able to solve it.

答:
From the javscript above, you should have used different variable name inside done because your action controller doesn't return item and you want to get the item object.

```<code>self.PutBook = function (item, book) {
    ajaxHelper(booksUri + item.Id, 'PUT').done(function (result) {
        self.books.put(item, book);
    });
}
</code>```

Title: Update web api record with knockout.js

Body:
I have this method in controller:

// PUT: api/Books/5
        [ResponseType(typeof(void))]
        public async Task<IHttpActionResult> PutBook(int id, Book book)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != book.Id)
            {
                return BadRequest();
            }

            db.Entry(book).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

I have this method in Knockout.js

self.PutBook = function (item, book) {
        ajaxHelper(booksUri + item.Id, 'PUT').done(function (item) {
            self.books.put(item, book);

        });
    }

I want to update record with values that are entered in frontend input fields. What is missing in knockout.js? I'm not able to solve it.

Body:
From the javscript above, you should have used different variable name inside done because your action controller doesn't return item and you want to get the item object.

self.PutBook = function (item, book) {
    ajaxHelper(booksUri + item.Id, 'PUT').done(function (result) {
        self.books.put(item, book);
    });
}


问:
Decorator pattern in Objective-C
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

```<code>// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end
</code>```

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.

答:
Yes, it is possible to implement the Decorator pattern in Objective-C with an NSProxy. You would have to implement methodSignatureForSelector: and forwardInvocation: to forward messages to the decorated object.

But I don't think that this would be a good solution for what you try to do here; sending invocations is very costly and is not intended for such a purpose - there are certainly better ways to achieve what you want to do, e.g. with Categories (or maybe method swizzling).

Title: Decorator pattern in Objective-C

Body:
I was thinking of using the decorator pattern to extend the functionality of a UIKit class. The problem that I'm facing is that from examples I've seen in other languages the pattern forces me to duplicate the decorated object's interface. Here's how I would see the pattern implemented:

// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end

So to summarize, the problem is the duplication of the decorated object's method, even when I don't need to alter anything there. Is there a simpler way to pass along those methods that I don't need to "overwrite"? Could I use something like a NSProxy for this?

EDIT: This has become mostly a theoretical problem for me since I realized the decorator pattern is not what I needed to solve my actual problem. However, since I may come to use it again in the future, I'm still very interested in your answers.


问:
How to avoid memory leaks when MATLAB function inside parfor generates warning?
I use matlab R2015b for Win Server 2012 OS with local parpool. I have memory leaks on local workers when function inside parfor-loop generate warning. Also memory is not released after parfor-loop ends. Example:

```<code>x = rand(78, 1);
for j = 1:100
    parfor i = 1:1000
        [~, z] = kpsstest(x);
    end
end
</code>```

function kpsstest generates warning:

Warning: Test statistic #1 below tabulated critical values:
maximum p-value = 0.100 reported.
 In kpsstest>getStat (line 632)
 In kpsstest (line 291)

Memory leaks on workers even when i use constructions:

```<code>   warning('off', 'econ:kpsstest:StatTooSmall');
   pctRunOnAll warning('off', 'econ:kpsstest:StatTooSmall')
</code>```

Memory on start workers:

Memory on after executing code:

How to avoid memory leaks when function inside parfor generates warning?

Thank you.

答: Well, probably this is not the cleanest way, but you can shutdown the parallel pool, see here</p>

Body:
I use matlab R2015b for Win Server 2012 OS with local parpool. I have memory leaks on local workers when function inside parfor-loop generate warning. Also memory is not released after parfor-loop ends. Example:

x = rand(78, 1);
for j = 1:100
    parfor i = 1:1000
        [~, z] = kpsstest(x);
    end
end

function kpsstest generates warning:

Warning: Test statistic #1 below tabulated critical values:
maximum p-value = 0.100 reported.
 In kpsstest>getStat (line 632)
 In kpsstest (line 291)

Memory leaks on workers even when i use constructions:

   warning('off', 'econ:kpsstest:StatTooSmall');
   pctRunOnAll warning('off', 'econ:kpsstest:StatTooSmall')

Memory on start workers:

Memory on after executing code:

How to avoid memory leaks when function inside parfor generates warning?

Thank you.


问:
how to run two instances of couchDB in the same linux physical machine
I would like to have two couchdb server running on my machine.

I have already one instance running installed via this command line

```<code>sudo apt-get install couchdb -y
</code>```

I can run it and stop it via

```<code>/etc/init.d/couchdb [start|stop|restart]
</code>```

how can I have another instance of couchdb running on a different port

OS : linux 16.04

答:
You can use a different configuration file to start a second instance with. This is definitively an advanced topic, as you must take extra care that different instances of couchdb don't share any data, log or configuration files. You find some information about configuration in the CouchDB docs. You could start with duplicating the startup script (/etc/init.d/couchdb) and adapting the folders there, then copying the local.ini from the config folder and changing the data folders, http port and other configuration there.

I used this (quite old) build script to install completely separate copies and found it easier to work with.

But nowadays I would just use Docker and install several CouchDB containers, preferably with the  klaemo/couchdb image which is easy to handle.

Body:
I would like to have two couchdb server running on my machine.

I have already one instance running installed via this command line

sudo apt-get install couchdb -y

I can run it and stop it via

/etc/init.d/couchdb [start|stop|restart]

how can I have another instance of couchdb running on a different port

OS : linux 16.04


问:
GC overhead limit exceeded while reading huge txt files
I have a 20GB folder which consist of 358 txt files and there are 733,019,372 lines total and all txt files format is below

```<code>77 clueweb12-0211wb-83-00000
88 clueweb12-0211wb-83-00001
82 clueweb12-0211wb-83-00002
82 clueweb12-0211wb-83-00003
64 clueweb12-0211wb-83-00004
80 clueweb12-0211wb-83-00005
83 clueweb12-0211wb-83-00006
75 clueweb12-0211wb-83-00007
</code>```

My purpose is while program is traversing all the txt file recursively reading files line by line,seperate into two parts each line(e.g 88 and clueweb12-0211wb-83-0003) and put these parts into a LinkedHashMap<String, List<String>>. Afther that, take docIds(clueweb12-0211wb-83-00006) from user as an argument and put the score belongs to this docIds(83).If a non-existing docID is encountered, -1 should be returned as a score.For example:

```<code>clueweb12-0003wb-22-11553,foo,clueweb12-0109wb-78-15059,bar,clueweb12-0302wb-50-22339
</code>```

should print out : 84,-1,19,-1,79

And i take the path to file from user as an argument.

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

import static java.nio.file.FileVisitResult.CONTINUE;

public class App extends SimpleFileVisitor<Path>{

    public LinkedHashMap<String, List<String>> list = new LinkedHashMap<>(); // Put there scores and docIds

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {

     File file =  new File(path.toString());
     BufferedReader br = new BufferedReader(new FileReader(file));
     String line;

    while((line = br.readLine()) != null){

        if(list.containsKey(line.split(" ")[0])){
            list.get(line.split(" ")[0]).add(line.split(" ")[1]);
        }
        else{
            list.put(line.split(" ")[0],new ArrayList(Arrays.asList(line.split(" ")[1])));
        }

    }
        return CONTINUE;
    }

    public static void main(String args[]) throws IOException {

        if (args.length < 2) {
            System.err.println("Usage: java App spamDir docIDs ...");
            return;
        }
        Path spamDir = Paths.get(args[0]);
        String[] docIDs = args[1].split(",");

        App ap = new App();
        Files.walkFileTree(spamDir, ap);
        ArrayList scores = new ArrayList(); // keep scores in that list

        //Search the Lists in LinkedHashMap
        for(int j=0; j<docIDs.length; j++){
            Set set = ap.list.entrySet();
            Iterator i = set.iterator();
            int counter = 0;
            while(i.hasNext()){

                // if LinkedHashMap has the docID add it to scores List
                Map.Entry me = (Map.Entry) i.next();
                ArrayList searchList = (ArrayList) me.getValue();
                if(searchList.contains(docIDs[j])){
                    scores.add(me.getKey());
                    counter++;
                    break;

                }
                else {

                    continue;
                }

            }
            // if LinkedHashMap has not the docId add -1 to scores List
            if(counter == 0){
                scores.add("-1");
            }

        }

        String joined = String.join("," , scores);
        System.out.println(joined);

    }
}
</code>```

But I encountered that problem :

```<code>Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at ceng.bim208.App.visitFile(App.java:35)
    at ceng.bim208.App.visitFile(App.java:18)
    at java.nio.file.Files.walkFileTree(Files.java:2670)
    at java.nio.file.Files.walkFileTree(Files.java:2742)
    at ceng.bim208.App.main(App.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

I tried to use XmX2048M to increase heap size but it doesn't solve my problem. What should i do?

In addition, if i run the program on a different path(include 2 txt file same format) it works correctly.

答:
This sounds like an interview homework assignment. I bet that the task here is to take the mental leap and separate the data which you must hold in memory from those which you can store in an index while you parse the files.

No matter how much memory you have you'll run out of it eventually if you keep doing it like this. In your case there are some useful tips which you can use to fix this:

Don't put everything into the memory. Build an index if you can to a separate file which only holds the necessary data

Process the files as streams: this means that you parse the InputStream line by line, file by file and this way you don't have to keep them in memory.

In your case this:

```<code>public LinkedHashMap<String, List<String>> list
</code>```

fills up the memory with the parsed Strings. From what I understand you don't need to store the Strings themselves but only the score. If you clarify what your task is I can help you further but currently it is not clear what your task is.

my task is take the docIds as a command-line argument and print out their scores.

What you need is a lookup for the scores:

```<code>Map<String, Map<Integer, Integer>> docIdsWithScoresAndCounts;
</code>```

or

```<code>Map<String, List<Integer>> docIdsWithScores;
</code>```

depending on whether you want to count how many times a score appeared. The outer Map holds the doc ids as keys and the inner maps are lookups themselves for score -> count. This is a tricky variation of the counting sort algorithm: you only need to keep track of the doc ids and the scores of each doc id and since the scores are limited in size (how many digits can they have?) you end up with O(1) memory consumption. The rest of the data can be thrown away.

Note that you only need to store the keys of the doc ids you are interested in. You can throw away the rest.

Body:
I have a 20GB folder which consist of 358 txt files and there are 733,019,372 lines total and all txt files format is below

77 clueweb12-0211wb-83-00000
88 clueweb12-0211wb-83-00001
82 clueweb12-0211wb-83-00002
82 clueweb12-0211wb-83-00003
64 clueweb12-0211wb-83-00004
80 clueweb12-0211wb-83-00005
83 clueweb12-0211wb-83-00006
75 clueweb12-0211wb-83-00007

My purpose is while program is traversing all the txt file recursively reading files line by line,seperate into two parts each line(e.g 88 and clueweb12-0211wb-83-0003) and put these parts into a LinkedHashMap<String, List<String>>. Afther that, take docIds(clueweb12-0211wb-83-00006) from user as an argument and put the score belongs to this docIds(83).If a non-existing docID is encountered, -1 should be returned as a score.For example:

clueweb12-0003wb-22-11553,foo,clueweb12-0109wb-78-15059,bar,clueweb12-0302wb-50-22339

should print out : 84,-1,19,-1,79

And i take the path to file from user as an argument.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

import static java.nio.file.FileVisitResult.CONTINUE;

public class App extends SimpleFileVisitor<Path>{

    public LinkedHashMap<String, List<String>> list = new LinkedHashMap<>(); // Put there scores and docIds

    @Override
    public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {

     File file =  new File(path.toString());
     BufferedReader br = new BufferedReader(new FileReader(file));
     String line;

    while((line = br.readLine()) != null){

        if(list.containsKey(line.split(" ")[0])){
            list.get(line.split(" ")[0]).add(line.split(" ")[1]);
        }
        else{
            list.put(line.split(" ")[0],new ArrayList(Arrays.asList(line.split(" ")[1])));
        }

    }
        return CONTINUE;
    }

    public static void main(String args[]) throws IOException {

        if (args.length < 2) {
            System.err.println("Usage: java App spamDir docIDs ...");
            return;
        }
        Path spamDir = Paths.get(args[0]);
        String[] docIDs = args[1].split(",");

        App ap = new App();
        Files.walkFileTree(spamDir, ap);
        ArrayList scores = new ArrayList(); // keep scores in that list

        //Search the Lists in LinkedHashMap
        for(int j=0; j<docIDs.length; j++){
            Set set = ap.list.entrySet();
            Iterator i = set.iterator();
            int counter = 0;
            while(i.hasNext()){

                // if LinkedHashMap has the docID add it to scores List
                Map.Entry me = (Map.Entry) i.next();
                ArrayList searchList = (ArrayList) me.getValue();
                if(searchList.contains(docIDs[j])){
                    scores.add(me.getKey());
                    counter++;
                    break;

                }
                else {

                    continue;
                }

            }
            // if LinkedHashMap has not the docId add -1 to scores List
            if(counter == 0){
                scores.add("-1");
            }

        }

        String joined = String.join("," , scores);
        System.out.println(joined);

    }
}

But I encountered that problem :

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.util.Arrays.copyOf(Arrays.java:3181)
    at java.util.ArrayList.grow(ArrayList.java:261)
    at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
    at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
    at java.util.ArrayList.add(ArrayList.java:458)
    at ceng.bim208.App.visitFile(App.java:35)
    at ceng.bim208.App.visitFile(App.java:18)
    at java.nio.file.Files.walkFileTree(Files.java:2670)
    at java.nio.file.Files.walkFileTree(Files.java:2742)
    at ceng.bim208.App.main(App.java:58)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I tried to use XmX2048M to increase heap size but it doesn't solve my problem. What should i do?

In addition, if i run the program on a different path(include 2 txt file same format) it works correctly.

Body:
This sounds like an interview homework assignment. I bet that the task here is to take the mental leap and separate the data which you must hold in memory from those which you can store in an index while you parse the files.

No matter how much memory you have you'll run out of it eventually if you keep doing it like this. In your case there are some useful tips which you can use to fix this:

Don't put everything into the memory. Build an index if you can to a separate file which only holds the necessary data

Process the files as streams: this means that you parse the InputStream line by line, file by file and this way you don't have to keep them in memory.

In your case this:

public LinkedHashMap<String, List<String>> list

fills up the memory with the parsed Strings. From what I understand you don't need to store the Strings themselves but only the score. If you clarify what your task is I can help you further but currently it is not clear what your task is.

my task is take the docIds as a command-line argument and print out their scores.

What you need is a lookup for the scores:

Map<String, Map<Integer, Integer>> docIdsWithScoresAndCounts;

or

Map<String, List<Integer>> docIdsWithScores;

depending on whether you want to count how many times a score appeared. The outer Map holds the doc ids as keys and the inner maps are lookups themselves for score -> count. This is a tricky variation of the counting sort algorithm: you only need to keep track of the doc ids and the scores of each doc id and since the scores are limited in size (how many digits can they have?) you end up with O(1) memory consumption. The rest of the data can be thrown away.

Note that you only need to store the keys of the doc ids you are interested in. You can throw away the rest.


答:
pass the variables that you want to use from main method as parameter of the DisplayNum method

```<code>    public static void DisplayNum(int days,int num){
   int half = days / 2;
   int newnum = num + 2;

   System.out.println("Day \t Num");

       for (int current_day = 1; current_day <= (days/2); current_day++){
            newnum = newnum - 2;
            System.out.println(current_day + "\t" + (num + 2));
              }
       for (int current_day = (days/2) + 1; current_day <= days; current_day++){
                  newnum++;
                  System.out.println(current_day + "\t" + (num + 2));
              }
    }
</code>```

Then in main method pass in the values for parameter

```<code>public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);
    int days;
    int temp;                                          //variable for starting temperature

      System.out.print("Enter number of days in the period of time: ");
        days = keyboard.nextInt();

      System.out.print("Enter number for first day: ");
        num = keyboard.nextInt();

       DisplayNum(days,temp);
}
</code>```

Title: Call method from main method?

Body:
pass the variables that you want to use from main method as parameter of the DisplayNum method

    public static void DisplayNum(int days,int num){
   int half = days / 2;
   int newnum = num + 2;

   System.out.println("Day \t Num");

       for (int current_day = 1; current_day <= (days/2); current_day++){
            newnum = newnum - 2;
            System.out.println(current_day + "\t" + (num + 2));
              }
       for (int current_day = (days/2) + 1; current_day <= days; current_day++){
                  newnum++;
                  System.out.println(current_day + "\t" + (num + 2));
              }
    }

Then in main method pass in the values for parameter

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);
    int days;
    int temp;                                          //variable for starting temperature

      System.out.print("Enter number of days in the period of time: ");
        days = keyboard.nextInt();

      System.out.print("Enter number for first day: ");
        num = keyboard.nextInt();

       DisplayNum(days,temp);
}


问:
Get format string for date
I have a list of date strings, potentially very large. The format is unknown, but will be the same in all elements. Assume dateutil.parser will succeed in parsing it.

The problem is that the list is very large and dateutil.parser is slow. I could parse one element and then use a faster method (strptime, perhaps) if I could infer the format string. However, as far as I can tell, the parser does not give me the format string it succeeded with.

Is there an elegant solution?

答:
If you have some heavy calculation, I think you can use multithreading with the threading module.

```<code>import threading

thread = threading.Thread(target=some_def, args=(), kwargs={})
thread.start() # will run some_def
thread.join() # will wait until some_def is done
</code>```

Or in your's case:

import threading
    import dateutil.parser

```<code>threads = []
times = ["Sat Oct 11 17:13:46 UTC 2003", "Sat Oct 11 17:13:46 UTC 2004"]
for time in times:
    thread = threading.Thread(target=dateutil.parser.parser, args=(time))
    threads.append(thread)

for thread in threads:
    thread.start()

map(lambda thread: thread.join(), threads)
</code>```

For more information: Asynchronous method call in Python?.

Title: Get format string for date

Body:
If you have some heavy calculation, I think you can use multithreading with the threading module.

import threading

thread = threading.Thread(target=some_def, args=(), kwargs={})
thread.start() # will run some_def
thread.join() # will wait until some_def is done

Or in your's case:

import threading
    import dateutil.parser

threads = []
times = ["Sat Oct 11 17:13:46 UTC 2003", "Sat Oct 11 17:13:46 UTC 2004"]
for time in times:
    thread = threading.Thread(target=dateutil.parser.parser, args=(time))
    threads.append(thread)

for thread in threads:
    thread.start()

map(lambda thread: thread.join(), threads)

For more information: Asynchronous method call in Python?.


答:
You need to pass days and temp values ad arguments to your DisplayNum method.

You should define public static void DisplayNum(int days int temp) and call DisplayNum(days, temp) from your main method.

Title: Call method from main method?

Body:
Im trying to make 2 methods. The main method has the user input, and the other method called ShowNum should output the...output. Heres my original code with one main method:

public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int days;
int num;

System.out.print("Enter number of days: ");
days = keyboard.nextInt();

System.out.print("Enter number for first day: ");
num = keyboard.nextInt();

int half = days/2;
int newnum = num + 2;

      System.out.println("Day \t Number");

          for (int current_day = 1; current_day <= half; current_day++){
              newnum = newnum - 2;
              System.out.println(current_day + "\t" + (newnum + 2));
          }
          for (int current_day = half + 1; current_day <= days; current_day++){
              newnum++;
              System.out.println(current_day + "\t" + (newnum + 2));
          }

Ive tried this:

public static void DisplayNum(){
   int half = days / 2;
   int newnum = num + 2;

   System.out.println("Day \t Num");

       for (int current_day = 1; current_day <= (days/2); current_day++){
            newnum = newnum - 2;
            System.out.println(current_day + "\t" + (num + 2));
              }
       for (int current_day = (days/2) + 1; current_day <= days; current_day++){
                  newnum++;
                  System.out.println(current_day + "\t" + (num + 2));
              }
}

public static void main(String[] args){

    Scanner keyboard = new Scanner(System.in);
        int days;
        int num;

          System.out.print("Enter number of days in the period of time: ");
            days = keyboard.nextInt();

          System.out.print("Enter number for first day: ");
            num = keyboard.nextInt();

           DisplayNum();

Its a mess of errors because the variables aren't all defined in both methods but I don't know how to make them defined without just making it in one method. This is basically what my professor said to do yet I'm very confused. I'd appreciate help or any other advice. Thanks in advance.


问:
Production database tables not being created
I am using ASP.NET EntityFramework Core

My production environment database is not having tables created inside it.

As per this article: https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/

I have added this code to my Startup.Configure() method:

```<code>using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
       var context = serviceScope.ServiceProvider.GetService<MyContext>();
       context.Database.Migrate();
 }
</code>```

This does not work.  I am given no error message, there is just no tables created. (locally in development encironment I created them with update-database)

I am trying this on my production server.  The process I followed was to publish site and then upload the PublishOutput folder to the server.  The app works fine everywhere it doesn't require the database.

Does the published website contain the migrations?

How do I carry out the migrations on my production database?

Again, please note I am using the Core version.  Answers relating to older versions of entity framework do not apply.

答:
It works if I manually create the __EFMigrationsHistory table

```<code>CREATE TABLE `__EFMigrationsHistory` (
  `MigrationId` varchar(150) NOT NULL,
  `ProductVersion` varchar(32) NOT NULL
)
</code>```

Body:
I am using ASP.NET EntityFramework Core

My production environment database is not having tables created inside it.

As per this article: https://blogs.msdn.microsoft.com/dotnet/2016/09/29/implementing-seeding-custom-conventions-and-interceptors-in-ef-core-1-0/

I have added this code to my Startup.Configure() method:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
       var context = serviceScope.ServiceProvider.GetService<MyContext>();
       context.Database.Migrate();
 }

This does not work.  I am given no error message, there is just no tables created. (locally in development encironment I created them with update-database)

I am trying this on my production server.  The process I followed was to publish site and then upload the PublishOutput folder to the server.  The app works fine everywhere it doesn't require the database.

Does the published website contain the migrations?

How do I carry out the migrations on my production database?

Again, please note I am using the Core version.  Answers relating to older versions of entity framework do not apply.

Body:
It works if I manually create the __EFMigrationsHistory table

CREATE TABLE `__EFMigrationsHistory` (
  `MigrationId` varchar(150) NOT NULL,
  `ProductVersion` varchar(32) NOT NULL
)


答:
it's because you are trying to decode a not base64 encoded string
that it works on hi is just a coincidence it seems.

atob = decode

btoa = encode

Title: Decoding not working with Base64

Body:
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

document.write(atob("hi"));

This does not:

var tempvar = "hello";
document.write(atob(tempvar));

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.


问:
Facebook API post to page with page credentials
I was using a call to the facebook API to post news published in my website to our facebook page with a CURL call

```<code>$message= $facebook . " http://www.k-pop.com.mx/nota/".$date."/".$latestnews;
            //Post to facebook
            $data['picture'] = "http://www.k-pop.com.mx/images/news/".$ultima_noticia . "-" . $imageslug . ".jpg";
            $data['link'] = "http://www.k-pop.com.mx/nota/".$date."/".$imageslug;
            $data['message'] = $facebook;
            $data['caption'] = "K-Pop Mexico";
            $data['description'] = $descripcion;

            $data['access_token'] = "MY_LONG_ACCESS_TOKEN";
            $post_url = 'https://graph.facebook.com/PAGEID/feed';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $post_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $return = curl_exec($ch);
            curl_close($ch);
</code>```

but since a couple of days the posts have been publishing with my facebook personal user, instead of the page name.

I debugged my tokens to check if something was missing, but the token is there, I even created a new extended token with the next scopes:

```<code>user_birthday, user_photos, user_videos, user_friends, email, publish_actions, manage_pages, publish_pages, business_management, pages_messaging, pages_messaging_phone_number, public_profile
</code>```

Did facebook change something or is there an extra step I'm missing?

Thanks for your help in advance.

答:
Looks like I needed to create a page access token, by calling the url

https://graph.facebook.com/PAGE_ID?fields=access_token&access_token=MY_ACCESS_TOKEN

This returned a page access token and by using that token on the call the problem was fixed.

Body:
I was using a call to the facebook API to post news published in my website to our facebook page with a CURL call

$message= $facebook . " http://www.k-pop.com.mx/nota/".$date."/".$latestnews;
            //Post to facebook
            $data['picture'] = "http://www.k-pop.com.mx/images/news/".$ultima_noticia . "-" . $imageslug . ".jpg";
            $data['link'] = "http://www.k-pop.com.mx/nota/".$date."/".$imageslug;
            $data['message'] = $facebook;
            $data['caption'] = "K-Pop Mexico";
            $data['description'] = $descripcion;

            $data['access_token'] = "MY_LONG_ACCESS_TOKEN";
            $post_url = 'https://graph.facebook.com/PAGEID/feed';

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $post_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $return = curl_exec($ch);
            curl_close($ch);

but since a couple of days the posts have been publishing with my facebook personal user, instead of the page name.

I debugged my tokens to check if something was missing, but the token is there, I even created a new extended token with the next scopes:

user_birthday, user_photos, user_videos, user_friends, email, publish_actions, manage_pages, publish_pages, business_management, pages_messaging, pages_messaging_phone_number, public_profile

Did facebook change something or is there an extra step I'm missing?

Thanks for your help in advance.


问:
Regex in JavaScript replace function break script after uglifyjs or minify run
Could someone with more regex experience than me help me out?

```<code>return path.replace(/\//g, '.').replace(/^\./, '');
</code>```

I have found this regex in a js file within a giant app. The JS when run through npm node-minify or any of the others sees it as a comment and turns it into this:

```<code>return path.replace(/\g, '.').replace(/^\./, '');
</code>```

I get the first bit is replacing all \ with a .  and the second bit trims any leading . from the string. Can i change this so the regex pattern is wrapped in quotes?

答:
Just use the RegExp constructor and quote your pattern.

const path = '/usr/bin/env';
const matchSlash = new RegExp('/', 'g');
const translate = path => path.replace(matchSlash, '.').replace(/^\./, '');
console.log(translate(path));```

Body:
Could someone with more regex experience than me help me out?

return path.replace(/\//g, '.').replace(/^\./, '');

I have found this regex in a js file within a giant app. The JS when run through npm node-minify or any of the others sees it as a comment and turns it into this:

return path.replace(/\g, '.').replace(/^\./, '');

I get the first bit is replacing all \ with a .  and the second bit trims any leading . from the string. Can i change this so the regex pattern is wrapped in quotes?


问:
Setting a limit to a queue size
How does one set a queue to hold N values. When the N is reached, remove the last item and add a value to the front of the queue.

Should this be done with if statement?

I also want to calculate the values within the queue as a new item is added. e.g. add all of the values in the queue.

答:
I assume from your query that you both want to maximize the length of the queue and get the sum of all the values.

To answer your easiest question first: Erlang queues, however you wish to represent them, are normal Erlang data structures so there are no problems in storing them in a dictionary.

The OTP queue module is actually very simple but the plethora of interfaces easily makes it confusing to use. @Nathon's enqueue function can be made much more efficient by not using the queue data structure directly but by defining your own data structure which includes the queue and its current length, {Length,Queue}. If the sum is important then you could even include it as well.

The queue representations are very simple so it is very easy to write your own specialised form of it.

The simplest way is to keep the queue in a list and take elements from the head and add new elements to the end. So :

```<code>new(Max) when is_integer(Max), Max > 0 -> {0,Max,[]}.   %Length, Max and Queue list

take({L,M,[H|T]}) -> {H,{L-1,M,T}}.

add(E, {L,M,Q}) when L < M ->
    {L+1,M,Q ++ [E]};                                   %Add element to end of list
add(E, {M,M,[H|T]}) -
    {M,M,T ++ [E]}.                                     %Add element to end of list
</code>```

When the queue becomes full the oldest member, which is at the front of the queue, is dropped. An empty queue generates an error. This is a very simple structure but it is inefficient as the queue is copied every time a new element is added. Reversing the list does not help as then the list is copied every time an element is removed from it. But it is simple, and it does work.

A much more efficient structure is to split the queue into two lists, the front end of the queue and the rear end of the queue. The rear end is reversed and becomes the new front when the front is empty. So:

```<code>new(Max) when is_integer(Max), Max > 0 ->
    {0,Max,[],[]}.                                      %Length, Max, Rear and Front

take({L,M,R,[H|T]}) -> {H,{L-1,M,R,T}};
take{{L,M,R,[]}) when L > 0 ->
    take({L,M,[],lists:reverse(R)}).                    %Move the rear to the front

add(E, {L,M,R,F}) when L < M ->
    {L+1,M,[R|E],F};                                    %Add element to rear
add(E, {M,M,R,[H|T]}) ->
    {M,M,[R|E],T};                                      %Add element to rear
add(E, {M,M,R,[]}) ->
    add(E, {M,M,[],lists:reverse(R)}).                  %Move the rear to the front
</code>```

Again when the queue becomes full the oldest member, which is at the front of the queue, is dropped and an empty queue generates an error. This is the data structure used in the queue module.

It would be very easy to add the current sum of the elements to the structure and manage it directly.

Often, when working on simple data structures like this, it is just as easy to roll your own module as it is to use a provided one.

Title: Setting a limit to a queue size

Body:
I assume from your query that you both want to maximize the length of the queue and get the sum of all the values.

To answer your easiest question first: Erlang queues, however you wish to represent them, are normal Erlang data structures so there are no problems in storing them in a dictionary.

The OTP queue module is actually very simple but the plethora of interfaces easily makes it confusing to use. @Nathon's enqueue function can be made much more efficient by not using the queue data structure directly but by defining your own data structure which includes the queue and its current length, {Length,Queue}. If the sum is important then you could even include it as well.

The queue representations are very simple so it is very easy to write your own specialised form of it.

The simplest way is to keep the queue in a list and take elements from the head and add new elements to the end. So :

new(Max) when is_integer(Max), Max > 0 -> {0,Max,[]}.   %Length, Max and Queue list

take({L,M,[H|T]}) -> {H,{L-1,M,T}}.

add(E, {L,M,Q}) when L < M ->
    {L+1,M,Q ++ [E]};                                   %Add element to end of list
add(E, {M,M,[H|T]}) -
    {M,M,T ++ [E]}.                                     %Add element to end of list

When the queue becomes full the oldest member, which is at the front of the queue, is dropped. An empty queue generates an error. This is a very simple structure but it is inefficient as the queue is copied every time a new element is added. Reversing the list does not help as then the list is copied every time an element is removed from it. But it is simple, and it does work.

A much more efficient structure is to split the queue into two lists, the front end of the queue and the rear end of the queue. The rear end is reversed and becomes the new front when the front is empty. So:

new(Max) when is_integer(Max), Max > 0 ->
    {0,Max,[],[]}.                                      %Length, Max, Rear and Front

take({L,M,R,[H|T]}) -> {H,{L-1,M,R,T}};
take{{L,M,R,[]}) when L > 0 ->
    take({L,M,[],lists:reverse(R)}).                    %Move the rear to the front

add(E, {L,M,R,F}) when L < M ->
    {L+1,M,[R|E],F};                                    %Add element to rear
add(E, {M,M,R,[H|T]}) ->
    {M,M,[R|E],T};                                      %Add element to rear
add(E, {M,M,R,[]}) ->
    add(E, {M,M,[],lists:reverse(R)}).                  %Move the rear to the front

Again when the queue becomes full the oldest member, which is at the front of the queue, is dropped and an empty queue generates an error. This is the data structure used in the queue module.

It would be very easy to add the current sum of the elements to the structure and manage it directly.

Often, when working on simple data structures like this, it is just as easy to roll your own module as it is to use a provided one.


问:
Deleting all data in a Core Data entity in Swift 3
Is there a way to do a batch delete of all data stored in all of the entities in core data?

I read somewhere that in iOS 9 or 10 that apple introduced a way to do batch deletes, but I can't seem to find any good information on it.

Ultimately, I just need a function that goes through an entity, and deletes all of the data in it. Seems like it should be simple enough, but documentation/tutorials for it have proven exceedingly difficult to find.

Any thoughts?

Edit

I added the following code into an IBAction attached to a button:

```<code>@IBAction func clearAllData(_ sender: AnyObject) {
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PLProjects")
    let request = NSBatchDeleteRequest(fetchRequest: fetch)

    //get the data from core data
    getPLData()

    //reload the table view
    tableView.reloadData()
}
</code>```

This does not seem to work however. If I close down the project and reopen it, the data is still there. I am assuming this is also why the table view doesn't update, because the data is not actually being deleted.

答:
To flesh out Tom's reply, this is what I added to have a complete routine:</p>

```<code>func deleteAllRecords() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext

    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "CurrentCourse")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

    do {
        try context.execute(deleteRequest)
        try context.save()
    } catch {
        print ("There was an error")
    }
}
</code>```

Body:
Is there a way to do a batch delete of all data stored in all of the entities in core data?

I read somewhere that in iOS 9 or 10 that apple introduced a way to do batch deletes, but I can't seem to find any good information on it.

Ultimately, I just need a function that goes through an entity, and deletes all of the data in it. Seems like it should be simple enough, but documentation/tutorials for it have proven exceedingly difficult to find.

Any thoughts?

Edit

I added the following code into an IBAction attached to a button:

@IBAction func clearAllData(_ sender: AnyObject) {
    let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "PLProjects")
    let request = NSBatchDeleteRequest(fetchRequest: fetch)

    //get the data from core data
    getPLData()

    //reload the table view
    tableView.reloadData()
}

This does not seem to work however. If I close down the project and reopen it, the data is still there. I am assuming this is also why the table view doesn't update, because the data is not actually being deleted.

Body:
To flesh out Tom's reply, this is what I added to have a complete routine:

func deleteAllRecords() {
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext

    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "CurrentCourse")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

    do {
        try context.execute(deleteRequest)
        try context.save()
    } catch {
        print ("There was an error")
    }
}


问:
Deleting head or only node in Linked List in C
I am writing a function which removes a specific node from the linked list. The function works for most cases but does not work when the node to delete is either the head node, or the only node in the linked list. I tried setting the current to equal NULL when this case happens but that creates a segmentation fault, where is my logic wrong?</p>

```<code>void deleteNodeAfter(Node *head, Node *delete) {
    bool remove = false;
    Node *current = head;
    Node *delNode = delete;
    if (current->songName == delNode->songName){
        current= NULL;
        remove = true;
    }
    while (!remove) {
        if (current->link->songName == delNode->songName) {
            current->link = delNode->link;
            remove = true;
            // free(delNode);
        } else {
            current = current->link;
        }
    }
}
</code>```

答:
```<code>void deleteNodeAfter(Node **head, Node *delete) {
  bool remove = false;
  Node *current;
  while(current=*head;head=&(current->next),current=*head;current)
  {
    if (current->songName == delNode->songName){
      // perhaps the above check should be   current==delNode
      *head=current->next
      free(current)
      return;
    }
  }
}
</code>```

You need to pass in a pointer to the pointer to the list so that the pointer-to-llist can be updated by the delete operation.

Body:
I am writing a function which removes a specific node from the linked list. The function works for most cases but does not work when the node to delete is either the head node, or the only node in the linked list. I tried setting the current to equal NULL when this case happens but that creates a segmentation fault, where is my logic wrong?

void deleteNodeAfter(Node *head, Node *delete) {
    bool remove = false;
    Node *current = head;
    Node *delNode = delete;
    if (current->songName == delNode->songName){
        current= NULL;
        remove = true;
    }
    while (!remove) {
        if (current->link->songName == delNode->songName) {
            current->link = delNode->link;
            remove = true;
            // free(delNode);
        } else {
            current = current->link;
        }
    }
}

Body:
void deleteNodeAfter(Node **head, Node *delete) {
  bool remove = false;
  Node *current;
  while(current=*head;head=&(current->next),current=*head;current)
  {
    if (current->songName == delNode->songName){
      // perhaps the above check should be   current==delNode
      *head=current->next
      free(current)
      return;
    }
  }
}

You need to pass in a pointer to the pointer to the list so that the pointer-to-llist can be updated by the delete operation.


问:
Using .stage not giving desired result
I make a global variable equal to a movieclip

A function gets run with an if statement checking if [x] movieclip exists, if it doesn't add it.
Despite the MovieClip being on the stage it continues using the if statement.

Document class

```<code>public static var skinHolder:MovieClip = new test;
</code>```

Seperate Class (function runs every frame)

```<code>    function animHandler():void
    {
        if (! Game.skinHolder.stage)
        {
            // if its not on the stage we add it to the stage
            addChild(Game.skinHolder);
        }

    }
</code>```

答:
The stage is not set immediately after a MovieClip is added, usually it happens on the next frame.

It is an odd way to check if an object exist though, you should do something like this:

```<code>private var mySkinHolder:MovieClip;

if (!mySkinHolder)
{
    // if it not exist we add it to the stage
    mySkinHolder = addChild(new test());
}
</code>```

Title: Using .stage not giving desired result

Body:
I make a global variable equal to a movieclip

A function gets run with an if statement checking if [x] movieclip exists, if it doesn't add it.
Despite the MovieClip being on the stage it continues using the if statement.

Document class

public static var skinHolder:MovieClip = new test;

Seperate Class (function runs every frame)

    function animHandler():void
    {
        if (! Game.skinHolder.stage)
        {
            // if its not on the stage we add it to the stage
            addChild(Game.skinHolder);
        }

    }

Body:
The stage is not set immediately after a MovieClip is added, usually it happens on the next frame.

It is an odd way to check if an object exist though, you should do something like this:

private var mySkinHolder:MovieClip;

if (!mySkinHolder)
{
    // if it not exist we add it to the stage
    mySkinHolder = addChild(new test());
}


问:
PHP fileUpload with Pdf/Docx Instead of Image
I have an example code below working for images as user's input,

```<code><?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
</code>```

but my main intention is to upload Pdf & Docx as user's input this time instead of images.

I tried to change but couldn't succeeded. Any link or at least a description with a couple of links I can assume the rest works for me (I hoped if it's a duplicate but not asked the same way I guess).

答:
Basically, I just changed all $imagefileType to $fileType and it works!! I just skipped the image check as shown with the comment section below. Even not sure if it is needed for pdf/doc & docx unlike image. I appreciate If anyone provide additional information I skipped or it's already fine this way @bxN5 @Ravinder Reddy.

It's just simple as is.

```<code><?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
/*
if(isset($_POST["submit"])) {
    $check = getfilesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
*/
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($fileType != "pdf" && $fileType != "doc" && $fileType != "docx") {
    echo "Sorry, only PDF, DOC & DOCX files are allowed.";
    $uploadOk = 0;
}
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
</code>```

Body:
I have an example code below working for images as user's input,

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";

} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

but my main intention is to upload Pdf & Docx as user's input this time instead of images.

I tried to change but couldn't succeeded. Any link or at least a description with a couple of links I can assume the rest works for me (I hoped if it's a duplicate but not asked the same way I guess).

Body:
Basically, I just changed all $imagefileType to $fileType and it works!! I just skipped the image check as shown with the comment section below. Even not sure if it is needed for pdf/doc & docx unlike image. I appreciate If anyone provide additional information I skipped or it's already fine this way @bxN5 @Ravinder Reddy.

It's just simple as is.

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
/*
if(isset($_POST["submit"])) {
    $check = getfilesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
*/
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
if($fileType != "pdf" && $fileType != "doc" && $fileType != "docx") {
    echo "Sorry, only PDF, DOC & DOCX files are allowed.";
    $uploadOk = 0;
}
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>


问:
geom_area different fill colour when above critical level
I am trying to get a geom_area to have twin colours dependant on value of Y axis.

So for example if we have a geom_area with a max X value of 50, I would like the fill colour to be blue when below 10 and red when above 10.

Sample Data;

```<code>df <- data.frame(
  y = sample(1:50),
  x = sample(1:50)
)
</code>```

The closest that I have managed to get thus far is by using the following code;

```<code>ggplot(data = df, aes(x = x)) +
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue")
</code>```

This almost gets me what I require however the problem is that the horizontal split is not completely across the geom_area, as when the next value falls below the max value the edge of the ribbon goes straight to the next point, which upsets the split.

This is plotting exactly what the code tells it, so I must be using the wrong method to create the split in colours, but cannot figure out how to do it correctly.

答:
A quick fix would be to interpolate between the x-values using approx. Set the n argument (the number of interpolation points) to a high-enough value to get blue all the way across:

```<code>ggplot(data = as.data.frame(approx(df,n=1000)), aes(x = x)) +
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue") +
  theme_classic()
</code>```

Body:
I am trying to get a geom_area to have twin colours dependant on value of Y axis.

So for example if we have a geom_area with a max X value of 50, I would like the fill colour to be blue when below 10 and red when above 10.

Sample Data;

df <- data.frame(
  y = sample(1:50),
  x = sample(1:50)
)

The closest that I have managed to get thus far is by using the following code;

ggplot(data = df, aes(x = x)) +
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue")

This almost gets me what I require however the problem is that the horizontal split is not completely across the geom_area, as when the next value falls below the max value the edge of the ribbon goes straight to the next point, which upsets the split.

This is plotting exactly what the code tells it, so I must be using the wrong method to create the split in colours, but cannot figure out how to do it correctly.

Body:
A quick fix would be to interpolate between the x-values using approx. Set the n argument (the number of interpolation points) to a high-enough value to get blue all the way across:

ggplot(data = as.data.frame(approx(df,n=1000)), aes(x = x)) +
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue") +
  theme_classic()


问:
url path parameter with % sign
I am using rg.glassfish.jersey.server.ApplicationHandler
need to capture the url path

```<code>URL: video/Id19%2Fabc%3D/title?sub=CDA
</code>```

I have tried the following to capture but this doesn't capture % sign.

```<code>@Path("/video/{Id:.*}/title/")
</code>```

答:
Is this what you're looking for?

https://regex101.com/r/qYs7gQ/3

```<code>Regex: video\/Id(?<ID>.*)\/title
</code>```

Title: url path parameter with % sign

Body:
I am using rg.glassfish.jersey.server.ApplicationHandler
need to capture the url path

URL: video/Id19%2Fabc%3D/title?sub=CDA

I have tried the following to capture but this doesn't capture % sign.

@Path("/video/{Id:.*}/title/")

Body:
Is this what you're looking for?

https://regex101.com/r/qYs7gQ/3

Regex: video\/Id(?<ID>.*)\/title


问:
STL std::map, pass by ref to const and the necessity of const_casting
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

```<code>#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};
</code>```

Definition:

```<code>#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}
</code>```

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

答:
Why not use a map<const Widget*,int>? You don't seem to ever modify the Widget pointed to by any of the keys in your map.

Assuming there's a good reason then yes, I think you're right. When calling code which is guaranteed not to modify the referand of the pointer, it's safe to cast away const. Because of the way containers of pointers are templated, none of their functions ever directly modify that referand, but if the contained type were a const pointer, then users wouldn't be able to modify the referand either (without a const cast). It's certainly safer to cast away const before searching, than to cast away const before modifying, if it must be one of the two...

Btw, hasWidget would be shorter if you use count rather than find. It's also marginally const-safer in general (not in this case) to use count, because find with this const_cast returns an iterator that could be used to modify the Widget, whereas count doesn't. So you don't have to worry what happens to the return value of count. Obviously here that return value is entirely under control anyway.

Body:
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};

Definition:

#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.


问:
laravel carbon unset date
Right now I have a model that has a "followup" date that is rotected to convert to carbon (). The issue is in my controller if I have some dates that are not set and default (0000-00-00) Carbon returns them as -0001-11-30 00:00:00.000000. I get why, but trying to target those dates and just return "none" but cant figure out how.

in my controller:

```<code>foreach ($account->notes as $note) {

                $notes[$i]['note']       = $note;
                $notes[$i]['account']    = $account->name;

                if($note->followup != '-0001-11-30 00:00:00.000000'){
                     $notes[$i]['followup']   = $note->followup->diffForHumans();
                 } else {
                    $notes[$i]['followup']   = 'None';
                 }

               $i += 1;
           }
</code>```

答:
The following approach should give you the output you're looking for:

```<code>foreach ($account->notes as $note) {
    $notes[$i]['note']     = $note;
    $notes[$i]['account']  = $account->name;
    $notes[$i]['followup'] = (substr($note->followup, 0, 1) !== '-') ? $note->followup->diffForHumans() : 'None';

    $i += 1;
}
</code>```

But I'm confused as to why the approach you posted isn't working if you're checking for the precise value you're dumping out in your conditional statement.

Title: laravel carbon unset date

Body:
Right now I have a model that has a "followup" date that is rotected to convert to carbon (). The issue is in my controller if I have some dates that are not set and default (0000-00-00) Carbon returns them as -0001-11-30 00:00:00.000000. I get why, but trying to target those dates and just return "none" but cant figure out how.

in my controller:

foreach ($account->notes as $note) {

                $notes[$i]['note']       = $note;
                $notes[$i]['account']    = $account->name;

                if($note->followup != '-0001-11-30 00:00:00.000000'){
                     $notes[$i]['followup']   = $note->followup->diffForHumans();
                 } else {
                    $notes[$i]['followup']   = 'None';
                 }

               $i += 1;
           }

Body:
The following approach should give you the output you're looking for:

foreach ($account->notes as $note) {
    $notes[$i]['note']     = $note;
    $notes[$i]['account']  = $account->name;
    $notes[$i]['followup'] = (substr($note->followup, 0, 1) !== '-') ? $note->followup->diffForHumans() : 'None';

    $i += 1;
}

But I'm confused as to why the approach you posted isn't working if you're checking for the precise value you're dumping out in your conditional statement.


问:
(&const_object) can be evaluated to address of temporary
I had a discussion with one programmer, and its main point was that the following assertion in foo can be passed or not, depending on compiler.

```<code>#include <cassert>

const int i = 0 ;

void foo ( const int& i )
{
    assert( &::i == &i ) ;
}

int main ( )
{
    foo( i ) ;
}
</code>```

he told me, that (&i) expression can be evaluated to address of some temporary object.
since i have doubts, i'm here.
how reference to temp can be passed to a function, if in function I can check and do whatever I want with i's and parameter's addresses and expected semantics must be kept.? for example

```<code>#include <initializer_list>

const int i = 0 ;

bool func ( const int & i )
{
    return &::i == & i ;
}

int main ()
{
    const int i = 0 ;
    for ( const int * each : { &::i , &i , } )
         if ( func( * each ) ) break ; // etc
}
</code>```

probably such thing can occur somewhere, but not for this case.
that is how i think, but i cannot get complete proof from standard.

what i have found already (thanks to npw) :

from [expr.call#5] :

Where a parameter is of const reference type a temporary object is
  introduced if needed ([dcl.type], [lex.literal], [lex.string],
  [dcl.array], [class.temporary])

first four references are not applicable to my case, but fifth gives a hope.

so my question is : does standard give guaranties, that assertion in foo will be hold.?

答:
In the first code sample, the &::i == &i condition is always true.  A reference of type const int& binds directly to an object of type const int.  There is no temporary object created.

C++14 [dcl.init.ref]/5:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

If the reference is an lvalue reference and the initializer expression

is an lvalue (but is not a bit-field), and “ cv1 T1” is reference-compatible with “ cv2 T2,” or

[...],
  then the reference is bound to the initializer expression lvalue in the first case  [...]

A type is reference-compatible with itself.

The second example is similar: certainly, initializing a pointer with the address of an object does not create a temporary. It points to the object.

Body:
I had a discussion with one programmer, and its main point was that the following assertion in foo can be passed or not, depending on compiler.

#include <cassert>

const int i = 0 ;

void foo ( const int& i )
{
    assert( &::i == &i ) ;
}

int main ( )
{
    foo( i ) ;
}

he told me, that (&i) expression can be evaluated to address of some temporary object.
since i have doubts, i'm here.
how reference to temp can be passed to a function, if in function I can check and do whatever I want with i's and parameter's addresses and expected semantics must be kept.? for example

#include <initializer_list>

const int i = 0 ;

bool func ( const int & i )
{
    return &::i == & i ;
}

int main ()
{
    const int i = 0 ;
    for ( const int * each : { &::i , &i , } )
         if ( func( * each ) ) break ; // etc
}

probably such thing can occur somewhere, but not for this case.
that is how i think, but i cannot get complete proof from standard.

what i have found already (thanks to npw) :

from [expr.call#5] :

Where a parameter is of const reference type a temporary object is
  introduced if needed ([dcl.type], [lex.literal], [lex.string],
  [dcl.array], [class.temporary])

first four references are not applicable to my case, but fifth gives a hope.

so my question is : does standard give guaranties, that assertion in foo will be hold.?


问:
Show Message if successful sql request is done
I want to show message if my sql request is done with no problems. In this moment i have code that show MessageBox for every successful done request, but if there is no username and is didn't done again it's showing the same messagebox.

```<code>try
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand("DELETE FROM dbo.Admin WHERE UserName  = '" + txtUserName.Text +"'", con))
        {
            command.ExecuteNonQuery();
            MessageBox.Show("Successful operation!");
        }
        con.Close();
    }
</code>```

How can i fix that? I want to show successful operation only if there is result from sql request, not everytime when i am doing that command.

答:
You could just get the number of rows affected as below:

```<code>var numbersOfAffectedRows = command.ExecuteNonQuery();
</code>```

and then check if it is greater than zero.

```<code>if(numbersOfAffectedRows>0)
{
    MessageBox.Show("Successful operation!");
}
</code>```

Body:
I want to show message if my sql request is done with no problems. In this moment i have code that show MessageBox for every successful done request, but if there is no username and is didn't done again it's showing the same messagebox.

try
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        con.Open();
        using (SqlCommand command = new SqlCommand("DELETE FROM dbo.Admin WHERE UserName  = '" + txtUserName.Text +"'", con))
        {
            command.ExecuteNonQuery();
            MessageBox.Show("Successful operation!");
        }
        con.Close();
    }

How can i fix that? I want to show successful operation only if there is result from sql request, not everytime when i am doing that command.

Body:
You could just get the number of rows affected as below:

var numbersOfAffectedRows = command.ExecuteNonQuery();

and then check if it is greater than zero.

if(numbersOfAffectedRows>0)
{
    MessageBox.Show("Successful operation!");
}


问:
Adding fragments to a fragment
I am very new to Android (been at it for 1 week), and I can't seem to find the answer to what I am after.

I have in my main activity 3 tabs:

Home

Trending

Profile

When clicking each tab, I effectively load a fragment (corresponding to each one of my tabs) into my Main activity layout.

Additionally I have a fragment called articleEntryFragment.

For every one of my tab fragments I would like to load multiple article entries.

But as I understand it. Nested fragments don't work on APIs earlier than 17, and I want to have as much backward compatibility as possible.

Therefore, how is this very basic principal achieved?

For instance, when you go on the YouTube app, there are tabs, each tab has different videos.

It's my assumption that like in my app. Every tab is its own fragment, and every video listing uses a similar concept to my articleEntry fragment.

What's the proper way to achieve what I am after?

Thank you.

p.s. not looking for anyone to write code for me, but rather, direct me in the right path.

答:
Although nested fragments were introduced in API 17, they are available in the support library down to Android version 1.6. See "Nested Fragment" here.

The Android Support Library also now supports nested fragments, so you can implement nested fragment designs on Android 1.6 and higher.

You will need to include the support library in your build to use nested fragments.

Hope that helps.

Title: Adding fragments to a fragment


问:
Decoding not working with Base64
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

```<code>document.write(atob("hi"));
</code>```

This does not:

```<code>var tempvar = "hello";
document.write(atob(tempvar));
</code>```

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.

答:
You're using the wrong function. You should use btoa() to encode.

When you do atob('hi'), you're actually decoding 'hi', which happens to be valid base-64.

Title: Decoding not working with Base64

Body:
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

document.write(atob("hi"));

This does not:

var tempvar = "hello";
document.write(atob(tempvar));

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.


答:
Look at the result of ExecuteNonQuery method, it returns the number of row that's affected. So if it's higher than 0, u can show the message box:

```<code>if(command.ExecuteNonQuery() > 0)
{
    MessageBox.Show("Successful operation!");
}
</code>```

There is another problem in your code in terms of security, you should never build an sql query by concatenating plain user input, instead you should use Sql parameters, you can learn more about that and sql injection in general from the below links:

http://bobby-tables.com/

How do parameterized queries help against SQL injection?

How does SQLParameter prevent SQL Injection?

Title: Show Message if successful sql request is done

Body:
Look at the result of ExecuteNonQuery method, it returns the number of row that's affected. So if it's higher than 0, u can show the message box:

if(command.ExecuteNonQuery() > 0)
{
    MessageBox.Show("Successful operation!");
}

There is another problem in your code in terms of security, you should never build an sql query by concatenating plain user input, instead you should use Sql parameters, you can learn more about that and sql injection in general from the below links:

http://bobby-tables.com/

How do parameterized queries help against SQL injection?

How does SQLParameter prevent SQL Injection?