问:
Node executable could not be found in Atom with node-debugger in mac os
When I attempt to run the debugger but I get an error:

Failed to start debugger. Exit code was ENOENT which indicates that the node executable could not be found. Try specifying an explicit path in your atom config file using the node-debugger.nodePath configuration setting.

Here's my config.cson file:

```<code>"*":
  core:
    packagesWithKeymapsDisabled: [
      "git-plus"
    ]
  editor:
    fontSize: 16
  "exception-reporting":
    userId: "c1ad4fa3-59a5-4611-baf5-8312a36b059f"
  "node-debugger":
    nodePath: "/usr/bin/node"
    scriptMain: "Users/david/Documents/gitlab/prj/src/app.js"
</code>```

I tried to change the 'nodePath' parameter to '/usr/local/bin/node' but still got the same error.

I checked the following links:
node executable could not be found in atom with node-debugger pkg

https://github.com/kiddkai/atom-node-debugger/issues/127

Any help will be appreciated.

答:
In a terminal window, type which node.
Then back in Atom, go to Preferences->Packages->node->Settings.  Enter the path to node in the field Node Path.

Body:
When I attempt to run the debugger but I get an error:

Failed to start debugger. Exit code was ENOENT which indicates that the node executable could not be found. Try specifying an explicit path in your atom config file using the node-debugger.nodePath configuration setting.

Here's my config.cson file:

"*":
  core:
    packagesWithKeymapsDisabled: [
      "git-plus"
    ]
  editor:
    fontSize: 16
  "exception-reporting":
    userId: "c1ad4fa3-59a5-4611-baf5-8312a36b059f"
  "node-debugger":
    nodePath: "/usr/bin/node"
    scriptMain: "Users/david/Documents/gitlab/prj/src/app.js"

I tried to change the 'nodePath' parameter to '/usr/local/bin/node' but still got the same error.

I checked the following links:
node executable could not be found in atom with node-debugger pkg

https://github.com/kiddkai/atom-node-debugger/issues/127

Any help will be appreciated.


来源: stackexchange

问:
How to close file upload dialogue after click on upload button in protractor
I want to upload an image file in protractor. the problem is i can not get "input[type = "file"]" element without clicking on upload button.

when I click upload button, file upload dialogue popup opens.

i have tried

browser.actions().sendKeys(protractor.Key.ESCAPE).perform(); but it does not work.

This is what I am doing:

```<code>var image = '../images/image1.png';
var absPathImg = path.resolve(__dirname, image);
element(by.id('uploadImage')).click();
browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
element(by.css('input[type=file]')).sendKeys(absPathImg);
element(by.id('upload')).click();
</code>```

How can i close that file upload dialogue to upload an image?

答:
Instead of clicking on to ESCAPE, why not simulate the ENTER key press to simulate a person entering the path and pressing the ENTER key to upload the image.

I am doing this in my code and this works perfectly fine.

```<code>var path = require('path')
this.fileUploadOne = element(by.css('locator_to_element'));

var fileUpload = 'path_of_file_to_upload'

    absolutePath = path.resolve(__dirname,fileUpload);
    console.log(absolutePath);
    this.fileUploadOne.sendKeys(absolutePath);
    browser.actions().sendKeys(protractor.Key.ENTER).perform();

    //just for debugging purposes.
    browser.sleep(20000);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to upload an image file in protractor. the problem is i can not get "input[type = "file"]" element without clicking on upload button.

when I click upload button, file upload dialogue popup opens.

i have tried

browser.actions().sendKeys(protractor.Key.ESCAPE).perform(); but it does not work.

This is what I am doing:

var image = '../images/image1.png';
var absPathImg = path.resolve(__dirname, image);
element(by.id('uploadImage')).click();
browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
element(by.css('input[type=file]')).sendKeys(absPathImg);
element(by.id('upload')).click();

How can i close that file upload dialogue to upload an image?

Body:
Instead of clicking on to ESCAPE, why not simulate the ENTER key press to simulate a person entering the path and pressing the ENTER key to upload the image.

I am doing this in my code and this works perfectly fine.

var path = require('path')
this.fileUploadOne = element(by.css('locator_to_element'));

var fileUpload = 'path_of_file_to_upload'

    absolutePath = path.resolve(__dirname,fileUpload);
    console.log(absolutePath);
    this.fileUploadOne.sendKeys(absolutePath);
    browser.actions().sendKeys(protractor.Key.ENTER).perform();

    //just for debugging purposes.
    browser.sleep(20000);


问:
Swift: The method which belongs to nothing
Now I am reading the famous library "RxSwift", but I have a question.

See this page.

As you know the method _map<Element, R>(source: Observable<Element>, transform: @escaping (Element) throws -> R) doesn't belong to any class or extension or something like that.

How is this explained?

I know the concept of "top-level", but this is different with it.

Could you explain?

答:
Usually such a function is called a "global function" although in this specific case the function is only available in the RxSwift module, not globally. "Top level function" would work just as well as a descriptor.

The notion tends to throw off Java developers who are required to put every function in a class, but that requirement is an artificial and arbitrary one that only applies to Java AFAIK...


问:
Draw a line with a gradient brush (fade out from start to end point)
My task is pretty simple: draw a line from point A to point B and set different colors at point A and B, e.g. White at A and Black at B to fade out the line.

I tried doing this using a LinearGradientBrush:

```<code>var brush = new LinearGradientBrush(
                    Color.FromArgb(255, 0, 0, 0),
                    Color.FromArgb(255, 255, 0, 0), new Point(0, 0), new Point(1,1));
var pen = new Pen(brush, 10.0);

dc.DrawLine(pen, new Point (300, 300), new Point(300, 100));
</code>```

But this does not produce the wanted results since the GradientBrush is mapped according to the bounding box of the object. Therefore, the results for line going from 100/100 to 200/200 and a line going the opposite direction are the same (which is not what I want).

How could I solve this using WPF? Thanks.

Edit: I need to use the low level graphics functions (such as DrawLine) for performance reasons because I draw a lot of lines.

答:
How to use a LinearGradientBrush article with examples in both XAML and C# code.

Try this approach and please tell me is that what you need. Take attention please that this lines are drawn in opposite directions.

```<code>public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
      var image = new Image
                    {
                      Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300,300), new Point(300,100) ).Drawing),
                      Stretch = Stretch.None,
                    };

      var image2 = new Image
                     {
                       Margin = new Thickness(10, 0, 0, 0),
        Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300, 100), new Point(300, 300)).Drawing),
        Stretch = Stretch.None,
      };

      var stackPanel = new StackPanel() {Orientation = Orientation.Horizontal};
      stackPanel.Children.Add(image);
      stackPanel.Children.Add(image2);

      Content = stackPanel;
    }

    // Create a DrawingVisual that contains a rectangle.
    private DrawingVisual CreateDrawingVisualRectangle(Point start, Point end)
    {
      DrawingVisual drawingVisual = new DrawingVisual();

      // Retrieve the DrawingContext in order to create new drawing content.
      DrawingContext drawingContext = drawingVisual.RenderOpen();

      // Create a rectangle and draw it in the DrawingContext.
      var gradientStopCollection = new GradientStopCollection
                                     {
                                       new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.0),
                                       new GradientStop(Color.FromArgb(255, 255, 0, 0), 0.75)
                                     };

      var brush = new LinearGradientBrush(gradientStopCollection);
      var pen = new Pen(brush, 10.0);

      var vector1 = new Vector(start.X, start.Y);
      var vector2 = new Vector(end.X, end.Y);

      if (vector1.Length < vector2.Length)
      {
        brush.StartPoint = new Point(1, 1);
        brush.EndPoint = new Point(0, 0);
      }

      drawingContext.DrawLine(pen, start, end);
      drawingContext.Close();
      return drawingVisual;
    }
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My task is pretty simple: draw a line from point A to point B and set different colors at point A and B, e.g. White at A and Black at B to fade out the line.

I tried doing this using a LinearGradientBrush:

var brush = new LinearGradientBrush(
                    Color.FromArgb(255, 0, 0, 0),
                    Color.FromArgb(255, 255, 0, 0), new Point(0, 0), new Point(1,1));
var pen = new Pen(brush, 10.0);

dc.DrawLine(pen, new Point (300, 300), new Point(300, 100));

But this does not produce the wanted results since the GradientBrush is mapped according to the bounding box of the object. Therefore, the results for line going from 100/100 to 200/200 and a line going the opposite direction are the same (which is not what I want).

How could I solve this using WPF? Thanks.

Edit: I need to use the low level graphics functions (such as DrawLine) for performance reasons because I draw a lot of lines.

Body:
How to use a LinearGradientBrush article with examples in both XAML and C# code.

Try this approach and please tell me is that what you need. Take attention please that this lines are drawn in opposite directions.

