问:
Send SMS using HP UFT 12.02
I have a requirement of sending SMS to single/multiple users in case of any failure while executing a UFT automation script.
I have used below code & updated the smtp server name to the one I found in Outlook Account settings.Below code is failing with error "At least one recipient is required but none were found".

Please help me resolve this issue. Also note that I cannot use any free SMS API due to access restrictions

```<code>Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Test Failed"
objMessage.Sender = "test@domain.com"
objMessage.To = "+91XXXXXXXXXX"
objMessage.TextBody = "Test XYZ failed at: " & Now
'Configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "Server
 name"
'Server port
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send
Set objMessage = Nothing
</code>```

答:
CDO.Message uses SMTP!

SMTP

First of all you should know what SMPT is and for what it stands!

SMTP is a communication protocol for the transmission of E-Mails. Communication takes place between an e-mail client and an SMTP-Server or between two SMTP-Servers.

In addition to SMTP, there are two other protocols for E-Mail exchange with POP and IMAP. However, these two protocols are only used to fetch or manage E-Mail. SMTP, on the other hand, is a communication protocol that can receive and forward emails.

SMTP stands for Simple Mail Transfer Protocol.

Your Problem

You want to send Messages with HP UFT and you are trying to do this with SMTP. But now we know this isn't possible

Answer: It isn't possible to send SMS over HP UFT.

Title: Send SMS using HP UFT 12.02

Body:
I have a requirement of sending SMS to single/multiple users in case of any failure while executing a UFT automation script.
I have used below code & updated the smtp server name to the one I found in Outlook Account settings.Below code is failing with error "At least one recipient is required but none were found".

Please help me resolve this issue. Also note that I cannot use any free SMS API due to access restrictions

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Test Failed"
objMessage.Sender = "test@domain.com"
objMessage.To = "+91XXXXXXXXXX"
objMessage.TextBody = "Test XYZ failed at: " & Now
'Configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "Server
 name"
'Server port
objMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMessage.Configuration.Fields.Update
objMessage.Send
Set objMessage = Nothing


来源: stackexchange

问:
How to call ngOnInit() again in Angular 2?
Please explain in this code, how to call ngOnInit() again when I call another method?

ngOnInit(): void {
  this.route.params.subscribe((params: Params) => {
    this.model = this.userData;
  });
}

update() {
  this.loading = true;
  this.userService.update(this.model).subscribe(
    (data) => {
      alert('Update successful');
    },
    (error) => {
      alert('Not updated');
      this.loading = false;
    },
  );
  this.user_data();
}
```

答:
ngOnInit called once the component is created. so you can create a function and call the function again. Here is the sample code.

```<code>ngOnInit(): void {
    this.callFun();
}

update() {
    this.callFun();
    // do code
}

private callFun(){
   // do code
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
ngOnInit called once the component is created. so you can create a function and call the function again. Here is the sample code.

ngOnInit(): void {
    this.callFun();
}

update() {
    this.callFun();
    // do code
}

private callFun(){
   // do code
}

ContentLicense: CC BY-SA 3.0


问:
Reversing the letters in words in a String
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

```<code> // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }
</code>```

Here is my output for some tests of mine:

```<code>     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }
</code>```

答:
This would probably work with the punctuation:

```<code>public static String reverse(String x)
{
     String[] str = x.split("\\W"); //Split on non-word characters.

     StringBuilder rev = new StringBuilder("");
     int currentPosition = 0;
     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
             currentPosition++;
         }
         while (currentPosition < x.length() && Character.toString(x.charAt(currentPosition)).matches("\\W"))
            rev.append(x.charAt(currentPosition++)); //Add the actual character there.
     }

     return rev.toString();
 }
</code>```

Haven't coded in Java in a while now so I know it's probably not best practices here.

Complexity is O(n) (space and time).

If you start off with a string builder you might be able to lower space complexity by using in-place character swaps instead of appending, but you'd need to preemptively find where all the non-word characters are.

Body:
I have coded the following solution, and it works, except for when there is punctuation. I was wondering if there are O(1) space complexity and O(length of string) time complexity solutions, without using reverse() method, or anything similar that makes this task too easy. Any answer that can also handle punctuation correctly would be great.

Example:

Given string: "I love chocolate"

Return string should be: "I evol etalocohc"

For clarity, when I say handle punctuation correctly, I mean punctuation should not move around.

 // reverse the letters of every word in a sentence (string), and return the result

 public static String reverse(String x)
 {
     String[] str = x.split(" ");

     StringBuilder rev = new StringBuilder("");

     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
         }
         rev.append(" ");
     }

     return rev.toString();
 }

Here is my output for some tests of mine:

     public static void main(String[] args)
     {
         System.out.println(reverse("I love chocolate"));//this passes
         System.out.println(reverse("Geeks for Geeks"));//this passes
         System.out.println(reverse("You, are awesome"));//not handling puncutation mark correctly, gives me ",uoY era emosewa", instead of "uoY, era emosewa"
         System.out.println(reverse("Geeks! for Geeks."));//not handling puncutation marks correctly, gives me "!skeeG rof .skeeG", instead of "skeeG! rof skeeG."
     }

Body:
This would probably work with the punctuation:

public static String reverse(String x)
{
     String[] str = x.split("\\W"); //Split on non-word characters.

     StringBuilder rev = new StringBuilder("");
     int currentPosition = 0;
     for (int i = 0; i < str.length; i++)
     {
         for (int s = str[i].length()-1; s >= 0; s--)
         {
             rev.append(str[i].charAt(s));
             currentPosition++;
         }
         while (currentPosition < x.length() && Character.toString(x.charAt(currentPosition)).matches("\\W"))
            rev.append(x.charAt(currentPosition++)); //Add the actual character there.
     }

     return rev.toString();
 }

Haven't coded in Java in a while now so I know it's probably not best practices here.

Complexity is O(n) (space and time).

If you start off with a string builder you might be able to lower space complexity by using in-place character swaps instead of appending, but you'd need to preemptively find where all the non-word characters are.


问:
how to customize snackBar's layout?
Is there any method to change the layout of a snackBar to custom View?

Now it comes black and we can change the background color.
But I don't know the right way to inflate a new layout and making it as snackBars background?

Thanks...

答:
```<code>private Snackbar showSnackbar(CoordinatorLayout coordinatorLayout, int duration) { // Create the Snackbar
    Snackbar snackbar = Snackbar.make(coordinatorLayout, "", duration);
    // 15 is margin from all the sides for snackbar
    int marginFromSides = 15;

    float height = 100;

    //inflate view
    View snackView = getLayoutInflater().inflate(R.layout.snackbar_layout, null);

    // White background
    snackbar.getView().setBackgroundColor(Color.WHITE);
    // for rounded edges
    snackbar.getView().setBackground(getResources().getDrawable(R.drawable.round_edges));

    Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
    FrameLayout.LayoutParams parentParams = (FrameLayout.LayoutParams) snackBarView.getLayoutParams();
    parentParams.setMargins(marginFromSides, 0, marginFromSides, marginFromSides);
    parentParams.height = (int) height;
    parentParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
    snackBarView.setLayoutParams(parentParams);

    snackBarView.addView(snackView, 0);
    return snackbar;
}
</code>```

In onCreate of the Activity:

```<code>CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinator_layout);

final Snackbar snackbar = showSnackbar(coordinatorLayout, Snackbar.LENGTH_LONG);
            snackbar.show();
            View view = snackbar.getView();
            TextView tv = (TextView) view.findViewById(R.id.snackbar_action);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    snackbar.dismiss();
                }
            });
</code>```

Title: how to customize snackBar's layout?

Body:
private Snackbar showSnackbar(CoordinatorLayout coordinatorLayout, int duration) { // Create the Snackbar
    Snackbar snackbar = Snackbar.make(coordinatorLayout, "", duration);
    // 15 is margin from all the sides for snackbar
    int marginFromSides = 15;

    float height = 100;

    //inflate view
    View snackView = getLayoutInflater().inflate(R.layout.snackbar_layout, null);

    // White background
    snackbar.getView().setBackgroundColor(Color.WHITE);
    // for rounded edges
    snackbar.getView().setBackground(getResources().getDrawable(R.drawable.round_edges));

    Snackbar.SnackbarLayout snackBarView = (Snackbar.SnackbarLayout) snackbar.getView();
    FrameLayout.LayoutParams parentParams = (FrameLayout.LayoutParams) snackBarView.getLayoutParams();
    parentParams.setMargins(marginFromSides, 0, marginFromSides, marginFromSides);
    parentParams.height = (int) height;
    parentParams.width = FrameLayout.LayoutParams.MATCH_PARENT;
    snackBarView.setLayoutParams(parentParams);

    snackBarView.addView(snackView, 0);
    return snackbar;
}

In onCreate of the Activity:

CoordinatorLayout coordinatorLayout = findViewById(R.id.coordinator_layout);