public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
      var image = new Image
                    {
                      Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300,300), new Point(300,100) ).Drawing),
                      Stretch = Stretch.None,
                    };

      var image2 = new Image
                     {
                       Margin = new Thickness(10, 0, 0, 0),
        Source = new DrawingImage(CreateDrawingVisualRectangle(new Point(300, 100), new Point(300, 300)).Drawing),
        Stretch = Stretch.None,
      };

      var stackPanel = new StackPanel() {Orientation = Orientation.Horizontal};
      stackPanel.Children.Add(image);
      stackPanel.Children.Add(image2);

      Content = stackPanel;
    }

    // Create a DrawingVisual that contains a rectangle.
    private DrawingVisual CreateDrawingVisualRectangle(Point start, Point end)
    {
      DrawingVisual drawingVisual = new DrawingVisual();

      // Retrieve the DrawingContext in order to create new drawing content.
      DrawingContext drawingContext = drawingVisual.RenderOpen();

      // Create a rectangle and draw it in the DrawingContext.
      var gradientStopCollection = new GradientStopCollection
                                     {
                                       new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.0),
                                       new GradientStop(Color.FromArgb(255, 255, 0, 0), 0.75)
                                     };

      var brush = new LinearGradientBrush(gradientStopCollection);
      var pen = new Pen(brush, 10.0);

      var vector1 = new Vector(start.X, start.Y);
      var vector2 = new Vector(end.X, end.Y);

      if (vector1.Length < vector2.Length)
      {
        brush.StartPoint = new Point(1, 1);
        brush.EndPoint = new Point(0, 0);
      }

      drawingContext.DrawLine(pen, start, end);
      drawingContext.Close();
      return drawingVisual;
    }
  }


问:
Translating arrays in pseudocode to Python
Hello I am trying to write a short program using the following pseudocode I can not figure out how to translate the arrays in pseudocode into Python. For example:

```<code>declare Names[5] as a string
</code>```

I tried to put

```<code>Name[5] = string
</code>```

but it will come up with unresolved reference I tried looking up tutorials on how to use arrays but still can't figure it out could you give me a few tips or some good videos explaining arrays

```<code>Main
    Call writeNammeAssn()
    Declare Names[5] As String
    Declare Sales[5] As Float
    Set Max = 0
    Set K = 0
    Set Index = 0
    Names[K] = getName()
    Sales[K] = getFloat()

    While Names[K] != "*"
        If Sales[K] > Max Then
            Set Index = K
            Set Max = Sales[Index]
        End If
        Set K = K + 1
        Names[K] = getName()
        Sales[K] = getInt()
    End While

    Write "Maximum sales for the month: " + Max
    Write "Salesperson: " + Names[Index]
End Main
</code>```

Body:
Hello I am trying to write a short program using the following pseudocode I can not figure out how to translate the arrays in pseudocode into Python. For example:

declare Names[5] as a string

I tried to put

Name[5] = string

but it will come up with unresolved reference I tried looking up tutorials on how to use arrays but still can't figure it out could you give me a few tips or some good videos explaining arrays

Main
    Call writeNammeAssn()
    Declare Names[5] As String
    Declare Sales[5] As Float
    Set Max = 0
    Set K = 0
    Set Index = 0
    Names[K] = getName()
    Sales[K] = getFloat()

    While Names[K] != "*"
        If Sales[K] > Max Then
            Set Index = K
            Set Max = Sales[Index]
        End If
        Set K = K + 1
        Names[K] = getName()
        Sales[K] = getInt()
    End While

    Write "Maximum sales for the month: " + Max
    Write "Salesperson: " + Names[Index]
End Main

Body:
Names=5*[""]
print Names

result:
['', '', '', '', '']

Names[2]="test"
print Names

result:
['', '', 'test', '', '']


问:
video background responsive 480p 720p 1080p
Hello i am trying to display a video in the background but the resolution changes when the window becomes smaller for uses less data to load it on mobile and tablet.

My video formats: .mp4 - .webm - .ogv - 30sec loop.

480p - 6mb for mobile

720p - 10mb for tablet

1080p to 2k - 15mb-25mb for pc

My CSS:

```<code>    video#bgvid-480p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/480p.jpg) no-repeat;
    background-size: cover;
}

    video#bgvid-720p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/720p.jpg) no-repeat;
    background-size: cover;
}

    video#bgvid-1080p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/1080p.jpg) no-repeat;
    background-size: cover;
}

video {
display: block;
}
</code>```

My Code:

```<code><video autoplay loop poster="images/480p.jpg" id="bgvid-480p">
<source src="medias/480p.webm" type="video/webm">
<source src="medias/480p.mp4" type="video/mp4">
<source src="medias/480p.ogv" type="video/ogg">
</video>

<video autoplay loop poster="images/720p.jpg" id="bgvid-720p">
<source src="medias/720p.webm" type="video/webm">
<source src="medias/720p.mp4" type="video/mp4">
<source src="medias/720p.ogv" type="video/ogg">
</video>

<video autoplay loop poster="images/1080p.jpg" id="bgvid-1080p">
<source src="medias/1080p.webm" type="video/webm">
<source src="medias/1080p.mp4" type="video/mp4">
<source src="medias/1080p.ogv" type="video/ogg">
</video>
</code>```

What is the best solution to automatically change the video if the window is smaller. Js or css? I want to keep this basic code but I cannot make it work.

答:
It should be noted that 480 and 720 are measurements of video height — not width.
A 720p video is 1280px wide by 720 high.

So for the breakpoints it should be:

```<code>var quality = "480p";
if (width > 640 && width <= 720) { quality = "720p"; }
if (width > 1280) { quality = "1080p"; }
</code>```

Great code though! Just used it a project.

Body:
Hello i am trying to display a video in the background but the resolution changes when the window becomes smaller for uses less data to load it on mobile and tablet.

My video formats: .mp4 - .webm - .ogv - 30sec loop.

480p - 6mb for mobile

720p - 10mb for tablet

1080p to 2k - 15mb-25mb for pc

My CSS:

    video#bgvid-480p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/480p.jpg) no-repeat;
    background-size: cover;
}

    video#bgvid-720p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/720p.jpg) no-repeat;
    background-size: cover;
}

    video#bgvid-1080p {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(images/1080p.jpg) no-repeat;
    background-size: cover;
}

video {
display: block;
}

My Code:

<video autoplay loop poster="images/480p.jpg" id="bgvid-480p">
<source src="medias/480p.webm" type="video/webm">
<source src="medias/480p.mp4" type="video/mp4">
<source src="medias/480p.ogv" type="video/ogg">
</video>

<video autoplay loop poster="images/720p.jpg" id="bgvid-720p">
<source src="medias/720p.webm" type="video/webm">
<source src="medias/720p.mp4" type="video/mp4">
<source src="medias/720p.ogv" type="video/ogg">
</video>

<video autoplay loop poster="images/1080p.jpg" id="bgvid-1080p">
<source src="medias/1080p.webm" type="video/webm">
<source src="medias/1080p.mp4" type="video/mp4">
<source src="medias/1080p.ogv" type="video/ogg">
</video>

What is the best solution to automatically change the video if the window is smaller. Js or css? I want to keep this basic code but I cannot make it work.

Body:
It should be noted that 480 and 720 are measurements of video height — not width.
A 720p video is 1280px wide by 720 high.

So for the breakpoints it should be:

var quality = "480p";
if (width > 640 && width <= 720) { quality = "720p"; }
if (width > 1280) { quality = "1080p"; }

Great code though! Just used it a project.


问:
Scope variables in typescript
I'm working with Angular 2 (Typescript) on Ionic 2 App. I have one class NewFavoriteSitePage with private property siteForm and I can use this property in class methods but when I am inside one google maps method this variable is undefined. What are the scope of variable or How do I define the variable to access from both sides?

```<code>declare var google;
......
export class NewFavoriteSitePage {
  .....
  private siteForm: FormGroup;

  loadMap(){
  //I can access to siteForm here!
  .....
      google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
        let newlatLng = marker.latLng;
        console.log(this.siteForm); //Here this.siteForm is undefined
      });
  }
</code>```

答:
Use an arrow function to retain context:</p>

```<code>  google.maps.event.addListener(marker, 'dragend', (marker, siteForm) => {
    let newlatLng = marker.latLng;
    console.log(this.siteForm);
  });
</code>```

Title: Scope variables in typescript

Body:
I'm working with Angular 2 (Typescript) on Ionic 2 App. I have one class NewFavoriteSitePage with private property siteForm and I can use this property in class methods but when I am inside one google maps method this variable is undefined. What are the scope of variable or How do I define the variable to access from both sides?

declare var google;
......
export class NewFavoriteSitePage {
  .....
  private siteForm: FormGroup;

  loadMap(){
  //I can access to siteForm here!
  .....
      google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
        let newlatLng = marker.latLng;
        console.log(this.siteForm); //Here this.siteForm is undefined
      });
  }

Body:
Use an arrow function to retain context:

  google.maps.event.addListener(marker, 'dragend', (marker, siteForm) => {
    let newlatLng = marker.latLng;
    console.log(this.siteForm);
  });


问:
find all DUPLICATE TOPICS NAME mysql
I am running a query like this:

```<code>SELECT id, title, COUNT( * ) c FROM news GROUP BY title HAVING c >1 LIMIT 22
</code>```

but it's take long time to respond how to Optimizing it ?

答:
to Optimize it must title have index

```<code>CREATE INDEX index_name ON table_name (column_name);
</code>```

that will help sql to remember titles and search faster

Title: find all DUPLICATE TOPICS NAME mysql

Body:
I am running a query like this:

SELECT id, title, COUNT( * ) c FROM news GROUP BY title HAVING c >1 LIMIT 22

but it's take long time to respond how to Optimizing it ?

Body:
to Optimize it must title have index

CREATE INDEX index_name ON table_name (column_name);

that will help sql to remember titles and search faster


问:
How to handle SMTP email verification at scale without getting IPs blocked or SMTP requests rejected?
I hope this question is not completely off-topic.

I've been wondering about SMTP email verification. There are so many services (e.g. Kickbox.io, Email-Validator.net, etc.) that seem to handle SMTP verification without having their IPs blocked or SMTP requests rejected.

As far as I know there is still no other method than to use the SMTP "VRFY" command, and to abort the connection once the target SMTP server has confirmed the existence of the requested user on the given mail server. I've been playing around with a few PHP scripts that claim to do this, but I keep being rejected by some mail servers, especially hotmail (as well as all other Microsoft mail services) seem to be very quickly in rejecting "spammy" SMTP requests.

Now, my question is: How is it possible that services like the ones I mentioned above process thousands of email addresses a day and validate them via what they call "SMTP handshakes", and don't see similar issues like the ones I described?

Thanks for reading.

答:
Companies like Email-Validator.net start by analyzing the email address to see if it is syntactically valid, whether it is legal and useful (e.g. probably not postmaster) whether the domain is valid (has valid DNS records), whether the address is from a throw-away email service, and other methods of checking whether they can disqualify it immediately.

After that, they attempt to send email to the address, and check the SMTP response codes from the server.  I think this is what you meant by the "SMTP handshake" you mentioned.

VRFY is no longer a very useful method of validation because most servers don't want to expose their lists of valid addresses to spammers.  Most servers don't implement support for it, or they respond to the VRFY command with a 251 or 252, indicating that the query is legal, but they aren't going to give an informative answer.

They may also use their experience with the email service provider in question (e.g. Gmail) to evaluate what the SMTP response means.  For example, some services accept all recipient addresses as though they were valid, so they don't expose which ones are valid and which ones aren't.  If none or few of the recipients were valid, the server may later drop the connection or even accept the email but not  deliver it.  Some service providers use greylisting, which can cause valid addresses to be rejected initially.  The validation service may know about the service provider's behavior from the response, a posted policy, or from their own testing.

It's also possible that companies like kickbox.io have negotiated contracts with service providers like Microsoft Hotmail so that their queries are honored, and they can validate email addresses.  It could be in the service provider's interest to allow legitimate senders to clean their mailing lists since it reduces traffic to their servers.  However, there has to be some trust that they aren't providing validation services to spammers attempting to harvest their directory.

ContentLicense: CC BY-SA 4.0


问:
What is the Mac OSX Expose algorithm?
I am looking for an algorithm to organise squares in space in a similar fashion the OSX expose feature does.

Thanks
- rS

答: It's more involved than just filling a grid if you actively try to minimize unused space, as windows can have different aspect ratios. See this example. You can find code that does this in KDE's kwin implementation of the Present Windows effect.</p>

Title: What is the Mac OSX Expose algorithm?


问:
How do I Import a library from github in Android Studio?
[I'm a newbie] I want to include a git library in android studio -> https://github.com/florent37/MaterialViewPager
I tried this. New-> import module -> downloaded file address
But it's giving some errors.</p>

答:
```<code>allprojects {
repositories {
    jcenter()
    mavenCentral()
    maven { url "https://jitpack.io" }
}
</code>```

working code: add maven { url "https://jitpack.io" } to your project level gradle.

Body:
allprojects {
repositories {
    jcenter()
    mavenCentral()
    maven { url "https://jitpack.io" }
}

working code: add maven { url "https://jitpack.io" } to your project level gradle.


问:
Layout view is in top left corner in emulator
Constraint layout is not well placed. It always views on top left corner, but in design view it shows in the whole display. I want to display the app in full screen mode.

This is a screenshot of what's happening:

答:
It seems that you've set your
RelativeLayout to a layout_width of 364dp and a layout_height of 494dp.  It looks fine on your preview because you are using a Nexus 4 (look above your preview) as your preview but you are testing with a emulated Nexus 5. Due to the fact that you've coded the resolution to be 364dpx494dp (which is fine for a Nexus 4) your view will look different on different devices as they have difference screens. You should try changing your layout_height and layout_width to fill_parent


问:
Assigning the last iterated value to a variable in python
I have the last set of values of an iteration: y1[i],y2[i],y3[i](which was obtained by doing the integration of coupled ODE)
Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again).
This is part of my code:

```<code>#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))

#for iteration
p = 0.0
q = 1.0
n = 10000.0

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.
</code>```

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'

keeps showing up.
The link to the complete code is here:
https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)

I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.

答:
You have a variable named H and a function named H()

```<code>H = 2.27e-18
</code>```

and

```<code>def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)
</code>```

Change the name of the variable or the function for something else.

```<code>H_1 = 2.27e-18 #for example
</code>```

As @randomir says, you probably want to look at his answer too

You can reproduce the error by simple doing:

```<code>H = 5

def H(a,b):
  pass

print(H**3)
</code>```

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'

Body:
I have the last set of values of an iteration: y1[i],y2[i],y3[i](which was obtained by doing the integration of coupled ODE)
Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again).
This is part of my code:

#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))

#for iteration
p = 0.0
q = 1.0
n = 10000.0

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'

keeps showing up.
The link to the complete code is here:
https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)

I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.

Body:
You have a variable named H and a function named H()

H = 2.27e-18

and

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

Change the name of the variable or the function for something else.

H_1 = 2.27e-18 #for example

As @randomir says, you probably want to look at his answer too

You can reproduce the error by simple doing:

H = 5

def H(a,b):
  pass

print(H**3)

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'


问:
How to use a QR code to link a video?
Hello and thank you for your time:
I'd like more information about how to use QR codes to embed a video. It is related to making a pamphlet where I need to include a way to show a video which is a company's announce, but I have not used those codes before.
I need some references to start with!

I have read similar topic as:
Linking a QR Code straight to video
and
How to use a computer's webcam to read a qr code and open a website [Java]

But I need a generator or service already implemented!

答:
Follow steps below:

Upload/Pick your Video for your QR Code.

Create the QR Code Linking To Your Video.
There are some QR code generators, for example: GoQR.me

Once you are there, select the URL tab and insert your link.

Test Your QR Code Link To Your Video.
Pickup your mobile phone and open up your QR code reader. Scan your QR code video link that you just created.

Get the QR Code Out

Title: How to use a QR code to link a video?


问:
SQL- How to combine rows?
I have about a dozen or so devices I need to search on, and some of them have a variant. For example, if I do a GROUP BY device, it looks something like this:

```<code>Device Amount
X1     10
X2     2
X2-A   6
X3     9
X3-A   3
X4     8
X5     11
etc...
</code>```

Personally, I don't care about the variants, so after I search I have to go into Excel and manually add the rows for X2 and X2A. Is there a way to combine them in my search query?

答:
Well, if these are always two characters, you can do:

```<code>select substr(Device, 1, 2) as Device, sum(Amount)
from t
group by substr(Device, 1, 2);
</code>```

If the expression can be of variable length, then you can have a more complicated string expression.

Title: SQL- How to combine rows?

Body:
I have about a dozen or so devices I need to search on, and some of them have a variant. For example, if I do a GROUP BY device, it looks something like this:

Device Amount
X1     10
X2     2
X2-A   6
X3     9
X3-A   3
X4     8
X5     11
etc...

Personally, I don't care about the variants, so after I search I have to go into Excel and manually add the rows for X2 and X2A. Is there a way to combine them in my search query?

Body:
Well, if these are always two characters, you can do:

select substr(Device, 1, 2) as Device, sum(Amount)
from t
group by substr(Device, 1, 2);

If the expression can be of variable length, then you can have a more complicated string expression.


问:
Necessity of repair before Cassandra version upgrade
Our production version of DSE is 4.8.4(Cassandra 2.1.12). We run 3 nodes cluster with 256 vnodes per node, ~200GB data per node, RF=3. We are going to consistently migrate to the latest DSE version 5.1.1(Cassandra 3.10.0).

According to DataStax upgrade manual http://docs.datastax.com/en/upgrade/doc/upgrade/datastax_enterprise/upgdDSE50.html repair should be done before starting the upgrade. We don't use incremental repairs and to repair the entire cluster we ran full sequential repair on a single node. After 12 hours of running 100/768 token ranges are repaired, but cpu usage pretty high and number of sstables for one of our tables increases almost linearly. We have several issues with this table during normal operation as well and one of the upgrade reason is to replace existing DTCS with new TWCS compaction strategy.

We are concerned about long repair time duration and increasing resources utilization.
So we want to know whether repair is 100% necessary before upgrade? What are consequences of not doing/doing it? If we are going to upgrade several versions consistently should we perform read repair after each upgrade?

答:
So, you don't do regular repairs at all? It's highly recommended.

About repair before the upgrade: from what i know it's just a precaution, as upgrade process itself will not modify your data until you upgrade sstables in the end.

If you use QUORUM consistency level you should not be affected much by inconsistencies between nodes which will be eventually repaired by Read Repair.

So i think it's safe, but i think you should ask Datastax just to be sure.


问:
How to get the id number of a new turtle just created?
I have the following code where I hatch a new agent,

```<code>to t-of-slowdown [ es-poi ]
  if we-look > 0 [
    set we-look (we-look - 1)
    if (we-look <= 0) [
      if es-poi and (not any? events-here) [
        hatch-events 1 [
          set color green
          set size 5
          set is-poi? true
          set new-poi true
          let m [[ end2 ] of cur-link] of myself
          move-to  m ]
        set events-x ([who] of events-here)
        show events-x
        set we-poi-var va-geometric (1 / 1500) + we-ticks poi
        set sera-poi false
      ]
      set impregna true
      set color red
      set seguir true
      set we-look random-normal 120 20 ;time to watch an event
      ]
  ]
end
</code>```