final Snackbar snackbar = showSnackbar(coordinatorLayout, Snackbar.LENGTH_LONG);
            snackbar.show();
            View view = snackbar.getView();
            TextView tv = (TextView) view.findViewById(R.id.snackbar_action);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    snackbar.dismiss();
                }
            });


问:
Telnet is not recognized command when cmd.exe is started from Process.Start in C#
I have already switch on the telnet option on control panel - program/features.
Though telnet worked fine manually, but when I run below from my C# library, I am getting this error :

"'telnet' is not recognized as an internal or external command,
  operable program or batch file."

This is the code I use to start Telnet:

```<code>Process.Start("cmd", "/k telnet")
</code>```

What makes the difference between this and running it from the command prompt manually and how do I overcome this difference?

答:
Telnet is a program, always installed in the system folder. Which also means, it's always in the path. You don't need to start cmd.exe in order to start telnet.exe. Just use

```<code>Process.Start("telnet.exe");
</code>```

Use the arguments parameter to pass arguments to telnet itself, eg the host, log file etc:

```<code>Process.Start("telnet.exe","localhost 80 -f mylog.txt");
</code>```

There other, probably better options.

Use a Telnet Library

You can use a Telnet library and connect to a server directly, eg using the Telnet NuGet package :

```<code>using (Client client = new Client("localhost",80, new System.Threading.CancellationToken()))
{
    await client.WriteLine("abcd");
    string response = await client.ReadAsync();
    Console.WriteLine(response);
}
</code>```

Use PowerShell

Telnet is often used to test connectivity to a web server, not to actually send commands. In this case, you could use PowerShell's Test-NetConnection to receive diagnostics about the connection:

```<code>using System.Management.Automation;

var ps = PowerShell.Create()
                    .AddCommand("test-netconnection")
                    .AddArgument("localhost")
                    .AddParameter("CommonTCPPort", "HTTP");
var results = cmd.Invoke();
foreach (dynamic result in results)
{
    Console.WriteLine($"{result.TcpTestSucceeded} {result.SourceAddress}");
}
</code>```

Make sure you add the correct Powershell NuGet package, Microsoft.PowerShell.5.ReferenceAssemblies, not the unsupported and abandoned System.Management.Automation package

The advantage of PowerShell is that you can chain commands and scripts together just by adding more AddComand, AddScript calls. Each command will receive the output of the previous one. You could use Import-CSV to read a list of servers and ports from a file and pipe the output to Test-NetConnection

Body:
I have already switch on the telnet option on control panel - program/features.
Though telnet worked fine manually, but when I run below from my C# library, I am getting this error :

"'telnet' is not recognized as an internal or external command,
  operable program or batch file."

This is the code I use to start Telnet:

Process.Start("cmd", "/k telnet")

What makes the difference between this and running it from the command prompt manually and how do I overcome this difference?

Body:
Telnet is a program, always installed in the system folder. Which also means, it's always in the path. You don't need to start cmd.exe in order to start telnet.exe. Just use

Process.Start("telnet.exe");

Use the arguments parameter to pass arguments to telnet itself, eg the host, log file etc:

Process.Start("telnet.exe","localhost 80 -f mylog.txt");

There other, probably better options.

Use a Telnet Library

You can use a Telnet library and connect to a server directly, eg using the Telnet NuGet package :

using (Client client = new Client("localhost",80, new System.Threading.CancellationToken()))
{
    await client.WriteLine("abcd");
    string response = await client.ReadAsync();
    Console.WriteLine(response);
}

Use PowerShell

Telnet is often used to test connectivity to a web server, not to actually send commands. In this case, you could use PowerShell's Test-NetConnection to receive diagnostics about the connection:

using System.Management.Automation;

var ps = PowerShell.Create()
                    .AddCommand("test-netconnection")
                    .AddArgument("localhost")
                    .AddParameter("CommonTCPPort", "HTTP");
var results = cmd.Invoke();
foreach (dynamic result in results)
{
    Console.WriteLine($"{result.TcpTestSucceeded} {result.SourceAddress}");
}

Make sure you add the correct Powershell NuGet package, Microsoft.PowerShell.5.ReferenceAssemblies, not the unsupported and abandoned System.Management.Automation package

The advantage of PowerShell is that you can chain commands and scripts together just by adding more AddComand, AddScript calls. Each command will receive the output of the previous one. You could use Import-CSV to read a list of servers and ports from a file and pipe the output to Test-NetConnection


问:
Detect touch on UIView with Interface Builder
How can I detect touches in a UIviewController for a UIView with code only (without Interface Builder)?

I found the touchesBegan method but it doesn't get called ever. I didn't initialize anything else regarding this method.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
```

答:
```<code>#import "TouchView.h"

//TouchView.h

#import <Foundation/Foundation.h>
#import "TouchViewDelegate.h"

@interface TouchView : UIView {
    id <TouchViewDelegate>  delegate;
}
@property (retain) id delegate;
@end

//TouchView.m

@implementation TouchView
@synthesize delegate;

-(id) initWithFrame:(CGRect)frame
{
    self.userInteractionEnabled = YES;
    return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder
{
    self.userInteractionEnabled = YES;
    return self;
}
-(void) awakeFromNib
{
    self.userInteractionEnabled = YES;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [delegate touchDown:self];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [delegate touchUp:self];
}
@end

//TouchViewDelegate.h
#import <UIKit/UIKit.h>

@protocol TouchViewDelegate
-(void) touchDown:(id) sender;
-(void) touchUp:(id)sender;
@end
</code>```

ContentLicense: CC BY-SA 2.5


问:
Kodi script loading icon issue
I am just getting started with writing Kodi Python scripts (although I do have prior Python experience. I have taken the following code from the Kodi wiki to generate a list on screen:

```<code>import xbmc, xbmcgui

#get actioncodes from https://github.com/xbmc/xbmc/blob/master/xbmc/guilib/Key.h
ACTION_PREVIOUS_MENU = 10

class MyClass(xbmcgui.Window):
  def __init__(self):
    self.strActionInfo = xbmcgui.ControlLabel(250, 80, 200, 200, '', 'font14', '0xFFBBBBFF')
    self.addControl(self.strActionInfo)
    self.strActionInfo.setLabel('Push BACK to quit')
    self.list = xbmcgui.ControlList(500, 150, 300, 400)
    self.addControl(self.list)
    self.list.addItem('Item 1')
    self.list.addItem('Item 2')
    self.list.addItem('Item 3')
    self.setFocus(self.list)

  def onAction(self, action):
    if action == ACTION_PREVIOUS_MENU:
      self.close()

  def onControl(self, control):
    if control == self.list:
      item = self.list.getSelectedItem()
      self.message('You selected : ' + item.getLabel())
      self.close()

  def message(self, message):
    dialog = xbmcgui.Dialog()
    dialog.ok(" My message title", message)

mydisplay = MyClass()
mydisplay.doModal()
del mydisplay
</code>```

If you run this script the 'loading' icon with the rotating circles (v.17) persists on the screen until you click either ESC or the right mouse button. I've tried playing around with the code, but I am not sure what I need to amend so that the script loads the list up and the loading icon disappears on it's own.

Any ideas?

EDIT:

```<code>Addon.xml as requested...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="script.video.testaddon" name="testaddon" version="1.0.9" provider-name="Avigdor">
  <requires>
    <import addon="xbmc.python" version="2.1.0"/>
    <import addon="repository.xbmc-israel" />
  </requires>
  <extension point="xbmc.python.pluginsource" library="default.py">
        <provides>video</provides>
  </extension>
  <extension point="xbmc.addon.metadata">
    <summary lang="en">Playlist Loader - downloaded for free from:
http://www.hometheater.co.il</summary>
    <description lang="en">Playlist Loader - downloaded for free from:
http://www.hometheater.co.il</description>
    <platform>all</platform>
  </extension>
</addon>
</code>```

答:
That's what I thought. You are using a wrong addon type. xbmc.python.pluginsource or simply a plugin is meant for media content listings created with xbmcplugin module, while you aren't creating any plugin listing.
If you aren't calling xbmcplugin module, use xbmc.python.script or other appropriate addon type. More info: http://kodi.wiki/view/Addon.xml#.3Cextension.3E

Title: Kodi script loading icon issue

Body:
I am just getting started with writing Kodi Python scripts (although I do have prior Python experience. I have taken the following code from the Kodi wiki to generate a list on screen:

import xbmc, xbmcgui

#get actioncodes from https://github.com/xbmc/xbmc/blob/master/xbmc/guilib/Key.h
ACTION_PREVIOUS_MENU = 10

class MyClass(xbmcgui.Window):
  def __init__(self):
    self.strActionInfo = xbmcgui.ControlLabel(250, 80, 200, 200, '', 'font14', '0xFFBBBBFF')
    self.addControl(self.strActionInfo)
    self.strActionInfo.setLabel('Push BACK to quit')
    self.list = xbmcgui.ControlList(500, 150, 300, 400)
    self.addControl(self.list)
    self.list.addItem('Item 1')
    self.list.addItem('Item 2')
    self.list.addItem('Item 3')
    self.setFocus(self.list)

  def onAction(self, action):
    if action == ACTION_PREVIOUS_MENU:
      self.close()

  def onControl(self, control):
    if control == self.list:
      item = self.list.getSelectedItem()
      self.message('You selected : ' + item.getLabel())
      self.close()

  def message(self, message):
    dialog = xbmcgui.Dialog()
    dialog.ok(" My message title", message)

mydisplay = MyClass()
mydisplay.doModal()
del mydisplay

If you run this script the 'loading' icon with the rotating circles (v.17) persists on the screen until you click either ESC or the right mouse button. I've tried playing around with the code, but I am not sure what I need to amend so that the script loads the list up and the loading icon disappears on it's own.

Any ideas?

EDIT:

Addon.xml as requested...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="script.video.testaddon" name="testaddon" version="1.0.9" provider-name="Avigdor">
  <requires>
    <import addon="xbmc.python" version="2.1.0"/>
    <import addon="repository.xbmc-israel" />
  </requires>
  <extension point="xbmc.python.pluginsource" library="default.py">
        <provides>video</provides>
  </extension>
  <extension point="xbmc.addon.metadata">
    Playlist Loader - downloaded for free from:
http://www.hometheater.co.il
    <description lang="en">Playlist Loader - downloaded for free from:
http://www.hometheater.co.il</description>
    <platform>all</platform>
  </extension>
</addon>


问:
Gitlab private repository via composer
Today I have created private repository in gitlab and want to install it via composer in my laravel project, but  when I run composer update I am getting the following error

Your configuration does not allow connections to ...........

Here is a  part of my composer.json

```<code>"repositories": [{
        "type": "package",
        "package": {
            "name": "abc/def",
            "version": "dev-master",
            "type": "package",
            "source": {
                "url": "http://gitlab.abc.pro/abc/def",
                "type": "git",
                "reference": "master"
            },
        }
    } ],
"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "abc/def" : "dev-master",
    },