which is run in a turtle context (walkers breed)
A walker is moving by a 'link' (another procedure which calls this one), and when a counter is <0,
this code generates a new event (events breed) and places it in the same place where the walker is (cur-link is the current walker link).
After that, the walker must get the id number of the new event

```<code>set events-x ([who] of events-here)
</code>```

The problem here is that variable events-x get an empty list []. The next time the walker passes by the same event it does get the number-id of the event.

Something must be wrong but I can not guess what it is.
I would appreciate very much if someone could take a look and point me some help.

Regards

答:
You could:

```<code>let child-who -1
hatch-events 1 [
  ...
  set child-who who
  ...
]
set events-x child-who
</code>```

Or:

```<code>hatch-events 1 [
  ...
  let child-who who
  ask myself [ set events-x my-who ]
  ...
]
</code>```

Both of these are a bit clunky, sadly. The second one avoids needing to initialize child-who to a meaningless value, but it requires using myself, a primitive that is likely to mystify the reader.

You could avoid both problems with:

```<code>let parent self
hatch-events 1 [
  ...
  let child-who who
  ask parent [ set events-x child-who ]
  ...
]
</code>```

(But note that using who numbers at all, for anything, is rarely the best and most idiomatic solution to any problem. It's almost always better to store a reference to the turtle itself.)

Body:
I have the following code where I hatch a new agent,

to t-of-slowdown [ es-poi ]
  if we-look > 0 [
    set we-look (we-look - 1)
    if (we-look <= 0) [
      if es-poi and (not any? events-here) [
        hatch-events 1 [
          set color green
          set size 5
          set is-poi? true
          set new-poi true
          let m [[ end2 ] of cur-link] of myself
          move-to  m ]
        set events-x ([who] of events-here)
        show events-x
        set we-poi-var va-geometric (1 / 1500) + we-ticks poi
        set sera-poi false
      ]
      set impregna true
      set color red
      set seguir true
      set we-look random-normal 120 20 ;time to watch an event
      ]
  ]
end

which is run in a turtle context (walkers breed)
A walker is moving by a 'link' (another procedure which calls this one), and when a counter is <0,
this code generates a new event (events breed) and places it in the same place where the walker is (cur-link is the current walker link).
After that, the walker must get the id number of the new event

set events-x ([who] of events-here)

The problem here is that variable events-x get an empty list []. The next time the walker passes by the same event it does get the number-id of the event.

Something must be wrong but I can not guess what it is.
I would appreciate very much if someone could take a look and point me some help.

Regards

Body:
You could:

let child-who -1
hatch-events 1 [
  ...
  set child-who who
  ...
]
set events-x child-who

Or:

hatch-events 1 [
  ...
  let child-who who
  ask myself [ set events-x my-who ]
  ...
]

Both of these are a bit clunky, sadly. The second one avoids needing to initialize child-who to a meaningless value, but it requires using myself, a primitive that is likely to mystify the reader.

You could avoid both problems with:

let parent self
hatch-events 1 [
  ...
  let child-who who
  ask parent [ set events-x child-who ]
  ...
]

(But note that using who numbers at all, for anything, is rarely the best and most idiomatic solution to any problem. It's almost always better to store a reference to the turtle itself.)


问:
Bootstrap pull-right only working at small width
I'm using Bootstrap to get some text and a button to appear on the same line on opposite sides of the screen. I'm using pull-right to bring the button to the right side of the screen, but it only works when the screen width is narrow. If I make it wider, the button moves next to the text. Here's a JSFiddle example and the relevant code:

```<code><body>
    <div class='container-fluid'>
        <form class="form-inline">
            <div class="form-group ">
                <label>Some Text</label>
                <button type="button" class="btn btn-primary pull-right">Some Button</button>
            </div>
        </form>
        <div><p>The button only appears on the right side of the window when the width is fairly narrow, even though it has the Bootstrap 'pull-right' class.</p></div>

    </div>
</body>
</code>```

Is there a way to get the button to the right at all widths? Apologies, I'm not great with Bootstrap and CSS, so I'm sure this is an easy thing that I'm missing. Also, for what it's worth, this is for an Electron app, so it only needs to work in Chrome.

Thanks.

答: That's because it's wrapped in a form group div, which is only the full width on smaller viewports. You could get rid of the form group and just make the div width:100% in css.

Body:
I'm using Bootstrap to get some text and a button to appear on the same line on opposite sides of the screen. I'm using pull-right to bring the button to the right side of the screen, but it only works when the screen width is narrow. If I make it wider, the button moves next to the text. Here's a JSFiddle example and the relevant code:

        <form class="form-inline">

                Some Text
                <button type="button" class="btn btn-primary pull-right">Some Button</button>

        </form>

The button only appears on the right side of the window when the width is fairly narrow, even though it has the Bootstrap 'pull-right' class.

Is there a way to get the button to the right at all widths? Apologies, I'm not great with Bootstrap and CSS, so I'm sure this is an easy thing that I'm missing. Also, for what it's worth, this is for an Electron app, so it only needs to work in Chrome.

Thanks.


问:
Which is more efficient Cstr(value) or value.ToString()
I am wondering which is more efficient, using CStr() or object.toString().
The reason I ask this is because I thought all that CStr() does is to invoke the .ToString() method on the object it was dealing with.

But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object).

The following is purely an example to illustrate the issue.

```<code>Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return value.ToString
End Function
</code>```

Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can use .ToString()

```<code>Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return CStr(value)
End Function
</code>```

答:
Here is the results of a little test I made:

```<code>Module Module1
  Sub Main()

    Dim obj As Object = "asdfsdasdfsadfasdfasdfasdfsdasdfsadfasdfasdfdafsdfasd"
    Dim y = Now, z = Now

    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(obj.ToString)
    Next
    z = Now
    Dim time1 = z - y

    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(CStr(obj))
    Next
    z = Now

    Dim time2 = z - y
    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(DirectCast(obj, String))
    Next
    z = Now

    Dim time3 = z - y

    Console.WriteLine("obj.ToString took {0}.", time1)
    Console.WriteLine("CStr(obj) took {0}.", time2)
    Console.WriteLine("DirectCast(obj, String) took {0}.", time3)
    Console.Read()
  End Sub
End Module
</code>```

Results:

```<code>obj.ToString() took 00:00:06.9303964.
CStr(obj) took 00:00:06.8763933.
DirectCast(obj, String) took 00:00:06.8903941.
</code>```

Which makes it certain that CStr is the fastest, then goes DirectCast and finally ToString with highes performance cost.

Body:
I am wondering which is more efficient, using CStr() or object.toString().
The reason I ask this is because I thought all that CStr() does is to invoke the .ToString() method on the object it was dealing with.

But when recently using a generic method without any type constraints I had to use object.ToString() instead of CStr(object).

The following is purely an example to illustrate the issue.

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return value.ToString
End Function

Compiled as expected, but the following did not using CStr(). It gave an compilation error value of type ID_TYPE cannot be converted to string. But it obviously can use .ToString()

Public Function IDFromObject(Of ID_TYPE)(ByVal value As ID_TYPE) As String
    Return CStr(value)
End Function

Body:
Here is the results of a little test I made:

Module Module1
  Sub Main()

    Dim obj As Object = "asdfsdasdfsadfasdfasdfasdfsdasdfsadfasdfasdfdafsdfasd"
    Dim y = Now, z = Now

    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(obj.ToString)
    Next
    z = Now
    Dim time1 = z - y

    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(CStr(obj))
    Next
    z = Now

    Dim time2 = z - y
    y = Now
    For i = 0 To Short.MaxValue
      Console.WriteLine(DirectCast(obj, String))
    Next
    z = Now

    Dim time3 = z - y

    Console.WriteLine("obj.ToString took {0}.", time1)
    Console.WriteLine("CStr(obj) took {0}.", time2)
    Console.WriteLine("DirectCast(obj, String) took {0}.", time3)
    Console.Read()
  End Sub
End Module

Results:

obj.ToString() took 00:00:06.9303964.
CStr(obj) took 00:00:06.8763933.
DirectCast(obj, String) took 00:00:06.8903941.

Which makes it certain that CStr is the fastest, then goes DirectCast and finally ToString with highes performance cost.


问:
Invalid Syntax error pandas series
I am starting out with pandas on jupyter notebook. In the error message, there is a ^ below the = operator, but I cannot see the problem. What's missing?  thanks!

```<code>import pandas as pd
data2 = ([1, 2, 3, 4],  index = ['a', 'b', 'c', 'd'])

s = pd.Series(data2)
print(s.shape)
</code>```

This is the error:

```<code>File "<ipython-input-30-57c99bd7e494>", line 4
    data2 = ([1, 2, 3, 4],  index = ['a', 'b', 'c', 'd'])
                                  ^
SyntaxError: invalid syntax
</code>```

答:
There proper way to do this is, separate variables for data and index:

```<code>import pandas as pd
data2 = [1,2,3,4]
index = ['a','b','c','d']

s = pd.Series(data2,index)
print(s.shape)
</code>```

Or as ayhan points our you could unpack a dictionary with **:

```<code>data2 = dict(data=[1,2,3,4], index=['a','b','c','d'])
s = pd.Series(**data2)
print(s.shape)
</code>```

Title: Invalid Syntax error pandas series

Body:
I am starting out with pandas on jupyter notebook. In the error message, there is a ^ below the = operator, but I cannot see the problem. What's missing?  thanks!

import pandas as pd
data2 = ([1, 2, 3, 4],  index = ['a', 'b', 'c', 'd'])

s = pd.Series(data2)
print(s.shape)

This is the error:

File "<ipython-input-30-57c99bd7e494>", line 4
    data2 = ([1, 2, 3, 4],  index = ['a', 'b', 'c', 'd'])
                                  ^
SyntaxError: invalid syntax

Body:
There proper way to do this is, separate variables for data and index:

import pandas as pd
data2 = [1,2,3,4]
index = ['a','b','c','d']

s = pd.Series(data2,index)
print(s.shape)

Or as ayhan points our you could unpack a dictionary with **:

data2 = dict(data=[1,2,3,4], index=['a','b','c','d'])
s = pd.Series(**data2)
print(s.shape)


问:
AttributeError: 'FlashPolicyServer' object has no attribute 'kill'
I get the following error as soon as I run django app along with the django-socketio app using python manage.py runserver_socketio

```<code>SocketIOServer running on 127.0.0.1:8001

KeyboardInterrupt
Thu Jul  6 22:04:52 2017
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
   execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
   utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
   self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
   self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
   output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django_socketio-0.3.9-py2.7.egg/django_socketio/management/commands/runserver_socketio.py", line 65, in handle
   server.kill()
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 43, in kill
   self.policy_server.kill()
 AttributeError: 'FlashPolicyServer' object has no attribute 'kill'
</code>```

Am I missing something ?

答:
Inspired by this issue, I tried downgrading gevent-socketio and gevent and it worked.</p>

```<code>pip uninstall gevent-socketio gevent
pip install gevent-socketio==0.2.1 gevent==0.13.6
</code>```

Body:
I get the following error as soon as I run django app along with the django-socketio app using python manage.py runserver_socketio

SocketIOServer running on 127.0.0.1:8001

KeyboardInterrupt
Thu Jul  6 22:04:52 2017
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
   execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
   utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 345, in execute
   self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 348, in run_from_argv
   self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 399, in execute
   output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django_socketio-0.3.9-py2.7.egg/django_socketio/management/commands/runserver_socketio.py", line 65, in handle
   server.kill()
  File "/usr/local/lib/python2.7/dist-packages/socketio/server.py", line 43, in kill
   self.policy_server.kill()
 AttributeError: 'FlashPolicyServer' object has no attribute 'kill'

Am I missing something ?

Body:
Inspired by this issue, I tried downgrading gevent-socketio and gevent and it worked.

pip uninstall gevent-socketio gevent
pip install gevent-socketio==0.2.1 gevent==0.13.6


问:
Convert native uint8_t (Java byte) into an int
I have a native function (from a library) that does some work on uint8_t types (unsigned 8-bit number 0-255). The closest thing Java has is byte which must be signed.

How can I convert this byte into a proper positive integer to use in Java? I know I'll have to store it in a short or int in order to properly represent numbers from 0-255, but I don't know how to convert the byte.

I tried int intValue = byteValue & 0xFF;, but that is giving me unexpected results, so I suspect it's incorrect. Or that is correct and I am misunderstanding the expected results from the native library function. Would appreciate confirmation either way.

答:
In Java, you can use a Guava library function to convert a byte to an int, treating it as unsigned: UnsignedBytes.toInt. So, if you returned the value of a C++ unsigned value as a byte to Java, you can then fix it up.

If you want to make it into an int and then return it to java as an int, that should be perfectly straightforward.


问:
Combining click and touchstart events not working
I have a website that I'm trying to make functional on mobile as well.  However, when I combine click and touchstart events for PC and tablets respectively, neither works(Clicking on the element the events are attached to aren't firing).  Can anyone explain how I should go about fixing this?  Here's an example of one element not working, the pen has the entire project.

HTML

```<code><div id="menu">
    <h1>MENU</h1>
</div>
<div class="dropdown hidden">
    <ul>
        <li id="home_navlink">Home</li>
        <li id="about_navlink">About Me</li>
        <li id="work_navlink">My Work</li>
        <li id="contact_navlink">Contact Me</li>
    </ul>
</div>
</code>```

JS

```<code>let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
    if(dropdown.classList.contains("showing")){
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    }
    else{
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
})
</code>```

Pen

答:
Fetch the menu using javascript:

```<code>let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
</code>```

Declare a handler function as a function reference:

```<code>let clickHandler = function() {
    if (dropdown.classList.contains("showing")) {
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    } else {
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
}
</code>```

Assign it to the click event:

```<code>menu.addEventListener("click", clickHandler);
</code>```

And then check for touch event handler and assign a function for touchstart:

```<code>if ('ontouchstart' in window) {
    menu.addEventListener("touchstart", function() {
        var touchHndl = function() {
            //call the clickHandler actually
            clickHandler();
            //remove the touchend haldler after perform
            this.removeEventListener(touchHndl)
        }
        //attach a handler for touch end when you are in touchstart event
        this.addEventListener(touchHndl);
    });
}
</code>```

So you were asking about a code segment in plain javascript, hope it helps.  :)

Body:
I have a website that I'm trying to make functional on mobile as well.  However, when I combine click and touchstart events for PC and tablets respectively, neither works(Clicking on the element the events are attached to aren't firing).  Can anyone explain how I should go about fixing this?  Here's an example of one element not working, the pen has the entire project.

HTML

MENU

Home

About Me

My Work

Contact Me

JS

let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
    if(dropdown.classList.contains("showing")){
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    }
    else{
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
})

Pen

Body:
Fetch the menu using javascript:

let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];

Declare a handler function as a function reference:

let clickHandler = function() {
    if (dropdown.classList.contains("showing")) {
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    } else {
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
}

Assign it to the click event:

menu.addEventListener("click", clickHandler);

And then check for touch event handler and assign a function for touchstart:

if ('ontouchstart' in window) {
    menu.addEventListener("touchstart", function() {
        var touchHndl = function() {
            //call the clickHandler actually
            clickHandler();
            //remove the touchend haldler after perform
            this.removeEventListener(touchHndl)
        }
        //attach a handler for touch end when you are in touchstart event
        this.addEventListener(touchHndl);
    });
}

So you were asking about a code segment in plain javascript, hope it helps.  :)


问:
How to style vaadin-context-menu?
This question is about the ES6 web component (compatible with Polymer 2.0) called vaadin-context-menu version 3.0.0-alpha1.

In the below screen capture, I want the paper-item labeled "Logout" to look the same as the paper items labeled "Edit Profile" and "Preferences."

Specifically, when not being hovered, I want all three to have:

```<code>paper-item {
  background-color: white;
  font-weight: normal;
}
</code>```

Here is my code.

my-el.html

```<code><vaadin-context-menu selector="button" open-on="click" close-on="none">
  <template>
    <style>
      paper-item {
        cursor: pointer;
        --paper-item-focused: {     /* Doesn't seem to work */
          background-color: white;  /* Doesn't seem to work */
          font-weight: normal;      /* Doesn't seem to work */
        };
      }
      paper-item {                  /* Doesn't seem to work */
        background-color: white;    /* Doesn't seem to work */
        font-weight: normal;        /* Doesn't seem to work */
      }
      paper-item:hover {
        background-color: var(--app-primary-color);
        color: white;
      }
    </style>
    <paper-listbox>
      <paper-item>Edit Profile</paper-item>
      <paper-item>Preferences</paper-item>
      <hr />
      <paper-item>Logout</paper-item>
    </paper-listbox>
  </template>
  <button>Click Me</button>
</vaadin-context-menu>
</code>```

答:
Here is one solution that bypasses the automatic highlighting of previously selected items. It is taken from the documentation here.

jsBin | source

https://jsbin.com/muwapaweke/1/edit?html,output

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>vaadin-context-menu demo</title>
  <script src="https://cdn.vaadin.com/vaadin-core-elements/master/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/vaadin-context-menu/vaadin-context-menu.html">

  <!-- import paper-menu and paper-item -->
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-listbox/paper-listbox.html">
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-item/paper-item.html">
</head>
<body>

<vaadin-context-menu>
  <template>
    <style>
      .my-menu {
        padding: 8px 0;
        background: #fff;
      }

      .my-menu-item {
        display: block;
        padding: 8px 24px;
        text-decoration: none;
        color: #000;
      }

      .my-menu-item:hover {
        background: #eee;
      }
    </style>
    <div class="my-menu">
      <a href="#" class="my-menu-item">First menu item</a>
      <a href="#" class="my-menu-item">Second menu item</a>
    </div>
  </template>

  <p>
    This paragraph has a context menu built using basic HTML elements
    and global CSS styles.
  </p>