</code>```

答: For easy using gitlab repository I have used packagist service, so you need to go to settings of your gitlab repository and set oAuth token which have been taken from packagist. For using private repositories you need to get public and private keys and set it in gitlab repo. </p>

Title: Gitlab private repository via composer

Body:
Today I have created private repository in gitlab and want to install it via composer in my laravel project, but  when I run composer update I am getting the following error

Your configuration does not allow connections to ...........

Here is a  part of my composer.json

"repositories": [{
        "type": "package",
        "package": {
            "name": "abc/def",
            "version": "dev-master",
            "type": "package",
            "source": {
                "url": "http://gitlab.abc.pro/abc/def",
                "type": "git",
                "reference": "master"
            },
        }
    } ],
"require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "abc/def" : "dev-master",
    },


问:
Why can't have I a pure virtual assignment operator?
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

```<code>class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}
</code>```

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

```<code>virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}
</code>```

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?

答:
The compiler generates an implicit copy-assignment operator that is being selected when you do a B = B assignment.   That is not selected when you do a B = C assignment.

http://en.cppreference.com/w/cpp/language/copy_assignment

https://wandbox.org/permlink/CM5tQU656rnwtrKl

If you look at your error message:

```<code>/tmp/cctHhd0D.o: In function `B::operator=(B const&)':
prog.cc:(.text._ZN1BaSERKS_[_ZN1BaSERKS_]+0x1f): undefined reference to `A::operator=(A const&)'
collect2: error: ld returned 1 exit status
</code>```

You can see that the linker error is from inside B::operator=(B const&), which, since you didn't define one, means it must be auto-generated.

Body:
I'm a bit lost in C++ operators. I'd like to enforce the assignment operator for two different classes, i.e. so one can assign one to each other:

class A {
public:
    virtual A &operator =(const A &a) = 0;
};

class B : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "B" << std::endl;
        return *this;
    }
};

class C : public A {
public:
    virtual A &operator =(const A &a) override {
        std::cout << "C" << std::endl;
        return *this;
    }
};

int main(int argc, char *argv[])
{
    B b;
    C c;
    b = c;

    // leads to a linker error: undefined reference to `A::operator=(A const&)'
    //B b2;
    //b = b2;
}

The first assignment seems to do the job, "B" is called. Similarly, for "c = b", "C" is called. However when I uncomment the second part, I get the linker error. If I define A's operator like:

virtual A &operator =(const A &a) {
        std::cout << "A" << std::endl;
        return *this;
}

I get "B", "A". Huh? Can somebody explain why "A" is needed when two B's are assigned but not when B <- C is?

Body:
The compiler generates an implicit copy-assignment operator that is being selected when you do a B = B assignment.   That is not selected when you do a B = C assignment.

http://en.cppreference.com/w/cpp/language/copy_assignment

https://wandbox.org/permlink/CM5tQU656rnwtrKl

If you look at your error message:

/tmp/cctHhd0D.o: In function `B::operator=(B const&)':
prog.cc:(.text._ZN1BaSERKS_[_ZN1BaSERKS_]+0x1f): undefined reference to `A::operator=(A const&)'
collect2: error: ld returned 1 exit status

You can see that the linker error is from inside B::operator=(B const&), which, since you didn't define one, means it must be auto-generated.


问:
Internal Server Error (Heroku Console)
Good day guys i'm having a problem about the cookie session im making. I want to get rid of the error

connect.session() memorystore is not designed for a production environment

so i've red a forum that says it's normal and if i want to get rid of the error then use a connect-redis and yeah it works but the problem is it gives me an error when opening my app(not in the console);

Internal Server Error

and on my console its returning the

```<code>return next(new Error('Oh no')) //handle error
</code>```

Here is my code so far:

app.set('trust proxy', 1);

```<code>app.use(session({
cookie:{
    secure: true,
    maxAge:60000
       },
store: new RedisStore({host:'https://pektos6.herokuapp.com', port: port}),
secret: 'secret',
saveUninitialized: true,
resave: false
}));

app.use(function(req,res,next){
if(!req.session){
    return next(new Error('Oh no')) //handle error
}
next() //otherwise continue
});
</code>```

答:
What i did here is

```<code>var session = require('cookie-session');
//instead of
//var session = require('express-session');

app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: false
    cookie:{secure:true}
}));
</code>```

and the memory leak is gone

Title: Internal Server Error (Heroku Console)

Body:
Good day guys i'm having a problem about the cookie session im making. I want to get rid of the error

connect.session() memorystore is not designed for a production environment

so i've red a forum that says it's normal and if i want to get rid of the error then use a connect-redis and yeah it works but the problem is it gives me an error when opening my app(not in the console);

Internal Server Error

and on my console its returning the

return next(new Error('Oh no')) //handle error

Here is my code so far:

app.set('trust proxy', 1);

app.use(session({
cookie:{
    secure: true,
    maxAge:60000
       },
store: new RedisStore({host:'https://pektos6.herokuapp.com', port: port}),
secret: 'secret',
saveUninitialized: true,
resave: false
}));

app.use(function(req,res,next){
if(!req.session){
    return next(new Error('Oh no')) //handle error
}
next() //otherwise continue
});

Body:
What i did here is

var session = require('cookie-session');
//instead of
//var session = require('express-session');

app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: false
    cookie:{secure:true}
}));

and the memory leak is gone


问:
Arangov2.8 - Examples of register user functions in AQL
I need to filter some nodes by regex but since Arango v2.8 does not have this functionality I want to try registering user functions can anyone give me an example of how to register a simple function and use it in AQL?

I'm trying:

```<code>var myfunc = function (ideation_node) {
  for (var i = 0; i < ideation_node.length; ++i) {

    if (true) {
      return ideation_node[i];
    }
  }
  return null;
}

RETURN myfunctions::myfunc()
</code>```

答:
You use triagens/ArangoDb/AqlUserFunction to register a user function.

```<code>    $funcHandler = new \triagens\ArangoDb\AqlUserFunction($arangoConnection);
    $funcHandler->name = 'myfunctions::myFunc';
    $funcHandler->code = 'function(ideation_node){...}';
    $funcHandler->register();
</code>```

In AQL-Statements registered functions are used like any other function, using the fully-qualified (i.e. with namespace-prefix) name of the function.

Make sure that the function is side-effect free and don't manipulate input-parameters, but use return-values to pass the calculation results to the outside world.

Body:
I need to filter some nodes by regex but since Arango v2.8 does not have this functionality I want to try registering user functions can anyone give me an example of how to register a simple function and use it in AQL?

I'm trying:

var myfunc = function (ideation_node) {
  for (var i = 0; i < ideation_node.length; ++i) {

    if (true) {
      return ideation_node[i];
    }
  }
  return null;
}

RETURN myfunctions::myfunc()