</vaadin-context-menu>
</body>
</html>
</code>```

Title: How to style vaadin-context-menu?

Body:
This question is about the ES6 web component (compatible with Polymer 2.0) called vaadin-context-menu version 3.0.0-alpha1.

In the below screen capture, I want the paper-item labeled "Logout" to look the same as the paper items labeled "Edit Profile" and "Preferences."

Specifically, when not being hovered, I want all three to have:

paper-item {
  background-color: white;
  font-weight: normal;
}

Here is my code.

my-el.html

<vaadin-context-menu selector="button" open-on="click" close-on="none">
  <template>

    <paper-listbox>
      <paper-item>Edit Profile</paper-item>
      <paper-item>Preferences</paper-item>

      <paper-item>Logout</paper-item>
    </paper-listbox>
  </template>
  <button>Click Me</button>
</vaadin-context-menu>

Body:
Here is one solution that bypasses the automatic highlighting of previously selected items. It is taken from the documentation here.

jsBin | source

https://jsbin.com/muwapaweke/1/edit?html,output

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>vaadin-context-menu demo</title>
  <script src="https://cdn.vaadin.com/vaadin-core-elements/master/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/vaadin-context-menu/vaadin-context-menu.html">

  <!-- import paper-menu and paper-item -->
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-listbox/paper-listbox.html">
  <link rel="import" href="https://cdn.vaadin.com/vaadin-core-elements/master/paper-item/paper-item.html">
</head>
<body>

<vaadin-context-menu>
  <template>
    <style>
      .my-menu {
        padding: 8px 0;
        background: #fff;
      }

      .my-menu-item {
        display: block;
        padding: 8px 24px;
        text-decoration: none;
        color: #000;
      }

      .my-menu-item:hover {
        background: #eee;
      }
    </style>
    <div class="my-menu">
      <a href="#" class="my-menu-item">First menu item</a>
      <a href="#" class="my-menu-item">Second menu item</a>
    </div>
  </template>

  <p>
    This paragraph has a context menu built using basic HTML elements
    and global CSS styles.
  </p>
</vaadin-context-menu>
</body>
</html>


问:
Spring Batch :- Running Job in two stages
Here is the spring batch design for job recommending to my client:-

UI application will call Rest API on API server. Rest API creates a unique id , and send unique id, job params, job name as jms message to some batch server.  Rest API sends the unique token id to UI.

JMS message listener on batch server create a new spring batch job instance and set up unique id as job param and run the job.

UI keeps on polling the Status Rest API by passing the unique token.

Rest API finds from job param table for unique id, job execution id and provide the job status to UI.

Please advise, any suggestion so that we can create the job on API server, so that job instance and param created but does not execute any steps. We know the job execution id

On batch server with input job execution id, we can rerun/resume the job again.

答: I was able to do this by providing my own incrementer factory while creating the  Job Repository bean. Now I can get the job execution from  Seq at UI layer and use same while running  job. Job execution id is stored in thread local at batch server. I am overrirding the getNextKey() method from OracleSequenceMaxValueIncrementer</p>


问:
Golang Error Types are empty when encoded to JSON
I'm trying to encode some JSON for a REST api, everything is working fine except for some errors. For example, with this struct:

```<code>type TemplateResponse struct {
    Message string
    Error   error
    Template Template
}
</code>```

Encoded with this data:

```<code>res := TemplateResponse{"Template not found.", fmt.Errorf("There is no template on this host with the name " + vars["name"]), Template{}}
json.NewEncoder(w).Encode(res)
</code>```

Returns:

```<code>{
  "Message": "Template not found.",
  "Error": {},
  "Template": {
    "Name": "",
    "Disabled": false,
    "Path": "",
    "Version": ""
  }
}
</code>```

I'm getting this seemingly randomly across my application, where 'error' types are being returned as empty. Any ideas?

Thanks!

答:
Because error is just an interface. It may hold a value of any concrete type that implements it.

In your example you used fmt.Errorf() to create an error value. That calls errors.New() which returns a pointer to a value of the unexported errors.errorString struct. Its definition is:

```<code>type errorString struct {
    s string
}
</code>```

This struct value will be marshaled, but since it has no exported fields (only exported fields are marshaled), it will be an empty JSON object: {}.

The "fix" is: don't marshal values of "general" interfaces, relying on that the dynamic values can be marshaled into JSON meaningfully. Instead you should add a field that stores the error string (the result of error.Error()), and omit the Error error field from marshaling, e.g.:

```<code>type TemplateResponse struct {
    Message  string
    Error    error `json:"-"`
    ErrorMsg string
    Template Template
}
</code>```

Of course then you also need to set / fill the ErrorMsg field before marshaling.

Or if you don't need to store the error value in the struct, remove that field completely:

```<code>type TemplateResponse struct {
    Message  string
    ErrorMsg string
    Template Template
}
</code>```

If you still want to keep the Error error field (and not the ErrorMsg field), then you need to implement a custom marshaling logic by implementing the json.Marshaler interface where you can "convert" the error value to a meaningful string for example (or into another value that can be marshaled properly).

Body:
I'm trying to encode some JSON for a REST api, everything is working fine except for some errors. For example, with this struct:

type TemplateResponse struct {
    Message string
    Error   error
    Template Template
}

Encoded with this data:

res := TemplateResponse{"Template not found.", fmt.Errorf("There is no template on this host with the name " + vars["name"]), Template{}}
json.NewEncoder(w).Encode(res)

Returns:

{
  "Message": "Template not found.",
  "Error": {},
  "Template": {
    "Name": "",
    "Disabled": false,
    "Path": "",
    "Version": ""
  }
}

I'm getting this seemingly randomly across my application, where 'error' types are being returned as empty. Any ideas?

Thanks!

Body:
Because error is just an interface. It may hold a value of any concrete type that implements it.

In your example you used fmt.Errorf() to create an error value. That calls errors.New() which returns a pointer to a value of the unexported errors.errorString struct. Its definition is:

type errorString struct {
    s string
}

This struct value will be marshaled, but since it has no exported fields (only exported fields are marshaled), it will be an empty JSON object: {}.

The "fix" is: don't marshal values of "general" interfaces, relying on that the dynamic values can be marshaled into JSON meaningfully. Instead you should add a field that stores the error string (the result of error.Error()), and omit the Error error field from marshaling, e.g.:

type TemplateResponse struct {
    Message  string
    Error    error `json:"-"`
    ErrorMsg string
    Template Template
}

Of course then you also need to set / fill the ErrorMsg field before marshaling.

Or if you don't need to store the error value in the struct, remove that field completely:

type TemplateResponse struct {
    Message  string
    ErrorMsg string
    Template Template
}

If you still want to keep the Error error field (and not the ErrorMsg field), then you need to implement a custom marshaling logic by implementing the json.Marshaler interface where you can "convert" the error value to a meaningful string for example (or into another value that can be marshaled properly).


问:
How to count number of words from String using shell
I want to count number of words from a String using Shell.

Suppose the String is:

```<code>input="Count from this String"
</code>```

Here the delimiter is space ' ' and expected output is 4.
There can also be trailing space characters in the input string like "Count from this String ".

If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?

答:
I'll just chime in with a perl one-liner (avoiding 'useless use of echo'):</p>

```<code>perl -lane 'print scalar(@F)' <<< $input
</code>```

Body:
I want to count number of words from a String using Shell.

Suppose the String is:

input="Count from this String"

Here the delimiter is space ' ' and expected output is 4.
There can also be trailing space characters in the input string like "Count from this String ".

If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?

Body:
I'll just chime in with a perl one-liner (avoiding 'useless use of echo'):

perl -lane 'print scalar(@F)' <<< $input


问:
How to make a column in SQL case insensitive?
The problem is the page linking process in wikimedia whereby I create a link [[like this]] or [[Like This]] creating two different links. A third and separate link would be [[LIKE this]] ... I was hoping to make the database case insensitive so they would all link to the same page. Here are some proposed solutions: I was attempting solution #6. https://meta.wikimedia.org/wiki/Case_sensitivity_of_page_names

http://archive.is/Dm5YI#selection-376.1-393.32

Case insensitive means:

https://iglooo.000webhostapp.com/index.php?title=Computer_science

would return the same results as:

https://iglooo.000webhostapp.com/index.php?title=Computer_Science

Instead of a separate page like it currently does.

‘collate latin1_bin’ actually forces the mySQL column to be case sensitive.

Here is what I did, the key drop is required for the alter table:

```<code>alter table page drop key name_title;
alter table page modify column page_title varchar(255) NOT NULL default '';
</code>```

There is table named 'page' that needs to become case insensitive. The above attempt at this has failed. Please help.

I am using the latest mediawiki distrobution.

答:
If you don't clean the data going into the system, there is no way to store it in a case insensitive way. That being said, you can query on the data using a function.

select
    foo.bar
from
    foo
where
    upper(foo.bar) = upper(MY_PARAMETER)
```

Note, the right hand upper() cluase would be better handled in your application logic, but it's perfectly possible to do it here.

Body:
The problem is the page linking process in wikimedia whereby I create a link [[like this]] or [[Like This]] creating two different links. A third and separate link would be [[LIKE this]] ... I was hoping to make the database case insensitive so they would all link to the same page. Here are some proposed solutions: I was attempting solution #6. https://meta.wikimedia.org/wiki/Case_sensitivity_of_page_names

http://archive.is/Dm5YI#selection-376.1-393.32

Case insensitive means:

https://iglooo.000webhostapp.com/index.php?title=Computer_science

would return the same results as:

https://iglooo.000webhostapp.com/index.php?title=Computer_Science

Instead of a separate page like it currently does.

‘collate latin1_bin’ actually forces the mySQL column to be case sensitive.

Here is what I did, the key drop is required for the alter table:

alter table page drop key name_title;
alter table page modify column page_title varchar(255) NOT NULL default '';

There is table named 'page' that needs to become case insensitive. The above attempt at this has failed. Please help.

I am using the latest mediawiki distrobution.

Body:
If you don't clean the data going into the system, there is no way to store it in a case insensitive way. That being said, you can query on the data using a function.

select
    foo.bar
from
    foo
where
    upper(foo.bar) = upper(MY_PARAMETER)

Note, the right hand upper() cluase would be better handled in your application logic, but it's perfectly possible to do it here.


答:
Avoiding the alter table and the change of format for you column you can simply use a collate