Body:
You use triagens/ArangoDb/AqlUserFunction to register a user function.

    $funcHandler = new \triagens\ArangoDb\AqlUserFunction($arangoConnection);
    $funcHandler->name = 'myfunctions::myFunc';
    $funcHandler->code = 'function(ideation_node){...}';
    $funcHandler->register();

In AQL-Statements registered functions are used like any other function, using the fully-qualified (i.e. with namespace-prefix) name of the function.

Make sure that the function is side-effect free and don't manipulate input-parameters, but use return-values to pass the calculation results to the outside world.


问:
Android Service Stops When App Is Closed
I am starting a service from my main Android activity as follows:

```<code>final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);
</code>```

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?

答:
Best solution is to use the sync Adapter in android to start the service. Create a Sync Adapter and call start service their.. inside onPerformSync method.  to create sync Account please refer this link https://developer.android.com/training/sync-adapters/index.html

Why SyncAdapter? Ans: Because earlier you used to start the service using your App context. so whenever your app process get killed (When u remove it from task manager or OS kill it because of lack of resources ) at that time your service will also be removed. SyncAdapter will not work in application thread.. so if u call inside it.. service will no longer be removed.. unless u write code to remove it.

Body:
I am starting a service from my main Android activity as follows:

final Context context = base.getApplicationContext();
final Intent intent = new Intent(context, MyService.class);
startService(intent);

When I close the activity page by swiping it out from the recent apps list, the service stops running and restarts after some time. I can't use persistent services with notifications because of my app requirements. How can I make the service NOT restart or shutdown and just keep on running on app exit?


答:
You should not need to call ngOnInit again. So the question remains, what are you really trying to accomplish? Are you having issues retrieving the routing parameter?

```<code> ngOnInit(): void {
      this.route.params.subscribe((params: Params) => {
        this.model=this.userData;
  });
</code>```

Your code within the subscribe above will AUTOMATICALLY be re-executed every time the route parameters change. So there is no need to manually call ngOnInit again.

Title: How to call ngOnInit() again in Angular 2?

Body:
Please explain in this code, how to call ngOnInit() again when I call another method?

ngOnInit(): void {
  this.route.params.subscribe((params: Params) => {
    this.model = this.userData;
  });
}

update() {
  this.loading = true;
  this.userService.update(this.model).subscribe(
    (data) => {
      alert('Update successful');
    },
    (error) => {
      alert('Not updated');
      this.loading = false;
    },
  );
  this.user_data();
}

Body:
You should not need to call ngOnInit again. So the question remains, what are you really trying to accomplish? Are you having issues retrieving the routing parameter?

 ngOnInit(): void {
      this.route.params.subscribe((params: Params) => {
        this.model=this.userData;
  });

Your code within the subscribe above will AUTOMATICALLY be re-executed every time the route parameters change. So there is no need to manually call ngOnInit again.


问:
scrapy text encoding
Here is my spider

```<code>from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from vrisko.items import VriskoItem

class vriskoSpider(CrawlSpider):
    name = 'vrisko'
    allowed_domains = ['vrisko.gr']
    start_urls = ['http://www.vrisko.gr/search/%CE%B3%CE%B9%CE%B1%CF%84%CF%81%CE%BF%CF%82/%CE%BA%CE%BF%CF%81%CE%B4%CE%B5%CE%BB%CE%B9%CE%BF']
    rules = (Rule(SgmlLinkExtractor(allow=('\?page=\d')),'parse_start_url',follow=True),)

    def parse_start_url(self, response):
        hxs = HtmlXPathSelector(response)
        vriskoit = VriskoItem()
        vriskoit['eponimia'] = hxs.select("//a[@itemprop='name']/text()").extract()
        vriskoit['address'] = hxs.select("//div[@class='results_address_class']/text()").extract()
        return vriskoit
</code>```

My problem is that the returned strings are unicode and i want to encode them to utf-8. I dont know which is the best way to do this. I tried several ways without result.

Thank you in advance!

答:
Try adding the following line to the config file for Scrapy (i.e. settings.py):

```<code>FEED_EXPORT_ENCODING = 'utf-8'
</code>```

Title: scrapy text encoding

Body:
Here is my spider

from scrapy.contrib.spiders import CrawlSpider,Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from vrisko.items import VriskoItem

class vriskoSpider(CrawlSpider):
    name = 'vrisko'
    allowed_domains = ['vrisko.gr']
    start_urls = ['http://www.vrisko.gr/search/%CE%B3%CE%B9%CE%B1%CF%84%CF%81%CE%BF%CF%82/%CE%BA%CE%BF%CF%81%CE%B4%CE%B5%CE%BB%CE%B9%CE%BF']
    rules = (Rule(SgmlLinkExtractor(allow=('\?page=\d')),'parse_start_url',follow=True),)

    def parse_start_url(self, response):
        hxs = HtmlXPathSelector(response)
        vriskoit = VriskoItem()
        vriskoit['eponimia'] = hxs.select("//a[@itemprop='name']/text()").extract()
        vriskoit['address'] = hxs.select("//div[@class='results_address_class']/text()").extract()
        return vriskoit

My problem is that the returned strings are unicode and i want to encode them to utf-8. I dont know which is the best way to do this. I tried several ways without result.

Thank you in advance!

Body:
Try adding the following line to the config file for Scrapy (i.e. settings.py):

FEED_EXPORT_ENCODING = 'utf-8'


问:
webpack DefinePlugin use external config.js
I am new in webpack
I have this code in webpack.config.js

```<code>var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
var myconfig = require('./webpack.myconfig.js');

// bundle dependencies in separate vendor bundle
var dependencies = Object.keys(pkg.dependencies).filter(function (el) {
  //exclude font packages from vendor bundle & css-toggle-switch
  if (el.indexOf('font') !== -1 || el.indexOf('css-toggle-switch') !== -1) {
    return false;
  }
  else return true;
});

module.exports = {
  entry: {
      libs: dependencies,
      main: './src/index'
  },
  output: {
    path: path.join(__dirname, myconfig.buildPath),
    publicPath: myconfig.uiURL,
    filename: 'dist/js/[name].js',
    chunkFilename: '[id].[name].js'
  },
  plugins: [
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],
};
</code>```

and this is myconfig.js

```<code>myconfig = {
  uiURL: 'http://example.com/',
  apiUrl: 'http://api.example.com/api/'
};

module.exports = myconfig;
</code>```

and if I run this syntax

```<code>webpack -p --config webpack.config.js --progress --colors
</code>```

I will get the result like

```<code>/dist/js/libs.js
/dist/js/main.js
</code>```

but I want the result not like this, I want the result to be:

```<code>/dist/js/myconfig.js
/dist/js/libs.js
/dist/js/main.js
</code>```

What really I want is,
I want in main.js file, it will use myconfig.apiUrl as depedencies,
so when I deployed to production or qserver, I just change myconfig.js.

Thank you

答:
If you just want to get myconfig.js in /dist/js/, you can use CopyWebpackPlugin. It can copy static files from one path to another.

Add a new new line plugins section like :

```<code> plugins: [
     new CopyWebpackPlugin([{ from: APP_DIR + '\\images', to: APP_DIR + '\\build\\images' }]),
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],
</code>```

Here CopyWebpackPlugin copies file from one path to another.

Make sure you var CopyWebpackPlugin = require('copy-webpack-plugin');at top of webpack.config.js & added same in package.json & installed via npm.

Body:
I am new in webpack
I have this code in webpack.config.js

var path = require('path');
var webpack = require('webpack');
var pkg = require('./package.json');
var myconfig = require('./webpack.myconfig.js');

// bundle dependencies in separate vendor bundle
var dependencies = Object.keys(pkg.dependencies).filter(function (el) {
  //exclude font packages from vendor bundle & css-toggle-switch
  if (el.indexOf('font') !== -1 || el.indexOf('css-toggle-switch') !== -1) {
    return false;
  }
  else return true;
});

module.exports = {
  entry: {
      libs: dependencies,
      main: './src/index'
  },
  output: {
    path: path.join(__dirname, myconfig.buildPath),
    publicPath: myconfig.uiURL,
    filename: 'dist/js/[name].js',
    chunkFilename: '[id].[name].js'
  },
  plugins: [
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],
};

and this is myconfig.js

myconfig = {
  uiURL: 'http://example.com/',
  apiUrl: 'http://api.example.com/api/'
};

module.exports = myconfig;

and if I run this syntax

webpack -p --config webpack.config.js --progress --colors

I will get the result like

/dist/js/libs.js
/dist/js/main.js

but I want the result not like this, I want the result to be:

/dist/js/myconfig.js
/dist/js/libs.js
/dist/js/main.js

What really I want is,
I want in main.js file, it will use myconfig.apiUrl as depedencies,
so when I deployed to production or qserver, I just change myconfig.js.

Thank you

Body:
If you just want to get myconfig.js in /dist/js/, you can use CopyWebpackPlugin. It can copy static files from one path to another.

Add a new new line plugins section like :

 plugins: [
     new CopyWebpackPlugin([{ from: APP_DIR + '\\images', to: APP_DIR + '\\build\\images' }]),
    new webpack.DefinePlugin({
      DEBUG_MODE: JSON.stringify(false),
      TIMEOUT: JSON.stringify(30000),
      API_URL: JSON.stringify(myconfig.apiUrl),
      "process.env": {
        NODE_ENV: JSON.stringify("production")
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'libs',
      filename: 'dist/js/libs.js',
      minChunks: Infinity
    })
  ],

Here CopyWebpackPlugin copies file from one path to another.

Make sure you var CopyWebpackPlugin = require('copy-webpack-plugin');at top of webpack.config.js & added same in package.json & installed via npm.


问:
sas do until and do while distance reaches 250 miles
In the following program, complete the statement so that the program stops generating observations when Distance reaches 250 miles or when 10 gallons of fuel have been used.

```<code>Data work.go259;
    set perm.cars;
    do gallons = 1 to 10 .....;
    Distance= gallons*mpg;
    output;
    end;
run;
</code>```

The correct answer is "do gallons = 1 to 10 while (distance <250)"
but I am wondering why "do gallons=1 to 10 until (distance =250) is incorrect? I assumed the do loop will stop when distance=250, therefore the program will stop generating observations when distance reaches 250.

答:
As far as understood, you wish to break a loop conditionally. Two easy ways are leave and goto (talk about blast from past.^^)  Here are two examples that do just that. There is command Continue as well, but haven't tested that out yet.</p>

```<code>Data test_goto;
    do gallons = 1 to 10;
    Distance= gallons*75;
    output;
        if distance >=250 then goto hop_Out;
    end;
    hop_Out:
run;

Data test_leave;
    do gallons = 1 to 10;
    Distance= gallons*75;
    output;
        if distance >=250 then leave;
    end;
run;
</code>```

Body:
In the following program, complete the statement so that the program stops generating observations when Distance reaches 250 miles or when 10 gallons of fuel have been used.

Data work.go259;
    set perm.cars;
    do gallons = 1 to 10 .....;
    Distance= gallons*mpg;
    output;
    end;
run;

The correct answer is "do gallons = 1 to 10 while (distance <250)"
but I am wondering why "do gallons=1 to 10 until (distance =250) is incorrect? I assumed the do loop will stop when distance=250, therefore the program will stop generating observations when distance reaches 250.

Body:
As far as understood, you wish to break a loop conditionally. Two easy ways are leave and goto (talk about blast from past.^^)  Here are two examples that do just that. There is command Continue as well, but haven't tested that out yet.

Data test_goto;
    do gallons = 1 to 10;
    Distance= gallons*75;
    output;
        if distance >=250 then goto hop_Out;
    end;
    hop_Out:
run;

Data test_leave;
    do gallons = 1 to 10;
    Distance= gallons*75;
    output;
        if distance >=250 then leave;
    end;
run;


答:
It's just a function ... </p>

```<code>ngOnInit() {}

secondMethod() { this.ngOnInit(); }
</code>```

<p>I've been doing it all the time to reload my data, never had a problem with it. </p>

Body:
It's just a function ...

ngOnInit() {}

secondMethod() { this.ngOnInit(); }

I've been doing it all the time to reload my data, never had a problem with it.


问:
SonarQube Scanner stuck during AST scan on one java file
Sonar Scanner is not able to finish scanning. I checked the logs and I saw that scan stuck on one file as below

INFO: 977/6093 files analyzed, current file: C:\Projects\ABC\src\main\java.com.cmp.rpt.Report.java

The scanner keep printing this message and the scan never finishes.
This is a recent issue. I checked the history of that file and nothing has changed on that file. I recently updated the Java plugin in Sonar.
My server configuration is as below

SonarQube Scanner 2.8 (Tried 2.9 as well with no success)

SonarQube java plugin version 4.6.0.8784

SonarQube server 5.6.5

Could anyone shed some light on this issue

UPDATE: I reverted the SonarQube java plugin back to 3.13.1 and Scanner was able to continue. So the problem is in the new java plugin 4.6.0.8784

答:
I had the same problem.
When I updated to sonar-java-plugin-4.11 version
 and sonar-scanner.3.0 version,
the issue was fixed. </p>


问:
SSIS Derived Column condition to replace null values based on a specific date
I am working on a SSIS Package that will populate a SharePoint 2013 list with data from other SP lists.

I have created a Derived Column in the package, which is intended to replace null based on dates that are greater than or equal to a specific date in the data list. However, I am having trouble with the expression. Below is a condition and expression example that I am have trouble with.

```<code>REPLACENULL(ColumnName,"mm/dd/yyyy" > = GETDATE())
</code>```

Any assistance to point out what I am doing wrong is appreciated.

答:
Syntax for REPLACENULL is REPLACENULL(expression 1,expression 2) where

expression 1 :
The result of this expression is checked against NULL.

expression 2 :
The result of this expression is returned if the first expression evaluates to NULL.

If you're trying to REPLACE NULL values of a column based on another column's datetime condition, try something like this :

```<code>[column_1] >= GETDATE() ? REPLACENULL([column_2],"desired value") : [column_2]
</code>```

Body:
I am working on a SSIS Package that will populate a SharePoint 2013 list with data from other SP lists.

I have created a Derived Column in the package, which is intended to replace null based on dates that are greater than or equal to a specific date in the data list. However, I am having trouble with the expression. Below is a condition and expression example that I am have trouble with.

REPLACENULL(ColumnName,"mm/dd/yyyy" > = GETDATE())

Any assistance to point out what I am doing wrong is appreciated.

Body:
Syntax for REPLACENULL is REPLACENULL(expression 1,expression 2) where

expression 1 :
The result of this expression is checked against NULL.

expression 2 :
The result of this expression is returned if the first expression evaluates to NULL.

If you're trying to REPLACE NULL values of a column based on another column's datetime condition, try something like this :

[column_1] >= GETDATE() ? REPLACENULL([column_2],"desired value") : [column_2]


问:
String mismatch index
I have two strings and I want to get the index where the mismatch happens:

```<code>str = "abcdef"
str2 = "abddef"

Output: 2
</code>```

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

答:
```<code>    String str = "hello";
    String str2 = "helll";
    int indexDif = -1;
    for(int i=0; i<str.length(); i++)
        if(str.charAt(i) != str2.charAt(i))
        {
            indexDif = i;
            break;
        }
</code>```

assuming that both of the strings are of same length

Title: String mismatch index

Body:
I have two strings and I want to get the index where the mismatch happens:

str = "abcdef"
str2 = "abddef"

Output: 2

So can anyone tell me is there an inbuilt function in java to get the index? If not can someone give me a hint to do so? Thank You!

Body:
    String str = "hello";
    String str2 = "helll";
    int indexDif = -1;
    for(int i=0; i<str.length(); i++)
        if(str.charAt(i) != str2.charAt(i))
        {
            indexDif = i;
            break;
        }

assuming that both of the strings are of same length


问:
Collapsing toolbar layout with NestedScrollView doesnt scroll smoothly
I have a NestedScrollView with CollapsingToolbarLayout and I would like to make it work smoothly.

My problem is when scrolling up from content, my Collapsing Toolbar doesn't auto expand but is blocked when it hits top. Then i need to scroll up again in order to expand toolbar.

I would like to achieve smooth scrolling up from content that would auto expand my CollapsingToolbarLayout

Here is my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/product_detail_main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:apptools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="true"
            android:foregroundGravity="bottom|right"
            android:foregroundTintMode="add"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       /*
           CONTENT
       */

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

I found some similar questions but none of the answers worked for me.

答:
I have solved that problem by SmoothAppBarLayout

Link: https://github.com/henrytao-me/smooth-app-bar-layout

Add this dependency in your app level build.gradle

```<code>compile "me.henrytao:smooth-app-bar-layout:25.3.1.0"
</code>```

Mark that child of NestedScrollView should have clickable and focusable true.

This is XML Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable .../>
</data>

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayoutPlaceDetail"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/adViewPlaceDetail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <me.henrytao.smoothappbarlayout.SmoothAppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <!--app:layout_scrollInterpolator="@android:anim/accelerate_decelerate_interpolator"-->

                <ImageView
                    android:id="@+id/imgOfPlace"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:scaleType="fitXY"
                    android:src="@drawable/placeholder"
                    app:layout_collapseMode="parallax" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|enterAlways" />

            </android.support.design.widget.CollapsingToolbarLayout>

        </me.henrytao.smoothappbarlayout.SmoothAppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/nestedScrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:overScrollMode="never"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintLayoutInNestedScroll"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:focusable="true"
                android:focusableInTouchMode="true">

                <YOUR CONTENT VIEWS>

            </android.support.constraint.ConstraintLayout>

        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewPlaceDetail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="..."
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I have a NestedScrollView with CollapsingToolbarLayout and I would like to make it work smoothly.

My problem is when scrolling up from content, my Collapsing Toolbar doesn't auto expand but is blocked when it hits top. Then i need to scroll up again in order to expand toolbar.

I would like to achieve smooth scrolling up from content that would auto expand my CollapsingToolbarLayout

Here is my code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    android:id="@+id/product_detail_main_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:apptools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="true"
            android:foregroundGravity="bottom|right"
            android:foregroundTintMode="add"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:fitsSystemWindows="true"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

       /*
           CONTENT
       */

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

I found some similar questions but none of the answers worked for me.

Body:
I have solved that problem by SmoothAppBarLayout

Link: https://github.com/henrytao-me/smooth-app-bar-layout

Add this dependency in your app level build.gradle

compile "me.henrytao:smooth-app-bar-layout:25.3.1.0"

Mark that child of NestedScrollView should have clickable and focusable true.

This is XML Layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable .../>
</data>

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/coordinatorLayoutPlaceDetail"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/adViewPlaceDetail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <me.henrytao.smoothappbarlayout.SmoothAppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:contentScrim="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <!--app:layout_scrollInterpolator="@android:anim/accelerate_decelerate_interpolator"-->

                <ImageView
                    android:id="@+id/imgOfPlace"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:scaleType="fitXY"
                    android:src="@drawable/placeholder"
                    app:layout_collapseMode="parallax" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|enterAlways" />

            </android.support.design.widget.CollapsingToolbarLayout>

        </me.henrytao.smoothappbarlayout.SmoothAppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/nestedScrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:overScrollMode="never"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <android.support.constraint.ConstraintLayout
                android:id="@+id/constraintLayoutInNestedScroll"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clickable="true"
                android:focusable="true"
                android:focusableInTouchMode="true">

                <YOUR CONTENT VIEWS>

            </android.support.constraint.ConstraintLayout>

        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

    <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adViewPlaceDetail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="..."
        ads:layout_constraintBottom_toBottomOf="parent"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答: I would try the built-in QuoteName function.</p>

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?


问:
showing structure view for python files using jedi-vim
Does jedi vim support anything like intellijs https://www.jetbrains.com/help/idea/structure-tool-window-file-structure-popup.html ? </p>

答:
This very simple command gives you an actionable outline of your document:

```<code>:g/def\|class/#
</code>```

You can map it if you don't want to type it all the time; and make it a bit cleaner in the same move:

```<code>augroup PythonStuff
    autocmd!
    autocmd FileType python nnoremap <buffer> <F12> :<C-u>g/\<def\>\\|\<class\>/#<CR>
augroup END
</code>```

Body:
This very simple command gives you an actionable outline of your document:

:g/def\|class/#

You can map it if you don't want to type it all the time; and make it a bit cleaner in the same move:

augroup PythonStuff
    autocmd!
    autocmd FileType python nnoremap <buffer> <F12> :<C-u>g/\<def\>\\|\<class\>/#<CR>
augroup END


问:
How to update an observable array inside a component from the main ViewModel?
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}</code>```

<!DOCTYPE html>

 -

```
  </body>
</html></code>```

答:
You could use this solution given by the user JotaBe: Refresh observableArray when items are not observables.

```<code>ko.observableArray.fn.refresh = function (item) {
    var index = this['indexOf'](item);
    if (index >= 0) {
        this.splice(index, 1);
        this.splice(index, 0, item);
    }
}
</code>```

Now, I need to change addItem() and add the call to refresh with the updated element:

```<code>self.items.addItem = function(location, type) {
    self.items.push({
        location: location,
        type: type
    });
    if (location == "A" && type == "Apples") {
        self.types()[0].available = false;
        self.types.refresh(self.types()[0]); // <--- New sentence
    }
};
</code>```

This will refresh the ```</code>, that has a list of <code>types</code>.  But will not refresh the component, that also has a list of <code>types</code>.</p>

<p>Then I used this link, <a href="https://knockoutjs.com/documentation/deferred-updates.html" rel="nofollow noreferrer">Forcing deferred notifications to happen early</a>, and I added <code>ko.tasks.runEarly()</code> in the <code>refresh</code>, and now it works ok, I think.</p>

```ko.observableArray.fn.refresh = function (item) {
    var index = this['indexOf'](item);
    if (index >= 0) {
        this.splice(index, 1);
        ko.tasks.runEarly(); // <--- New sentence
        this.splice(index, 0, item);
    }
}
```

Here it is a Codepen.

Body:
I need to set from the main viewmodel a property inside an observable array.

I'm using the classic pre to debug and display the content of my observable array.
By using types.valueHasMutated() I can see the applied changes - just only to vm.types (which wouldn't be the case otherwise).

However, I need to see this changes reflected inside my component.

In my example, when I ckick "Apples", the corresponding input shall be disabled like the one below. Sadly, this is actually not the case.

What I'm doing wrong?

ko.components.register("available-items", {
  viewModel: function(params) {
    function AvailableItems(params) {
      var self = this;
      self.params = params;
      self.location = "A";
      self.types = ko.computed(function() {
        var types = self.params.types();
        return ko.utils.arrayFilter(types, function(item) {
          return item.location == self.location;
        });
      });
      self.addItem = function(data, event) {
        self.params.items.addItem(self.location, data.type);
      };
    }
    return new AvailableItems(params);
  },
  template: '
' +
    '
Add item
' +
    '
' +
    '
' +
    '<input type="text" data-bind="value: type, enable:available, event: {click: $parent.addItem}" readonly/>' +
    '
' +
    '
' +
    '
',
  synchronous: true
});

var types = [{
  type: "Apples",
  location: "A",
  available: true
}, {
  type: "Bananas",
  location: "A",
  available: false
}];

function Vm(data) {
  var self = this;
  self.items = ko.observableArray();
  self.types = ko.observableArray(ko.utils.arrayMap(data, function(item) {
    return item;
  }));
  self.items.addItem = function(location, type) {
    self.items.push({
      location: location,
      type: type
    });
    if (location == "A" && type == "Apples") {
      self.types()[0].available = false;
      self.types.valueHasMutated();
    }
  };
}

ko.options.deferUpdates = true;
var vm = new Vm(types);
ko.applyBindings(vm);

pre {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}

<!DOCTYPE html>

 -

Body:
You could use this solution given by the user JotaBe: Refresh observableArray when items are not observables.

ko.observableArray.fn.refresh = function (item) {
    var index = this['indexOf'](item);
    if (index >= 0) {
        this.splice(index, 1);
        this.splice(index, 0, item);
    }
}

Now, I need to change addItem() and add the call to refresh with the updated element:

self.items.addItem = function(location, type) {
    self.items.push({
        location: location,
        type: type
    });
    if (location == "A" && type == "Apples") {
        self.types()[0].available = false;
        self.types.refresh(self.types()[0]); // <--- New sentence
    }
};

This will refresh the <pre>, that has a list of types.  But will not refresh the component, that also has a list of types.

Then I used this link, Forcing deferred notifications to happen early, and I added ko.tasks.runEarly() in the refresh, and now it works ok, I think.

ko.observableArray.fn.refresh = function (item) {
    var index = this['indexOf'](item);
    if (index >= 0) {
        this.splice(index, 1);
        ko.tasks.runEarly(); // <--- New sentence
        this.splice(index, 0, item);
    }
}

Here it is a Codepen.


问:
When or from Where should we add listener to body in Android WebView?
From where exactly should we try to add a listener to body (or any other tag) tag using JS in Android webview.

Because in onPageStarted() the element might not have been loaded and in onPageFinished() the element might have already completed loading.

答:
You know that onPageFinished() and onPageStarted() are android methodes and not JS methodes. If you want to use JS that only is excuted when your page is load you need to do something like this:</p>

```<code>var init = function () {
    DoSomeFunction();
};

$(document).ready(init());
</code>```

Body:
You know that onPageFinished() and onPageStarted() are android methodes and not JS methodes. If you want to use JS that only is excuted when your page is load you need to do something like this:

var init = function () {
    DoSomeFunction();
};

$(document).ready(init());


问:
Items not getting added in Arraylist
This is how i am trying to add "ids" from api to my arraylist

```<code>int id;

 private List<HashMap<String, Object>>
               getMovies(JSONArray jMovies) throws NullPointerException {

 int movieCount = jMovies.length();

 List<HashMap<String, Object>> movieList = new ArrayList<HashMap<String, Object>>();

 HashMap<String, Object> movie = null;

    //Taking each movie, parses and adds to list object
    for (int i = 0; i < movieCount; i++) {

        try {
            JSONObject getid=(JSONObject) jMovies.get(i);

            movie = getMovie(getid);
            movieList.add(movie);
            id =Integer.parseInt(getid.getString("id"));

        } catch (JSONException e) {

        }
        getNumberlist(i,id);
    }

    return movieList;
}

public ArrayList<Integer> ids=new ArrayList<Integer>();
public void getNumberlist(int i,int id)
{
    ids.add(i,id);

}

public List<Integer> getNumberslist()
{ return this.ids;
}
</code>```

and trying to get it on Itemclick listener as

```<code>MovieJSONParser mj = new MovieJSONParser();

public void onItemClick(AdapterView<?> l, View v, int position, long id) {

   Intent intent = new Intent(this,next.class);

   if(position==0) {
       int id1 = mj.getNumberslist().get(0);
       intent.putExtra("id",id1);
       startActivity(intent);
   }
    if(position==1) {
        int id1 = mj.getNumberslist().get(1);
        intent.putExtra("id",id1);
        startActivity(intent);
    }
    if(position==2) {
        int id1 = mj.getNumberslist().get(2);
        intent.putExtra("id",id1);
        startActivity(intent);
    }
    if(position==3) {
        int id1 = mj.getNumberslist().get(3);
        intent.putExtra("id",id1);
        startActivity(intent);
    }

    }
</code>```

答:
First of all, if you are catching Exception, at least print stack trace so that it will be easier to debug code.

While getting JSONObject using jMovies.get(i) , your api data is empty so you will get index out of bound exception.

```<code>     for (int i = 0; i < movieCount; i++) {

            try {
                JSONObject getid=(JSONObject) jMovies.get(i);

                movie = getMovie(getid);
                movieList.add(movie);
                id =Integer.parseInt(getid.getString("id"));

            } catch (JSONException e) {
              e.printStackTrace();
            }
            getNumberlist(i,id);
        }
</code>```

Check if you are getting data in jMovies.

Title: Items not getting added in Arraylist

Body:
This is how i am trying to add "ids" from api to my arraylist

int id;

 private List<HashMap<String, Object>>
               getMovies(JSONArray jMovies) throws NullPointerException {

 int movieCount = jMovies.length();

 List<HashMap<String, Object>> movieList = new ArrayList<HashMap<String, Object>>();

 HashMap<String, Object> movie = null;

    //Taking each movie, parses and adds to list object
    for (int i = 0; i < movieCount; i++) {

        try {
            JSONObject getid=(JSONObject) jMovies.get(i);

            movie = getMovie(getid);
            movieList.add(movie);
            id =Integer.parseInt(getid.getString("id"));

        } catch (JSONException e) {

        }
        getNumberlist(i,id);
    }

    return movieList;
}

public ArrayList<Integer> ids=new ArrayList<Integer>();
public void getNumberlist(int i,int id)
{
    ids.add(i,id);

}

public List<Integer> getNumberslist()
{ return this.ids;
}

and trying to get it on Itemclick listener as

MovieJSONParser mj = new MovieJSONParser();

public void onItemClick(AdapterView<?> l, View v, int position, long id) {

   Intent intent = new Intent(this,next.class);

   if(position==0) {
       int id1 = mj.getNumberslist().get(0);
       intent.putExtra("id",id1);
       startActivity(intent);
   }
    if(position==1) {
        int id1 = mj.getNumberslist().get(1);
        intent.putExtra("id",id1);
        startActivity(intent);
    }
    if(position==2) {
        int id1 = mj.getNumberslist().get(2);
        intent.putExtra("id",id1);
        startActivity(intent);
    }
    if(position==3) {
        int id1 = mj.getNumberslist().get(3);
        intent.putExtra("id",id1);
        startActivity(intent);
    }

    }

Body:
First of all, if you are catching Exception, at least print stack trace so that it will be easier to debug code.

While getting JSONObject using jMovies.get(i) , your api data is empty so you will get index out of bound exception.

     for (int i = 0; i < movieCount; i++) {

            try {
                JSONObject getid=(JSONObject) jMovies.get(i);

                movie = getMovie(getid);
                movieList.add(movie);
                id =Integer.parseInt(getid.getString("id"));

            } catch (JSONException e) {
              e.printStackTrace();
            }
            getNumberlist(i,id);
        }

Check if you are getting data in jMovies.


问:
Could not resolve hostname with composer and private repository on gitlab
When I want to use a private git repository with composer, I add the private repository like

```<code>{
    type: "git",
    url: [git@host:port]:directory/subdirectory/repo. git"
}
</code>```

On my Mac it's working fine, but on the server (Debian) I'm getting could not resolve hostname host:port]: when it's trying to do a git clone.

But the hostname ist reachable. It seems it doesn't like the syntax [git@host:port]:

I would use type: gitlab, but composer has problems with subdirectories in gitlab.

答:
the problem will be the port - you could try via http - if using standard ports is not an option

```<code>"url" : "http://user:password@host:port/directory/subdirectory/repo.git",
</code>```

i guess you have tested this notation as well:

```<code>"url" : "ssh://git@host:port/directory/subdirectory/repo.git",
</code>```

Body:
When I want to use a private git repository with composer, I add the private repository like

{
    type: "git",
    url: [git@host:port]:directory/subdirectory/repo. git"
}

On my Mac it's working fine, but on the server (Debian) I'm getting could not resolve hostname host:port]: when it's trying to do a git clone.