in you query

```<code>col_name = 'Computer_science' COLLATE latin1_general_ci
</code>```

in this way the select column is used as case insesitive (by passing) you bin collation in table definition

Title: How to make a column in SQL case insensitive?

Body:
Avoiding the alter table and the change of format for you column you can simply use a collate

in you query

col_name = 'Computer_science' COLLATE latin1_general_ci

in this way the select column is used as case insesitive (by passing) you bin collation in table definition


问:
delete select option inside div with siblings()
I wrote this PHP code:

```<code>for ($i=1; $i < 11; $i++)
{
    $output.='
    <div class="form-group">
      <label>Schedule priority: '.$i.' </label><br>
      <select class="form-control selectDisable">
        <option selected disabled>Select an option</option>
        <option value="1">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Monday</option>
        <option value="2">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Tuesday</option>
        <option value="3">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Wednesday</option>
        <option value="4">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Thrusday</option>
        <option value="5">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Friday</option>
        <option value="6">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Saturday</option>
        <option value="7">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Sunday</option>
      </select>
    </div>';
}
</code>```

With Jquery I'm looking for delete selected option on siblings selects with this code:

```<code>   $(document).on('change','.selectDisable',function(){
    $(this).siblings().find('option[value="'+$(this).val()+'"]').remove();
  });
</code>```

It doesn´t work, maybe because the selects are inside
if i delete that tag the code works fine.

How I can run my code without remove the div tags?

答:
Siblings are elements of the same level. Your selects are in different levels. I suppose you can just select all selects without siblings:

```<code>$(document).on('change','.selectDisable',function(){
    $('.selectDisable').find('option[value="'+$(this).val()+'"]').remove();
});
</code>```

If you don't want to remove value from current select - use not:

```<code>$(document).on('change','.selectDisable',function(){
    $('.selectDisable').not(this).find('option[value="'+$(this).val()+'"]').remove();
});
</code>```

Body:
I wrote this PHP code:

for ($i=1; $i < 11; $i++)
{
    $output.='

      Schedule priority: '.$i.'

      <select class="form-control selectDisable">
        <option selected disabled>Select an option</option>
        <option value="1">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Monday</option>
        <option value="2">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Tuesday</option>
        <option value="3">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Wednesday</option>
        <option value="4">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Thrusday</option>
        <option value="5">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Friday</option>
        <option value="6">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Saturday</option>
        <option value="7">Schedule: 00:00 - 00:00 Break:  00:00 - 00:00 Restday: Sunday</option>
      </select>

';
}

With Jquery I'm looking for delete selected option on siblings selects with this code:

   $(document).on('change','.selectDisable',function(){
    $(this).siblings().find('option[value="'+$(this).val()+'"]').remove();
  });

It doesn´t work, maybe because the selects are inside
if i delete that tag the code works fine.

How I can run my code without remove the div tags?

Body:
Siblings are elements of the same level. Your selects are in different levels. I suppose you can just select all selects without siblings:

$(document).on('change','.selectDisable',function(){
    $('.selectDisable').find('option[value="'+$(this).val()+'"]').remove();
});

If you don't want to remove value from current select - use not:

$(document).on('change','.selectDisable',function(){
    $('.selectDisable').not(this).find('option[value="'+$(this).val()+'"]').remove();
});


问:
Can i override layout id in support library?
I want use custom view in BottomNavigationView from google support library.
I found where load view (android.support.design.internal.BottomNavigationItemView):

```<code>public BottomNavigationItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        final Resources res = getResources();
        int inactiveLabelSize =
                res.getDimensionPixelSize(R.dimen.design_bottom_navigation_text_size);
        int activeLabelSize = res.getDimensionPixelSize(
                R.dimen.design_bottom_navigation_active_text_size);
        mDefaultMargin = res.getDimensionPixelSize(R.dimen.design_bottom_navigation_margin);
        mShiftAmount = inactiveLabelSize - activeLabelSize;
        mScaleUpFactor = 1f * activeLabelSize / inactiveLabelSize;
        mScaleDownFactor = 1f * inactiveLabelSize / activeLabelSize;

        LayoutInflater.from(context).inflate(R.layout.design_bottom_navigation_item, this, true);
        setBackgroundResource(R.drawable.design_bottom_navigation_item_background);
        mIcon = (ImageView) findViewById(R.id.icon);
        mSmallLabel = (TextView) findViewById(R.id.smallLabel);
        mLargeLabel = (TextView) findViewById(R.id.largeLabel);
    }
</code>```

Can i replace this layout without fork class? Replace design_bottom_navigation_item layout?

答: Yes. It's possible. Just put design_bottom_navigation_item.xml in layout folder.</p>

Body:
I want use custom view in BottomNavigationView from google support library.
I found where load view (android.support.design.internal.BottomNavigationItemView):

public BottomNavigationItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        final Resources res = getResources();
        int inactiveLabelSize =
                res.getDimensionPixelSize(R.dimen.design_bottom_navigation_text_size);
        int activeLabelSize = res.getDimensionPixelSize(
                R.dimen.design_bottom_navigation_active_text_size);
        mDefaultMargin = res.getDimensionPixelSize(R.dimen.design_bottom_navigation_margin);
        mShiftAmount = inactiveLabelSize - activeLabelSize;
        mScaleUpFactor = 1f * activeLabelSize / inactiveLabelSize;
        mScaleDownFactor = 1f * inactiveLabelSize / activeLabelSize;

        LayoutInflater.from(context).inflate(R.layout.design_bottom_navigation_item, this, true);
        setBackgroundResource(R.drawable.design_bottom_navigation_item_background);
        mIcon = (ImageView) findViewById(R.id.icon);
        mSmallLabel = (TextView) findViewById(R.id.smallLabel);
        mLargeLabel = (TextView) findViewById(R.id.largeLabel);
    }

Can i replace this layout without fork class? Replace design_bottom_navigation_item layout?


问:
Query using subset of path in Postgres
Given this table:

```<code> id |            points (path)                 |
----+------------------------------------------+
  1 | ((1,2),(3,4),(5,6),(7,8))                |
</code>```

Is it possible to achieve the following using a single geometric operator and a path argument (sequential subset of the containing path), like ((3,4),(5,6))?

select * from things where points @> '(3,4)' and points @> '(5,6)';

答:
Maybe just convert it to string and match using LIKE (you need double because the path is closed):

```<code>select points::text  from things
where (points::text || points::text) like '%(3,4),(5,6)%';
</code>```

If you have a lot of things it`s worth to build index for the path, which will be used in the like query (you need trgm extension)

```<code>CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX thing_text_paths ON things USING gin ( (points::text || points::text) gin_trgm_ops);
</code>```

You can see it by running

```<code>SET enable_seqscan = OFF;
EXPLAIN select points::text  from things
where (points::text || points::text) like '%(3,4),(5,6)%';
</code>```

See http://sqlfiddle.com/#!17/bd760/2/0

Title: Query using subset of path in Postgres

Body:
Given this table:

 id |            points (path)                 |
----+------------------------------------------+
  1 | ((1,2),(3,4),(5,6),(7,8))                |

Is it possible to achieve the following using a single geometric operator and a path argument (sequential subset of the containing path), like ((3,4),(5,6))?

select * from things where points @> '(3,4)' and points @> '(5,6)';

Body:
Maybe just convert it to string and match using LIKE (you need double because the path is closed):

select points::text  from things
where (points::text || points::text) like '%(3,4),(5,6)%';

If you have a lot of things it`s worth to build index for the path, which will be used in the like query (you need trgm extension)

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX thing_text_paths ON things USING gin ( (points::text || points::text) gin_trgm_ops);

You can see it by running

SET enable_seqscan = OFF;
EXPLAIN select points::text  from things
where (points::text || points::text) like '%(3,4),(5,6)%';

See http://sqlfiddle.com/#!17/bd760/2/0


问:
jQuery 1.4.2 VSDoc
Where can I get the VSDoc for jQuery 1.4.2?</p>

答:
John T said:

For what it's worth, and from this
  question:

jQuery 1.4.3 vsdoc

Someone has updated the jQuery vsdoc
  for JQuery 1.4.3. It's at:

http://appendto.com/community/vsdoc

@John T: Thanks for the links!

For users of the v1.4.4 VSDOC file supplied here, there is a slight error that breaks IntelliSense; at line 1751 the file reads:

jQuery.proxy = function(function, context){

This causes Visual Studio to show the following error:

Error updating JScript IntelliSense: <your path>\jquery-1.4.4-vsdoc.js: Expected identifier @ 1750:24 (or near enough).

Update this line to read:

jQuery.proxy = function(method, context){

This bug was found and resolved in VS2008.

Title: jQuery 1.4.2 VSDoc


问:
EntityFramework Include and possibly join?
I have the following table structure as shown in the picture. (see: Table structure). Both tables ("Batches" and "Methods") reference to a "Project" table.
When I now create a new Project I would like to get all childs created as well.
Doing so I did the follwoing:

```<code>_dbContext.Projects.Where(x => x.Id == prjId)
            .Include(x => x.Batches)
            .Include(x => x.Batches.Select(y => y.Measurements))
            .Include(x => x.Methods).AsNoTracking().FirstOrDefault();
</code>```

Now the problem is the following:

New Batch and Method instances are created - thus they get a new ID(PK). The referenced Project_Id (FK) is set correct. But in my new Measurement instance only the Batch_Id(FK) is set correct and the Method_Id remains unchanged (has the old value) (see: result).

What I need is that the Measurements.Mehtod_Id is set from the Methods table.
 Is there any suitable solution for that?

My entities look like the following

```<code>public class Project
{
    [Key]
    public long Id { get; set; }

    public string Name { get; set; }
    public bool IsActive { get; set; }
    public virtual List<Batch> Batches { get; set; }
    public virtual List<Method> Methods { get; set; }
}

public class Batch : BaseObject
{
    public Batch()
    {
        BatchFiles = new List<FileAttachment>();
        Measurements = new List<Measurement>();
    }
    public long Id { get; protected set; }
    public long Project_Id { get; set; }
    public virtual Project Project { get; set; }
    public virtual List<Measurement> Measurements { get; set; }
}
public class Method : BaseObject
{
    public Method()
    {
        Parameters = new List<Parameter>();
    }

    public long Id { get; protected set; }
    public long Project_Id { get; set; }
    public virtual Project Project { get; set; }
    public virtual List<Measurement> Measurements { get; set; }
}

public class Measurement
{
    public int Id { get; protected set; }
    [ForeignKey("Batch")]
    public long? Batch_Id { get; set; }
    [Required]
    public virtual Batch Batch { get; set; }
    [ForeignKey("Method")]
    public long? Method_Id { get; set; }
    public virtual Method Method { get; set; }
}

// creation code (just a copy with new IDs for all childs)
Project newProjectVersion = _dbContext.Projects.Where(x => x.Id == prjId)
            .Include(x => x.Batches)
            .Include(x => x.Batches.Select(y => y.Measurements))
            .Include(x => x.Methods)
            .AsNoTracking().FirstOrDefault();
_dbContext.Projects.Add(newProjectVersion);
_dbContext.SaveChanges();
</code>```

Thanks for any help!

答:
The first problem is that your Select statement doesn't connect Measurements to Methods because of the AsNoTracking() addition. Only Projects and Methods are connected because they are explicitly Included off of the Project entity. The Measurements have a Method_id but this is value is not accompanied by a Method in their Method property. You could check that in the debugger if you walk through the object graph (with lazy loading disabled though!). Because of this, when all entities will be Add-ed to the context, EF won't notice that measurements receive new methods.

You could get tempted to fix that by Include-ing Measurement.Method as well:

```<code>...
.Include(x => x.Batches.Select(y => y.Measurements.Select(m => m.Method)))
...
</code>```

Now you'll see that Measurement.Method will be populated everywhere in the object graph.

However, there's a gotcha here. When using AsNoTracking, EF6 doesn't keep track of entities it materialized (duh). This means that for each Measurement it creates a new Method instance, even if an identical Method (by id) was materialized before for another Measurement. (And in this case it will always materialize duplicates, because you already include Project.Methods.)

That's why you can't do this in the quick way with AsNoTracking and Add using one context instance. You'll get an error that EF tries to attach duplicate entities.

You must build the object graph using one context, with tracking, so EF will not materialize duplicates. Then you must Add this object graph to a new context. Which will look like this:

```<code>Project project;

using(var db = new MyContext())
{
    db.Configuration.ProxyCreationEnabled = false;
    project = db.Projects.Where(x => x.Id == prjId)
                .Include(x => x.Batches)
                .Include(x => x.Batches.Select(y => y.Measurements))
                .Include(x => x.Methods).FirstOrDefault();
}

using(var db = new MyContext())
{
    db.Projects.Add(project);
    db.SaveChages();
}
</code>```

Three remarks:

Proxy creation is disabled, because you can't attach a proxy to another context without explicitly detaching it first.

No, I didn't forget to include Measurement.Method. All methods are loaded by including them in the Project and now (because of tracking, and assuming that measurement will only have methods of the project they belong to), EF connects them with the Measurements by relationship fixup.

EF-core is smarter here: when adding AsNoTracking it won't track materialized entities, but still, it won't create duplicates either. It seems to have some temporary tracking during the construction of an object graph.

Body:
I have the following table structure as shown in the picture. (see: Table structure). Both tables ("Batches" and "Methods") reference to a "Project" table.
When I now create a new Project I would like to get all childs created as well.
Doing so I did the follwoing:

_dbContext.Projects.Where(x => x.Id == prjId)
            .Include(x => x.Batches)
            .Include(x => x.Batches.Select(y => y.Measurements))
            .Include(x => x.Methods).AsNoTracking().FirstOrDefault();

Now the problem is the following:

New Batch and Method instances are created - thus they get a new ID(PK). The referenced Project_Id (FK) is set correct. But in my new Measurement instance only the Batch_Id(FK) is set correct and the Method_Id remains unchanged (has the old value) (see: result).

What I need is that the Measurements.Mehtod_Id is set from the Methods table.
 Is there any suitable solution for that?

My entities look like the following

public class Project
{
    [Key]
    public long Id { get; set; }

    public string Name { get; set; }
    public bool IsActive { get; set; }
    public virtual List<Batch> Batches { get; set; }
    public virtual List<Method> Methods { get; set; }
}

public class Batch : BaseObject
{
    public Batch()
    {
        BatchFiles = new List<FileAttachment>();
        Measurements = new List<Measurement>();
    }
    public long Id { get; protected set; }
    public long Project_Id { get; set; }
    public virtual Project Project { get; set; }
    public virtual List<Measurement> Measurements { get; set; }
}
public class Method : BaseObject
{
    public Method()
    {
        Parameters = new List<Parameter>();
    }

    public long Id { get; protected set; }
    public long Project_Id { get; set; }
    public virtual Project Project { get; set; }
    public virtual List<Measurement> Measurements { get; set; }
}

public class Measurement
{
    public int Id { get; protected set; }
    [ForeignKey("Batch")]
    public long? Batch_Id { get; set; }
    [Required]
    public virtual Batch Batch { get; set; }
    [ForeignKey("Method")]
    public long? Method_Id { get; set; }
    public virtual Method Method { get; set; }
}

// creation code (just a copy with new IDs for all childs)
Project newProjectVersion = _dbContext.Projects.Where(x => x.Id == prjId)
            .Include(x => x.Batches)
            .Include(x => x.Batches.Select(y => y.Measurements))
            .Include(x => x.Methods)
            .AsNoTracking().FirstOrDefault();
_dbContext.Projects.Add(newProjectVersion);
_dbContext.SaveChanges();

Thanks for any help!

Body:
The first problem is that your Select statement doesn't connect Measurements to Methods because of the AsNoTracking() addition. Only Projects and Methods are connected because they are explicitly Included off of the Project entity. The Measurements have a Method_id but this is value is not accompanied by a Method in their Method property. You could check that in the debugger if you walk through the object graph (with lazy loading disabled though!). Because of this, when all entities will be Add-ed to the context, EF won't notice that measurements receive new methods.

You could get tempted to fix that by Include-ing Measurement.Method as well:

...
.Include(x => x.Batches.Select(y => y.Measurements.Select(m => m.Method)))
...

Now you'll see that Measurement.Method will be populated everywhere in the object graph.

However, there's a gotcha here. When using AsNoTracking, EF6 doesn't keep track of entities it materialized (duh). This means that for each Measurement it creates a new Method instance, even if an identical Method (by id) was materialized before for another Measurement. (And in this case it will always materialize duplicates, because you already include Project.Methods.)

That's why you can't do this in the quick way with AsNoTracking and Add using one context instance. You'll get an error that EF tries to attach duplicate entities.

You must build the object graph using one context, with tracking, so EF will not materialize duplicates. Then you must Add this object graph to a new context. Which will look like this:

Project project;

using(var db = new MyContext())
{
    db.Configuration.ProxyCreationEnabled = false;
    project = db.Projects.Where(x => x.Id == prjId)
                .Include(x => x.Batches)
                .Include(x => x.Batches.Select(y => y.Measurements))
                .Include(x => x.Methods).FirstOrDefault();
}

using(var db = new MyContext())
{
    db.Projects.Add(project);
    db.SaveChages();
}

Three remarks:

Proxy creation is disabled, because you can't attach a proxy to another context without explicitly detaching it first.

No, I didn't forget to include Measurement.Method. All methods are loaded by including them in the Project and now (because of tracking, and assuming that measurement will only have methods of the project they belong to), EF connects them with the Measurements by relationship fixup.

EF-core is smarter here: when adding AsNoTracking it won't track materialized entities, but still, it won't create duplicates either. It seems to have some temporary tracking during the construction of an object graph.


问:
Amazon web services iOS
I'm trying to set up an Xcode application with Amazon web service. When I put the frameworks from the downloaded SDK into the project, I get multiple Apple Mach-O Linker Errors. Am I possibly doing something wrong while adding them to the project that gives me these errors? Or do I need to be doing something with them in my code to prevent these errors?</p>

答:
Try to generate a iOS app skeleton with Mobile Hub.

AWS Mobile Hub guides you through feature selection and configuration, automatically provisions the AWS services required, and generates working code that helps you integrate the Mobile SDK with your app in minutes.

Title: Amazon web services iOS


问:
How to get process pid in gjs?
What I really want to do is call getpid(), but there doesn't seem to be any sane way to do that in gjs. The best I've been able to come up with is:

// There's got to be a better way to get our pid in gjs?
let credentials = new Gio.Credentials();
let pid = credentials.get_unix_pid();

And that works, but it's horrible. Is there a better way?

答:
There is currently no other way than that.

Ideas for future versions of GJS include a process object compatible with the one in Node.

Title: How to get process pid in gjs?