But the hostname ist reachable. It seems it doesn't like the syntax [git@host:port]:

I would use type: gitlab, but composer has problems with subdirectories in gitlab.

Body:
the problem will be the port - you could try via http - if using standard ports is not an option

"url" : "http://user:password@host:port/directory/subdirectory/repo.git",

i guess you have tested this notation as well:

"url" : "ssh://git@host:port/directory/subdirectory/repo.git",


问:
Locking multiple mutexes
I'm wondering if it's possible to lock multiple mutexes at the same time, like:

```<code> Mutex1.Lock();
 {
     Mutex2.Lock();
     {
          // Code locked by mutex 1 and 2.
     }
     Mutex2.Unlock();

     // Code locked by mutex 1.
 }
 Mutex1.Unlock();
</code>```

It would be very useful for some situations. Thanks.

答:
C++17 also provides scoped_lock for the specific purpose of locking multiple mutexes that prevents deadlock in a RAII style, similar to lock_guard.

```<code>#include<mutex>

std::mutex mtx1, mtx2;
void foo()
{
    std::scoped_lock lck{mtx1, mtx2};
    // proceed
}
</code>```

Title: Locking multiple mutexes

Body:
I'm wondering if it's possible to lock multiple mutexes at the same time, like:

 Mutex1.Lock();
 {
     Mutex2.Lock();
     {
          // Code locked by mutex 1 and 2.
     }
     Mutex2.Unlock();

     // Code locked by mutex 1.
 }
 Mutex1.Unlock();

It would be very useful for some situations. Thanks.

Body:
C++17 also provides scoped_lock for the specific purpose of locking multiple mutexes that prevents deadlock in a RAII style, similar to lock_guard.

#include<mutex>

std::mutex mtx1, mtx2;
void foo()
{
    std::scoped_lock lck{mtx1, mtx2};
    // proceed
}


问:
Drupal update.php white screening
Tried everything..

Permissions, error logs, re-cloning, etc.

Works fine on another workstation so can't be the application code.

Any ideas?

答:
Just to further expand on this.

Local setup of Drupal

All the front-end pages work

Can login as a user or admin successfully at the URL '/user'

Colleague has followed the exact same process and works fine for him

Cannot access any page that has URL '/admin/...'

Tried everything...

.htaccess file from fresh Drupal install

.htaccess file from working local copy on colleagues machine

.htaccess file from working other local Drupal build that works

Increased php.ini memory limit to 256m

WAMP server apache rewrite_module is turned on

etc...

Whats really strange is that I have other Drupal builds locally that work fine.

Title: Drupal update.php white screening


问:
Shortcode for specific blog post/posts in wordpress?
I am having a trouble finding a way to create a shortcode for specific blog posts in wordpress.

What I want to create is a way to display,

latest post

2nd to latest post

3rd to latest post

4th to latest post

I know there are ways to display blog posts by listing them up, But I want to display them individually, so that I can place them in different parts of the pre-made theme.

Is there anyway to make this possible?

Thank you for your time! :)

答:
```<code>function latest_blog_posts(){
ob_start(); ?>
//use wp_query where you can have parameters 'order'=>'desc'
or you can use wordpress neat function wp_get_recent_posts()
<?php
$contents=ob_get_contents();
ob_end_clean();
return $contents;
}

add_shortcode('latest_blog_posts','latest_blog_posts');
</code>```

and paste your code wherever you want to

```<code><?php echo do_shortcode('[latest_blog_posts]'); ?>
</code>```

or you can directly paste it on editor as well

Body:
function latest_blog_posts(){
ob_start(); ?>
//use wp_query where you can have parameters 'order'=>'desc'
or you can use wordpress neat function wp_get_recent_posts()
<?php
$contents=ob_get_contents();
ob_end_clean();
return $contents;
}

add_shortcode('latest_blog_posts','latest_blog_posts');

and paste your code wherever you want to

<?php echo do_shortcode('[latest_blog_posts]'); ?>

or you can directly paste it on editor as well


问:
Fetching first records of sets matching a where condition in Rails
I want to create a method for my Activity model that has many Practices called month_days_not_practiced which gives a count of the days in the current month that the Activity does not have any practices recorded for (note: days_in_month is a helper method):

```<code>  def month_days_not_practiced(date = Date.today)
    p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).count
    days_in_month - p
  end
</code>```

However, I want to return only one record per month day.

Can someone help me with my custom SQL (I think) please? I'm drawing a blank at the moment..

TIA!

Andy

答:
Although you can do this with a simple GROUP BY operation and get the records you want, you may find this is not especially efficient since this will require a server-side sort and cannot be indexed:

```<code>SELECT DATE(created_at) AS on_date, COUNT(id) AS count_for_date FROM practices GROUP BY DATE(created_at)
</code>```

This will return the number of entries indexed by day. There will be no zero entries since these will not be grouped, but as you've observed, you can always compute how many missing days there are based on how many there should be.

You can iterate over these results using the connection object:

```<code>Practice.connection.select_rows("...").each do |date, count|
  # ...
end
</code>```

A way to optimize this is to simply add an indexed date column in your schema:

```<code>add_column :practices, :created_on, :date

execute "UPDATE practices SET created_on=created_at"

add_index :practices, :created_on
</code>```

Be sure to assign to this field when saving your models:

```<code>class Practice < ActiveRecord::Base
  before_create :assign_created_on

protected
  def assign_created_on
    self.created_on = Date.today
  end
end
</code>```

This should make your query fully indexable and much faster.

Body:
I want to create a method for my Activity model that has many Practices called month_days_not_practiced which gives a count of the days in the current month that the Activity does not have any practices recorded for (note: days_in_month is a helper method):

  def month_days_not_practiced(date = Date.today)
    p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).count
    days_in_month - p
  end

However, I want to return only one record per month day.

Can someone help me with my custom SQL (I think) please? I'm drawing a blank at the moment..

TIA!

Andy

Body:
Although you can do this with a simple GROUP BY operation and get the records you want, you may find this is not especially efficient since this will require a server-side sort and cannot be indexed:

SELECT DATE(created_at) AS on_date, COUNT(id) AS count_for_date FROM practices GROUP BY DATE(created_at)

This will return the number of entries indexed by day. There will be no zero entries since these will not be grouped, but as you've observed, you can always compute how many missing days there are based on how many there should be.

You can iterate over these results using the connection object:

Practice.connection.select_rows("...").each do |date, count|
  # ...
end

A way to optimize this is to simply add an indexed date column in your schema:

add_column :practices, :created_on, :date

execute "UPDATE practices SET created_on=created_at"

add_index :practices, :created_on

Be sure to assign to this field when saving your models:

class Practice < ActiveRecord::Base
  before_create :assign_created_on

protected
  def assign_created_on
    self.created_on = Date.today
  end
end

This should make your query fully indexable and much faster.


问:
How will I know if celery background process is successful inside django code. If it is successful I want render a html page
I am not able to do because I don't have the status of the currently running background process in the django code.

Request:
  I need to know the status  of the celery background task and render the html     page from there

```<code>@task_success.connect
def task_sent_handler3(sender=None,result=None,**kwargs):
    # information about task are located in headers for task messages
    # using the task protocol version 2.
    #info = headers if 'task' in headers else body
    tester()
    #print('after_task_publish for task id {info[id]}'.format(info="hhhi",))
</code>```

I tried the above celery annotation but i did not return anything.
If it return also will i be able to access the local variables and return the render function

render(request,'page.html') from that success decoration function

How can I tackle this?

答:
when you run the task for every task there will be unique id for that. from that id you can track the status of the task. on front side you can just check the status of sending the ajax call for that id. when it gets complete you can display the whatever you want to display.

http://thoslin.github.io/async-download-with-celery/

Body:
I am not able to do because I don't have the status of the currently running background process in the django code.

Request:
  I need to know the status  of the celery background task and render the html     page from there

@task_success.connect
def task_sent_handler3(sender=None,result=None,**kwargs):
    # information about task are located in headers for task messages
    # using the task protocol version 2.
    #info = headers if 'task' in headers else body
    tester()
    #print('after_task_publish for task id {info[id]}'.format(info="hhhi",))

I tried the above celery annotation but i did not return anything.
If it return also will i be able to access the local variables and return the render function

render(request,'page.html') from that success decoration function

How can I tackle this?


问:
Local storage and ngrxstore
I have an angular2app. I stored my data into localstorage. Every time when the action getting chage local storage data will clear. How can i store this localstorage data into ngrxstore. I have the following:

component.ts

```<code>onClickRoom(room: string): void {
this.date = new Date();
this.evntList = new events('', '', '');
this.evntList.timestamp = this.date;
this.evntList.name = room;
this.evntList.type = this.type;
console.log("eventList:", this.evntList);
this.eventArray.push(this.evntList);
this.tokenmanager.store(this.eventArray);
console.log('Room clicked: ', this.eventArray); ---> This event array successfully updating.
}
</code>```

globalstorage.ts

```<code>@Injectable()
export class TokenManager {

public tokenKey: string = 'app_token';

constructor() { }

store(content) {

    localStorage.setItem(this.tokenKey, JSON.stringify(content));

}

retrieve() {
    let storedToken: any = localStorage.getItem(this.tokenKey);

    if (!storedToken) throw 'no token found';
    return storedToken;
}
}
</code>```

My view is:

abc

pqr    -----> This is a list.

qwe

While I'm clicking abc 3 things get stored into local storage like:

```<code>[{name: "abc", timestamp:time, type: "typename"}].
</code>```

then after i clik the array will get update into

```<code>[{name: "abc", timestamp:time, type: "typename"}, {name: "pqr", timestamp:time, type: "typename"}].
</code>```

But after refreshing the page and click the same item the previously stored data will lost and array is updated with new value. But actually what I need is a new appended array. Which means previously stored data and newly stored data. How can I  implement this?

How can i store this local storage data to ngrx store for getting all evnts. I'm new to angular2 and ngrx store. Any help highly appreciated.

答:
I know that this is already a quite old question, but just stumbled upon this one and am working on something similar.

I am using ngrx-store-localstorage, this module is automatically synchronizing a ngrx-store with the localstorage if you are using the rehydrate option.

Hope that helps anybody stumbling upon this problem.

Title: Local storage and ngrxstore

Body:
I have an angular2app. I stored my data into localstorage. Every time when the action getting chage local storage data will clear. How can i store this localstorage data into ngrxstore. I have the following:

component.ts

onClickRoom(room: string): void {
this.date = new Date();
this.evntList = new events('', '', '');
this.evntList.timestamp = this.date;
this.evntList.name = room;
this.evntList.type = this.type;
console.log("eventList:", this.evntList);
this.eventArray.push(this.evntList);
this.tokenmanager.store(this.eventArray);
console.log('Room clicked: ', this.eventArray); ---> This event array successfully updating.
}

globalstorage.ts

@Injectable()
export class TokenManager {

public tokenKey: string = 'app_token';

constructor() { }

store(content) {

    localStorage.setItem(this.tokenKey, JSON.stringify(content));

}

retrieve() {
    let storedToken: any = localStorage.getItem(this.tokenKey);

    if (!storedToken) throw 'no token found';
    return storedToken;
}
}

My view is:

abc

pqr    -----> This is a list.

qwe

While I'm clicking abc 3 things get stored into local storage like:

[{name: "abc", timestamp:time, type: "typename"}].

then after i clik the array will get update into

[{name: "abc", timestamp:time, type: "typename"}, {name: "pqr", timestamp:time, type: "typename"}].

But after refreshing the page and click the same item the previously stored data will lost and array is updated with new value. But actually what I need is a new appended array. Which means previously stored data and newly stored data. How can I  implement this?

How can i store this local storage data to ngrx store for getting all evnts. I'm new to angular2 and ngrx store. Any help highly appreciated.


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
"It depends"

I do not know about Java but in .net (C#, VB.net...) it is usually not required to assign a null when you no longer require a object.

However note that it is "usually not required".

By analyzing your code the .net compiler makes a good valuation of the life time of the variable...to accurately tell when the object is not being used anymore. So if you write obj=null it might actually look as if the obj is still being used...in this case it is counter productive to assign a null.

There are a few cases where it might actually help to assign a null. One example is you have a huge code that runs for long time or a method that is running in a different thread, or some loop. In such cases it might help to assign null so that it is easy for the GC to know its not being used anymore.

There is no hard & fast rule for this. Going by the above place null-assigns in your code and do run a profiler to see if it helps in any way. Most probably you might not see a benefit.

If it is .net code you are trying to optimize, then my experience has been that taking good care with Dispose and Finalize methods is actually more beneficial than bothering about nulls.

Some references on the topic:

http://blogs.msdn.com/csharpfaq/archive/2004/03/26/97229.aspx

http://weblogs.asp.net/pwilson/archive/2004/02/20/77422.aspx

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

OwnerDisplayName: Sesh

LastEditorDisplayName: Sesh