问:
Database design, one2many, bidirectional dependency between tables
I'm working on lending system.
I have 2 tables. Loan and Tool. One loan can have more tools on it.

```<code>public class Loan
{
    [Key]
    public int LoanId { get; set; }

    [Required]
    public DateTime WhenBorrowed { get; set; }

    public DateTime? WhenReturned { get; set; }

    // foreign key to Tool
    public virtual ICollection<Tool> Tools { get; set; }
}

public class Tool
{
    // Primary key
    public int ToolId { get; set; }

    [Required]
    public string Name { get; set; }

    // foreign key to Loan
    public int? LoanId { get; set; }
    public virtual Loan Loan { get; set; }
}
</code>```

I want to ask questions like:

Tools availability - borrowed/not borrowed.

I solved this by using LoanId in Tool table, checking if it's null or not.

History of transactions

And here I have a problem. That icollections seems to contain only foreign keys to Tool table. So when I set LoanId back to null(to indicate that the tool was returned and can be borrowed again) I lose the history.
How should I solve this. Should I define another foreign key also in Loan table? Like this:

```<code>// foreign key to Tool
public IList<int> ToolId { get; set; }
public virtual Tool Tool { get; set; }
</code>```

It seems like circular dependencies in foreign keys to me. What is the right way to achieve needed functionality?

Thanks for any suggestions.

答:
Loan model:

```<code>public class Loan
{
    [Key]
    public int LoanId { get; set; }

    [Required]
    public DateTime WhenBorrowed { get; set; }

    public DateTime? WhenReturned { get; set; }

    // foreign key to Tool
    public virtual ICollection<LoanHistory> History { get; set; }
}
</code>```

LoanHistory model:

```<code>public class LoanHistory
{
    // foreign key to Tool
    public int ToolId { get; set; }
    public virtual Tool { get; set; }

    // foreign key to Loan
    public int LoanId { get; set; }
    public virtual Loan Loan { get; set; }
}
</code>```

Tool model:

```<code>public class Tool
{
    // Primary key
    public int ToolId { get; set; }

    [Required]
    public string Name { get; set; }

    public bool IsAvailable { get; set; }
}
</code>```

This way you keep the loan history.

To check the tools simply as that:

```<code>var AvailableTools = db.Tools
    .Where(p => p.IsAvailable == true)
    .ToList();
</code>```

Also is worth mentioning that you need to update the tools IsAvailable property when making a new loan or returning one.

Body:
I'm working on lending system.
I have 2 tables. Loan and Tool. One loan can have more tools on it.

public class Loan
{
    [Key]
    public int LoanId { get; set; }

    [Required]
    public DateTime WhenBorrowed { get; set; }

    public DateTime? WhenReturned { get; set; }

    // foreign key to Tool
    public virtual ICollection<Tool> Tools { get; set; }
}

public class Tool
{
    // Primary key
    public int ToolId { get; set; }

    [Required]
    public string Name { get; set; }

    // foreign key to Loan
    public int? LoanId { get; set; }
    public virtual Loan Loan { get; set; }
}

I want to ask questions like:

Tools availability - borrowed/not borrowed.

I solved this by using LoanId in Tool table, checking if it's null or not.

History of transactions

And here I have a problem. That icollections seems to contain only foreign keys to Tool table. So when I set LoanId back to null(to indicate that the tool was returned and can be borrowed again) I lose the history.
How should I solve this. Should I define another foreign key also in Loan table? Like this:

// foreign key to Tool
public IList<int> ToolId { get; set; }
public virtual Tool Tool { get; set; }

It seems like circular dependencies in foreign keys to me. What is the right way to achieve needed functionality?

Thanks for any suggestions.

Body:
Loan model:

public class Loan
{
    [Key]
    public int LoanId { get; set; }

    [Required]
    public DateTime WhenBorrowed { get; set; }

    public DateTime? WhenReturned { get; set; }

    // foreign key to Tool
    public virtual ICollection<LoanHistory> History { get; set; }
}

LoanHistory model:

public class LoanHistory
{
    // foreign key to Tool
    public int ToolId { get; set; }
    public virtual Tool { get; set; }

    // foreign key to Loan
    public int LoanId { get; set; }
    public virtual Loan Loan { get; set; }
}

Tool model:

public class Tool
{
    // Primary key
    public int ToolId { get; set; }

    [Required]
    public string Name { get; set; }

    public bool IsAvailable { get; set; }
}

This way you keep the loan history.

To check the tools simply as that:

var AvailableTools = db.Tools
    .Where(p => p.IsAvailable == true)
    .ToList();

Also is worth mentioning that you need to update the tools IsAvailable property when making a new loan or returning one.


来源: stackexchange

问:
AWS: Is there a way to make an user approve my app to do things on their behalf?
I am planning on a web page that creates an instance for an user using a specific AMI. Is there any AWS method to let the user approve my web application to do this using their credentials? (i. e. getting a secret token with certain privileges)

Similar to when you let a Facebook application have access to certain information of your profile. I am looking for a way to get a token from the user signed in so that I can create an instance for them.

I want to avoid the user the pain of doing all the manual steps of going to IAM, create a new user, get the token and then upload them to my site.

I looked into AWS Cognito but this doesn't seem to be what I am looking for.

答:
Similar to when you let a Facebook application have access to certain information of your profile.

AWS and Facebook are not similar in any sense.  Facebook is a web application.  AWS something entirely different.

Facebook has users, but AWS has accounts, which in turn have users... but in AWS, don't need a user's permission to do things to resources -- what you actually need is an account's permission to do things to its resources, because resources are associated with the account, not the user.

I am looking for a way to get a token from the user signed in so that I can create an instance for them.

Users sign in to the AWS console.  After this, there is no such concept as a user allowing an external application doing things under the "signed in" user's auspices.

The user has to have sufficient permissions to either create sufficiently-privileged temporary IAM credentials (such as with GetSessionToken or AssumeRole from the IAM API) and hand them over to you, or create an IAM user with sufficient privilege and hand the keys to that user over to you... or you provide them with the ARN of one of your IAM users, and your customer gives your user permission to perform the actions or assume a role in your customer's account, created for the purpose.

I want to avoid the user the pain of doing all the manual steps of going to IAM, create a new user, get the token and then upload them to my site.

That can't be avoided, by design... and, in any event, whatever exactly you are planning, your model seems flawed: it would only be a naïve user who would allow you to do this.  I have accounts that are allowed to launch hundreds of instances concurrently.  Does it make sense that I would allow a third party to have access to credentials that could run up a huge bill for me?  (If AWS trusts a set of credentials to launch instances, then it trusts them to launch instances -- all the way up to the account's instance limits).

If you want a user to be able to launch an instance from your AMI, you can simply list it on the AWS Marketplace, or you can share the AMI with the user's account, or even just make the AMI public.

ContentLicense: CC BY-SA 3.0


问:
Javascript date toISOSstring/toJSON one day backwards
I store two dates. First date is the current day and the second one is a future date. To convert those dates into format year-month-day I use toISOSstring function. However usually (but not always) the current date is changed one day backwards.

I also tried to use toJSON function instead. But nothing has changed.

```<code>    season.from =  "Sun Apr 02 2017 18:29:52 GMT+0200 (CEST)"
    season.to =   "Fri Apr 21 2017 18:29:52 GMT+0200 (CEST)"

    var date1 = new Date(season.from);
    var date2 = new Date(season.to);

    season.from = date1.toISOString().slice(0,10);
    season.to = date2.toISOString().slice(0,10);
    console.log(season.from); // one day backwards (e.g. 2017-04-01 not 2017-04-02)
    console.log(season.to); // proper date somewhere in the future
</code>```

答:
Your original time strings are in local time, or at least they have a time zone specification. But toISOString returns the UTC time:

The timezone is always zero UTC offset, as denoted by the suffix "Z"

In the case of your GMT+02 time zone, this means the date/time returned by toISOString is two hours "earlier" than the local time. In some cases this can be a time before midnight, and this can render a different date as well.

The implementation of the toJSON method depends on toISOString, so it has the same behaviour.

Work-around

You could use toLocaleDateString('se'), which uses your local time, and formats according to Swedish standards, i.e. YYYY-MM-DD, so you don't even need to slice it. There are some other country codes you could specify to have the same.

Body:
I store two dates. First date is the current day and the second one is a future date. To convert those dates into format year-month-day I use toISOSstring function. However usually (but not always) the current date is changed one day backwards.

I also tried to use toJSON function instead. But nothing has changed.

    season.from =  "Sun Apr 02 2017 18:29:52 GMT+0200 (CEST)"
    season.to =   "Fri Apr 21 2017 18:29:52 GMT+0200 (CEST)"

    var date1 = new Date(season.from);
    var date2 = new Date(season.to);

    season.from = date1.toISOString().slice(0,10);
    season.to = date2.toISOString().slice(0,10);
    console.log(season.from); // one day backwards (e.g. 2017-04-01 not 2017-04-02)
    console.log(season.to); // proper date somewhere in the future


问:
How to visualize QImage in QML
I have a QAbstractListModel with custom objects as items. Each object has a QImage that is loaded from a database. I use ListView in QML to visualize it but I do not see any mean to represent QImage in the delegate. Image primitive seems to accept only URLs.

Is the only way for me to show QImages is to create a QQuickImageProvider with some custom system of a URL per element (looks like a total overkill)?

答: A QML ShaderEffect will bind a QImage to a GLSL Sampler2D.  See the list of "how properties are mapped to GLSL uniform variables" in the ShaderEffect docs. Needs a few lines of GLSL writing in the ShaderEffect to pass pixels through, (will update this post with an example sometime, when I have access to my code), but the result is a fast, QSG-friendly all-QML element which can render QImages.  </p>

Title: How to visualize QImage in QML


问:
make wordpress menu sticky on scroll
Hello i am trying to make a wordpress menu sticky on scroll.

In practicality this is what i mean

http://dev.thegabrielmethod.com/   is the main menu which isnt sticky for now

https://www.thegabrielmethod.com/ this is how i want the menu to be on scroll, please check both links

This i what iv been able to do

```<code>http://dev.thegabrielmethod.com/gabriel/
</code>```

using

```<code>.banner {
padding: 30px 50px;
}
.banner {
position: fixed;
width: 100%;
top: 0;
left: 0;
border-top: 0px solid #ffffff;
border-bottom: 0px solid #ffffff;
background: #fff;
vertical-align: top;
-webkit-box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
z-index: 999999;
}

.nav-bar-below.op-page-header {
margin-top : 100px;
    position: fixed;
    width: 100%;
    background: #155b9b;
    background: -moz-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#155b9b),color-stop(100%,#155b9b));
    background: -webkit-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -o-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -ms-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: linear-gradient(top,#155b9b 0%,#155b9b 100%));
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#155b9b', endColorstr='#155b9b',GradientType=0 );
}
.op-page-header .navigation a {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    font-weight: 500;
    font-size: 13px;
    line-height: 19px;
    text-shadow: 0 1px 1px rgba(249, 249, 249, 0), 0 1px 1px rgba(0,0,0,.5)!important;
    text-rendering: optimizelegibility;
}
</code>```

which does not give the kind of look on scroll as this

```<code>https://www.thegabrielmethod.com/
</code>```

Can someone please help

答:
Here's the working jsfiddle: https://jsfiddle.net/cyp8ngck/1/

Okay, so here's what i did.

I Created 2 different menus:

1. A normal menu that will be scrolled along with the page.

2. A sticky menu that will be displayed when the normal menu is scrolled outside the viewport and is no longer visible.

CSS for both menu types will is as follows:

```<code>/* common CSS styling for both menus to keep the code clean */
    .menu, .sticky-menu {
      display: block;
      text-align: center;
      font-size: 22px;
      font-weight: bold;
      background: #2e2e2e;
      color: #ffffff;
      padding: 15px 0px;
    }

/* code for the sticky menu only */
    .sticky-menu {
      background: #cccccc;
      color: #2e2e2e;
      position: fixed;
      z-index: 9999;
      left:0;
      right:0;
      top:0;
      transform: translateY(-100%);
      transition: all .3s ease;
    }
</code>```

As you can see the sticky menu is pulled outside the viewport window and is kept hidden until the page is scrolled and the normal is hidden.

Now i just toggled this CSS class with the sticky menu:
(It pulls down and pulls up the Sticky Menu)

```<code>.pull-sticky-menu {
  transform: translateY(0%);
  transition: all .3s ease;
}
</code>```

by detecting if the menu height in jQuery:

```<code>$(document).scroll(function() {
  var scrollheight = $(this).scrollTop();
  var menuheight = $(".menu").height();
  if (scrollheight > menuheight) {
    $('.sticky-menu').addClass("pull-sticky-menu");
  } else {
    $('.sticky-menu').removeClass("pull-sticky-menu");
  }
});
</code>```

Here's the code snippet:

$(document).scroll(function() {
  var scrollheight = $(this).scrollTop();
  var menuheight = $(".menu").height();
  if (scrollheight > menuheight) {
    $('.sticky-menu').addClass("pull-sticky-menu");
  } else {
    $('.sticky-menu').removeClass("pull-sticky-menu");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: 16px;
}

.container {
  background: #ffffff;
}

.menu,
.sticky-menu {
  display: block;
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  background: #2e2e2e;
  color: #ffffff;
  padding: 15px 0px;
}

.sticky-menu {
  background: #cccccc;
  color: #2e2e2e;
  position: fixed;
  z-index: 9999;
  left: 0;
  right: 0;
  top: 0;
  transform: translateY(-100%);
  transition: all .3s ease;
}

.pull-sticky-menu {
  transform: translateY(0%);
  transition: all .3s ease;
}</code>```

    THIS IS STICKY MENU

    THIS IS NORMAL MENU

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis accumsan massa, id scelerisque elit. Morbi vel arcu accumsan, facilisis magna quis, accumsan ex. Cras congue enim aliquam, accumsan nulla tincidunt, dapibus justo. Phasellus nec pellentesque
    est. Morbi rutrum lectus libero, quis imperdiet turpis ultricies ut. Etiam pharetra dictum dui sit amet iaculis. Curabitur rhoncus gravida augue, dapibus semper nisl rutrum sed. Etiam facilisis lacus eget ullamcorper molestie. Duis vestibulum tortor
    lorem, sed auctor tellus efficitur id.

    Maecenas dapibus erat ac erat vehicula, nec iaculis dui faucibus. Mauris non gravida nunc. Duis eget leo sit amet sapien dictum tempus eu eget enim. Ut eu est vel nibh dictum malesuada in a metus. Sed finibus mollis ipsum, scelerisque maximus mauris blandit
    non. Aenean vel urna nisl. Ut facilisis nibh dolor, non malesuada felis facilisis eu. Maecenas ut neque quis purus rutrum pharetra sed id mauris. Ut eu ex eu turpis tincidunt placerat accumsan sed elit. Duis egestas, lectus et euismod tempor, nunc
    nibh convallis lectus, fringilla tincidunt odio augue a mauris. Aliquam ultrices arcu et orci laoreet, in congue magna gravida. Mauris posuere quis justo eu egestas.

    Praesent vehicula venenatis felis vel semper. Aenean pharetra dictum augue, laoreet scelerisque leo euismod vel. Aliquam scelerisque eleifend eleifend. Pellentesque a felis quis diam fringilla cursus at ac nibh. Etiam tellus lectus, vehicula non risus
    in, pellentesque tincidunt quam. Integer elit magna, euismod sit amet lorem quis, facilisis consectetur metus. Aliquam dictum ante quis laoreet congue. Morbi hendrerit posuere faucibus. Aliquam augue est, faucibus quis consequat in, pretium tincidunt
    libero. Fusce vulputate aliquam turpis eu sollicitudin. Nam accumsan eget nulla ut molestie. Morbi turpis felis, egestas eget velit et, fringilla sodales est.

    Duis vel velit quis metus efficitur luctus. Proin porttitor sapien eget diam fringilla mollis. Curabitur interdum efficitur enim, laoreet bibendum dui aliquet vitae. Etiam arcu ipsum, condimentum nec scelerisque vitae, ornare at justo. Duis eget tincidunt
    sapien. Quisque non arcu volutpat, lacinia sem id, volutpat tellus. Vivamus dui lorem, aliquam non iaculis posuere, euismod et velit. Vestibulum nunc mauris, pharetra porta nisi eu, convallis molestie massa. Donec tincidunt tempus egestas. Sed lectus
    sem, vestibulum at felis et, finibus egestas sem.

    Nulla auctor, quam sed efficitur tempor, felis justo egestas justo, ac bibendum sem ante eu nisi. Aliquam erat volutpat. Suspendisse turpis ante, dapibus in purus et, aliquet rutrum arcu. Suspendisse sem massa, ultrices sed felis vel, mollis porta nisl.
    Curabitur lectus urna, porta eu placerat id, tempor eget erat. Duis mattis eget nisi et bibendum. Aliquam nibh libero, elementum et leo nec, egestas vestibulum lacus. Suspendisse vel augue diam. Phasellus fermentum, quam sed euismod finibus, erat
    ante fermentum mi, at ullamcorper nisi sapien quis orci. Morbi id sem tincidunt, semper eros non, facilisis velit. Nam tincidunt neque ullamcorper, tristique justo quis, dapibus nunc. In in pharetra enim.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis accumsan massa, id scelerisque elit. Morbi vel arcu accumsan, facilisis magna quis, accumsan ex. Cras congue enim aliquam, accumsan nulla tincidunt, dapibus justo. Phasellus nec pellentesque
    est. Morbi rutrum lectus libero, quis imperdiet turpis ultricies ut. Etiam pharetra dictum dui sit amet iaculis. Curabitur rhoncus gravida augue, dapibus semper nisl rutrum sed. Etiam facilisis lacus eget ullamcorper molestie. Duis vestibulum tortor
    lorem, sed auctor tellus efficitur id.

    Maecenas dapibus erat ac erat vehicula, nec iaculis dui faucibus. Mauris non gravida nunc. Duis eget leo sit amet sapien dictum tempus eu eget enim. Ut eu est vel nibh dictum malesuada in a metus. Sed finibus mollis ipsum, scelerisque maximus mauris blandit
    non. Aenean vel urna nisl. Ut facilisis nibh dolor, non malesuada felis facilisis eu. Maecenas ut neque quis purus rutrum pharetra sed id mauris. Ut eu ex eu turpis tincidunt placerat accumsan sed elit. Duis egestas, lectus et euismod tempor, nunc
    nibh convallis lectus, fringilla tincidunt odio augue a mauris. Aliquam ultrices arcu et orci laoreet, in congue magna gravida. Mauris posuere quis justo eu egestas.

    Praesent vehicula venenatis felis vel semper. Aenean pharetra dictum augue, laoreet scelerisque leo euismod vel. Aliquam scelerisque eleifend eleifend. Pellentesque a felis quis diam fringilla cursus at ac nibh. Etiam tellus lectus, vehicula non risus
    in, pellentesque tincidunt quam. Integer elit magna, euismod sit amet lorem quis, facilisis consectetur metus. Aliquam dictum ante quis laoreet congue. Morbi hendrerit posuere faucibus. Aliquam augue est, faucibus quis consequat in, pretium tincidunt
    libero. Fusce vulputate aliquam turpis eu sollicitudin. Nam accumsan eget nulla ut molestie. Morbi turpis felis, egestas eget velit et, fringilla sodales est.

    Duis vel velit quis metus efficitur luctus. Proin porttitor sapien eget diam fringilla mollis. Curabitur interdum efficitur enim, laoreet bibendum dui aliquet vitae. Etiam arcu ipsum, condimentum nec scelerisque vitae, ornare at justo. Duis eget tincidunt
    sapien. Quisque non arcu volutpat, lacinia sem id, volutpat tellus. Vivamus dui lorem, aliquam non iaculis posuere, euismod et velit. Vestibulum nunc mauris, pharetra porta nisi eu, convallis molestie massa. Donec tincidunt tempus egestas. Sed lectus
    sem, vestibulum at felis et, finibus egestas sem.

    Nulla auctor, quam sed efficitur tempor, felis justo egestas justo, ac bibendum sem ante eu nisi. Aliquam erat volutpat. Suspendisse turpis ante, dapibus in purus et, aliquet rutrum arcu. Suspendisse sem massa, ultrices sed felis vel, mollis porta nisl.
    Curabitur lectus urna, porta eu placerat id, tempor eget erat. Duis mattis eget nisi et bibendum. Aliquam nibh libero, elementum et leo nec, egestas vestibulum lacus. Suspendisse vel augue diam. Phasellus fermentum, quam sed euismod finibus, erat
    ante fermentum mi, at ullamcorper nisi sapien quis orci. Morbi id sem tincidunt, semper eros non, facilisis velit. Nam tincidunt neque ullamcorper, tristique justo quis, dapibus nunc. In in pharetra enim.

```

Let me know if this helps :)

Title: make wordpress menu sticky on scroll

Body:
Hello i am trying to make a wordpress menu sticky on scroll.

In practicality this is what i mean

http://dev.thegabrielmethod.com/   is the main menu which isnt sticky for now

https://www.thegabrielmethod.com/ this is how i want the menu to be on scroll, please check both links

This i what iv been able to do

http://dev.thegabrielmethod.com/gabriel/

using

.banner {
padding: 30px 50px;
}
.banner {
position: fixed;
width: 100%;
top: 0;
left: 0;
border-top: 0px solid #ffffff;
border-bottom: 0px solid #ffffff;
background: #fff;
vertical-align: top;
-webkit-box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
-moz-box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
box-shadow: 0px 4px 22px 0px rgba(50, 50, 50, 0.75);
z-index: 999999;
}

.nav-bar-below.op-page-header {
margin-top : 100px;
    position: fixed;
    width: 100%;
    background: #155b9b;
    background: -moz-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#155b9b),color-stop(100%,#155b9b));
    background: -webkit-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -o-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: -ms-linear-gradient(top,#155b9b 0%,#155b9b 100%);
    background: linear-gradient(top,#155b9b 0%,#155b9b 100%));
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#155b9b', endColorstr='#155b9b',GradientType=0 );
}
.op-page-header .navigation a {
    font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
    font-weight: 500;
    font-size: 13px;
    line-height: 19px;
    text-shadow: 0 1px 1px rgba(249, 249, 249, 0), 0 1px 1px rgba(0,0,0,.5)!important;
    text-rendering: optimizelegibility;
}

which does not give the kind of look on scroll as this

https://www.thegabrielmethod.com/

Can someone please help

Body:
Here's the working jsfiddle: https://jsfiddle.net/cyp8ngck/1/

Okay, so here's what i did.

I Created 2 different menus:

1. A normal menu that will be scrolled along with the page.

2. A sticky menu that will be displayed when the normal menu is scrolled outside the viewport and is no longer visible.

CSS for both menu types will is as follows:

/* common CSS styling for both menus to keep the code clean */
    .menu, .sticky-menu {
      display: block;
      text-align: center;
      font-size: 22px;
      font-weight: bold;
      background: #2e2e2e;
      color: #ffffff;
      padding: 15px 0px;
    }

/* code for the sticky menu only */
    .sticky-menu {
      background: #cccccc;
      color: #2e2e2e;
      position: fixed;
      z-index: 9999;
      left:0;
      right:0;
      top:0;
      transform: translateY(-100%);
      transition: all .3s ease;
    }

As you can see the sticky menu is pulled outside the viewport window and is kept hidden until the page is scrolled and the normal is hidden.

Now i just toggled this CSS class with the sticky menu:
(It pulls down and pulls up the Sticky Menu)

.pull-sticky-menu {
  transform: translateY(0%);
  transition: all .3s ease;
}

by detecting if the menu height in jQuery:

$(document).scroll(function() {
  var scrollheight = $(this).scrollTop();
  var menuheight = $(".menu").height();
  if (scrollheight > menuheight) {
    $('.sticky-menu').addClass("pull-sticky-menu");
  } else {
    $('.sticky-menu').removeClass("pull-sticky-menu");
  }
});

Here's the code snippet:

$(document).scroll(function() {
  var scrollheight = $(this).scrollTop();
  var menuheight = $(".menu").height();
  if (scrollheight > menuheight) {
    $('.sticky-menu').addClass("pull-sticky-menu");
  } else {
    $('.sticky-menu').removeClass("pull-sticky-menu");
  }
});

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  font-size: 16px;
}

.container {
  background: #ffffff;
}

.menu,
.sticky-menu {
  display: block;
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  background: #2e2e2e;
  color: #ffffff;
  padding: 15px 0px;
}

.sticky-menu {
  background: #cccccc;
  color: #2e2e2e;
  position: fixed;
  z-index: 9999;
  left: 0;
  right: 0;
  top: 0;
  transform: translateY(-100%);
  transition: all .3s ease;
}

.pull-sticky-menu {
  transform: translateY(0%);
  transition: all .3s ease;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="sticky-menu">
    THIS IS STICKY MENU
  </div>

  <div class="menu">
    THIS IS NORMAL MENU
  </div>

  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis accumsan massa, id scelerisque elit. Morbi vel arcu accumsan, facilisis magna quis, accumsan ex. Cras congue enim aliquam, accumsan nulla tincidunt, dapibus justo. Phasellus nec pellentesque
    est. Morbi rutrum lectus libero, quis imperdiet turpis ultricies ut. Etiam pharetra dictum dui sit amet iaculis. Curabitur rhoncus gravida augue, dapibus semper nisl rutrum sed. Etiam facilisis lacus eget ullamcorper molestie. Duis vestibulum tortor
    lorem, sed auctor tellus efficitur id.
  </p>

  <p>
    Maecenas dapibus erat ac erat vehicula, nec iaculis dui faucibus. Mauris non gravida nunc. Duis eget leo sit amet sapien dictum tempus eu eget enim. Ut eu est vel nibh dictum malesuada in a metus. Sed finibus mollis ipsum, scelerisque maximus mauris blandit
    non. Aenean vel urna nisl. Ut facilisis nibh dolor, non malesuada felis facilisis eu. Maecenas ut neque quis purus rutrum pharetra sed id mauris. Ut eu ex eu turpis tincidunt placerat accumsan sed elit. Duis egestas, lectus et euismod tempor, nunc
    nibh convallis lectus, fringilla tincidunt odio augue a mauris. Aliquam ultrices arcu et orci laoreet, in congue magna gravida. Mauris posuere quis justo eu egestas.
  </p>

  <p>
    Praesent vehicula venenatis felis vel semper. Aenean pharetra dictum augue, laoreet scelerisque leo euismod vel. Aliquam scelerisque eleifend eleifend. Pellentesque a felis quis diam fringilla cursus at ac nibh. Etiam tellus lectus, vehicula non risus
    in, pellentesque tincidunt quam. Integer elit magna, euismod sit amet lorem quis, facilisis consectetur metus. Aliquam dictum ante quis laoreet congue. Morbi hendrerit posuere faucibus. Aliquam augue est, faucibus quis consequat in, pretium tincidunt
    libero. Fusce vulputate aliquam turpis eu sollicitudin. Nam accumsan eget nulla ut molestie. Morbi turpis felis, egestas eget velit et, fringilla sodales est.
  </p>

  <p>
    Duis vel velit quis metus efficitur luctus. Proin porttitor sapien eget diam fringilla mollis. Curabitur interdum efficitur enim, laoreet bibendum dui aliquet vitae. Etiam arcu ipsum, condimentum nec scelerisque vitae, ornare at justo. Duis eget tincidunt
    sapien. Quisque non arcu volutpat, lacinia sem id, volutpat tellus. Vivamus dui lorem, aliquam non iaculis posuere, euismod et velit. Vestibulum nunc mauris, pharetra porta nisi eu, convallis molestie massa. Donec tincidunt tempus egestas. Sed lectus
    sem, vestibulum at felis et, finibus egestas sem.
  </p>

  <p>
    Nulla auctor, quam sed efficitur tempor, felis justo egestas justo, ac bibendum sem ante eu nisi. Aliquam erat volutpat. Suspendisse turpis ante, dapibus in purus et, aliquet rutrum arcu. Suspendisse sem massa, ultrices sed felis vel, mollis porta nisl.
    Curabitur lectus urna, porta eu placerat id, tempor eget erat. Duis mattis eget nisi et bibendum. Aliquam nibh libero, elementum et leo nec, egestas vestibulum lacus. Suspendisse vel augue diam. Phasellus fermentum, quam sed euismod finibus, erat
    ante fermentum mi, at ullamcorper nisi sapien quis orci. Morbi id sem tincidunt, semper eros non, facilisis velit. Nam tincidunt neque ullamcorper, tristique justo quis, dapibus nunc. In in pharetra enim.
  </p>

  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis accumsan massa, id scelerisque elit. Morbi vel arcu accumsan, facilisis magna quis, accumsan ex. Cras congue enim aliquam, accumsan nulla tincidunt, dapibus justo. Phasellus nec pellentesque
    est. Morbi rutrum lectus libero, quis imperdiet turpis ultricies ut. Etiam pharetra dictum dui sit amet iaculis. Curabitur rhoncus gravida augue, dapibus semper nisl rutrum sed. Etiam facilisis lacus eget ullamcorper molestie. Duis vestibulum tortor
    lorem, sed auctor tellus efficitur id.
  </p>

  <p>
    Maecenas dapibus erat ac erat vehicula, nec iaculis dui faucibus. Mauris non gravida nunc. Duis eget leo sit amet sapien dictum tempus eu eget enim. Ut eu est vel nibh dictum malesuada in a metus. Sed finibus mollis ipsum, scelerisque maximus mauris blandit
    non. Aenean vel urna nisl. Ut facilisis nibh dolor, non malesuada felis facilisis eu. Maecenas ut neque quis purus rutrum pharetra sed id mauris. Ut eu ex eu turpis tincidunt placerat accumsan sed elit. Duis egestas, lectus et euismod tempor, nunc
    nibh convallis lectus, fringilla tincidunt odio augue a mauris. Aliquam ultrices arcu et orci laoreet, in congue magna gravida. Mauris posuere quis justo eu egestas.
  </p>

  <p>
    Praesent vehicula venenatis felis vel semper. Aenean pharetra dictum augue, laoreet scelerisque leo euismod vel. Aliquam scelerisque eleifend eleifend. Pellentesque a felis quis diam fringilla cursus at ac nibh. Etiam tellus lectus, vehicula non risus
    in, pellentesque tincidunt quam. Integer elit magna, euismod sit amet lorem quis, facilisis consectetur metus. Aliquam dictum ante quis laoreet congue. Morbi hendrerit posuere faucibus. Aliquam augue est, faucibus quis consequat in, pretium tincidunt
    libero. Fusce vulputate aliquam turpis eu sollicitudin. Nam accumsan eget nulla ut molestie. Morbi turpis felis, egestas eget velit et, fringilla sodales est.
  </p>

  <p>
    Duis vel velit quis metus efficitur luctus. Proin porttitor sapien eget diam fringilla mollis. Curabitur interdum efficitur enim, laoreet bibendum dui aliquet vitae. Etiam arcu ipsum, condimentum nec scelerisque vitae, ornare at justo. Duis eget tincidunt
    sapien. Quisque non arcu volutpat, lacinia sem id, volutpat tellus. Vivamus dui lorem, aliquam non iaculis posuere, euismod et velit. Vestibulum nunc mauris, pharetra porta nisi eu, convallis molestie massa. Donec tincidunt tempus egestas. Sed lectus
    sem, vestibulum at felis et, finibus egestas sem.
  </p>

  <p>
    Nulla auctor, quam sed efficitur tempor, felis justo egestas justo, ac bibendum sem ante eu nisi. Aliquam erat volutpat. Suspendisse turpis ante, dapibus in purus et, aliquet rutrum arcu. Suspendisse sem massa, ultrices sed felis vel, mollis porta nisl.
    Curabitur lectus urna, porta eu placerat id, tempor eget erat. Duis mattis eget nisi et bibendum. Aliquam nibh libero, elementum et leo nec, egestas vestibulum lacus. Suspendisse vel augue diam. Phasellus fermentum, quam sed euismod finibus, erat
    ante fermentum mi, at ullamcorper nisi sapien quis orci. Morbi id sem tincidunt, semper eros non, facilisis velit. Nam tincidunt neque ullamcorper, tristique justo quis, dapibus nunc. In in pharetra enim.
  </p>

</div>

Let me know if this helps :)


问:
.htaccess: remove html extension, force www and https
I developed a simple and pure html site with this pages:

```<code>index.html
page1.html
page2.html
etc
</code>```

And I would like to configure .htaccess to:

```<code>-Force https
-Force www
-Remove .html extension (/page1.html -> /page1)
-Redirect index.html -> /
-When someone types /page1.html to be redirected to /page1 (without html) or (if not possible) to 404 error page
</code>```

How should I configure my .htaccess?

Thanks in advance

答:
```<code>#OK we force https and www
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.exmple.com/$1 [L,R=301]

#  remove .html from uri
RewriteRule ^([^\.]+)$ $1.html [NC,L]

# remove trailing slashes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# redirect index.html -> /
RewriteCond %{REQUEST_URI} \.html$
Redirect /index.html /
</code>```

All seems to work except when I enter example.com/page1.html. It doesn't remove html

Body:
I developed a simple and pure html site with this pages:

index.html
page1.html
page2.html
etc

And I would like to configure .htaccess to:

-Force https
-Force www
-Remove .html extension (/page1.html -> /page1)
-Redirect index.html -> /
-When someone types /page1.html to be redirected to /page1 (without html) or (if not possible) to 404 error page

How should I configure my .htaccess?

Thanks in advance

Body:
#OK we force https and www
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.exmple.com/$1 [L,R=301]

#  remove .html from uri
RewriteRule ^([^\.]+)$ $1.html [NC,L]

# remove trailing slashes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# redirect index.html -> /
RewriteCond %{REQUEST_URI} \.html$
Redirect /index.html /

All seems to work except when I enter example.com/page1.html. It doesn't remove html


问:
How do I implement a simple undo/redo for actions in java?
I've created an XML editor and I'm stuck at the last phase: adding undo/redo functionality.

I've only got to add undo/redo for when users add elements, attributes, or text to the JTree.

I'm still quite new at this but in school today I attempted (unsuccessfully) to create two stack object []'s called undo and redo and to add the actions performed into them.

For instance, I have:

```<code>Action AddElement() {

// some code
public void actionPerformed(ActionEvent e) {

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

the performElementAction just actually adds an Element to the JTree.

I want to add a way to add this action performed to my undo stack.  is there a simple way to just undo.push(  the entire action performed) or something?

答:
TL;DR: You can support undo and redo actions by implementing the Command (p.233) and Memento (p.283) patterns (Design Patterns - Gamma et. al).

The Memento Pattern

This simple pattern allows you to save the states of an object. Simply wrap the object in a new class and whenever its state changes, update it.

public class Memento
{
    MyObject myObject;

    public MyObject getState()
    {
        return myObject;
    }

    public void setState(MyObject myObject)
    {
        this.myObject = myObject;
    }
}
```
<p><strong>The Command Pattern</strong></p>
<p>The Command pattern stores the original object (that we want to support undo/redo) and the memento object, which we need in case of an undo. Moreover, 2 methods are defined:</p>
<ol>
<li><em>execute</em>: executes the command</li>
<li><em>unExecute</em>: removes the command</li>
</ol>
<p>Code:</p>
<pre class="lang-java prettyprint-override"><code>public abstract class Command
{
    MyObject myObject;
    Memento memento;

    public abstract void execute();

    public abstract void unExecute();
}
</code>```

They define the logical "Actions" that extend Command (e.g. Insert):

```<code>public class InsertCharacterCommand extends Command
{
    //members..

    public InsertCharacterCommand()
    {
        //instantiate
    }

    @Override public void execute()
    {
        //create Memento before executing
        //set new state
    }

    @Override public void unExecute()
    {
        this.myObject = memento.getState()l
    }
}
</code>```

Applying the patterns:

This last step defines the undo/redo behavior. The core idea is to store a stack of commands that works as a history list of the commands. To support redo, you can keep a secondary pointer whenever an undo command is applied. Note that whenever a new object is inserted, then all the commands after its current position get removed; that's achieved by the deleteElementsAfterPointer method defined below:

private int undoRedoPointer = -1;
private Stack<Command> commandStack = new Stack<>();

private void insertCommand()
{
    deleteElementsAfterPointer(undoRedoPointer);
    Command command =
            new InsertCharacterCommand();
    command.execute();
    commandStack.push(command);
    undoRedoPointer++;
}

private void deleteElementsAfterPointer(int undoRedoPointer)
{
    if(commandStack.size()<1)return;
    for(int i = commandStack.size()-1; i > undoRedoPointer; i--)
    {
        commandStack.remove(i);
    }
}

  private void undo()
{
    Command command = commandStack.get(undoRedoPointer);
    command.unExecute();
    undoRedoPointer--;
}

private void redo()
{
    if(undoRedoPointer == commandStack.size() - 1)
        return;
    undoRedoPointer++;
    Command command = commandStack.get(undoRedoPointer);
    command.execute();
}
```

Conclusion:

What makes this design powerful is the fact that you can add as many commands as you like (by extending the Command class) e.g., RemoveCommand, UpdateCommand and so on. Moreover, the same pattern is applicable to any type of object, making the design reusable and modifiable across different use cases.

ContentLicense: CC BY-SA 4.0

Body:
I've created an XML editor and I'm stuck at the last phase: adding undo/redo functionality.

I've only got to add undo/redo for when users add elements, attributes, or text to the JTree.

I'm still quite new at this but in school today I attempted (unsuccessfully) to create two stack object []'s called undo and redo and to add the actions performed into them.

For instance, I have:

Action AddElement() {

// some code
public void actionPerformed(ActionEvent e) {

                    performElementAction();
                }
}

the performElementAction just actually adds an Element to the JTree.

I want to add a way to add this action performed to my undo stack.  is there a simple way to just undo.push(  the entire action performed) or something?

Body:
TL;DR: You can support undo and redo actions by implementing the Command (p.233) and Memento (p.283) patterns (Design Patterns - Gamma et. al).

The Memento Pattern

This simple pattern allows you to save the states of an object. Simply wrap the object in a new class and whenever its state changes, update it.

public class Memento
{
    MyObject myObject;

    public MyObject getState()
    {
        return myObject;
    }

    public void setState(MyObject myObject)
    {
        this.myObject = myObject;
    }
}

The Command Pattern

The Command pattern stores the original object (that we want to support undo/redo) and the memento object, which we need in case of an undo. Moreover, 2 methods are defined:

execute: executes the command

unExecute: removes the command

Code:

public abstract class Command
{
    MyObject myObject;
    Memento memento;

    public abstract void execute();

    public abstract void unExecute();
}

They define the logical "Actions" that extend Command (e.g. Insert):

public class InsertCharacterCommand extends Command
{
    //members..

    public InsertCharacterCommand()
    {
        //instantiate
    }

    @Override public void execute()
    {
        //create Memento before executing
        //set new state
    }

    @Override public void unExecute()
    {
        this.myObject = memento.getState()l
    }
}

Applying the patterns:

This last step defines the undo/redo behavior. The core idea is to store a stack of commands that works as a history list of the commands. To support redo, you can keep a secondary pointer whenever an undo command is applied. Note that whenever a new object is inserted, then all the commands after its current position get removed; that's achieved by the deleteElementsAfterPointer method defined below:

private int undoRedoPointer = -1;
private Stack<Command> commandStack = new Stack<>();

private void insertCommand()
{
    deleteElementsAfterPointer(undoRedoPointer);
    Command command =
            new InsertCharacterCommand();
    command.execute();
    commandStack.push(command);
    undoRedoPointer++;
}

private void deleteElementsAfterPointer(int undoRedoPointer)
{
    if(commandStack.size()<1)return;
    for(int i = commandStack.size()-1; i > undoRedoPointer; i--)
    {
        commandStack.remove(i);
    }
}

  private void undo()
{
    Command command = commandStack.get(undoRedoPointer);
    command.unExecute();
    undoRedoPointer--;
}

private void redo()
{
    if(undoRedoPointer == commandStack.size() - 1)
        return;
    undoRedoPointer++;
    Command command = commandStack.get(undoRedoPointer);
    command.execute();
}

Conclusion:

What makes this design powerful is the fact that you can add as many commands as you like (by extending the Command class) e.g., RemoveCommand, UpdateCommand and so on. Moreover, the same pattern is applicable to any type of object, making the design reusable and modifiable across different use cases.


问:
How to find 'old' pages in Confluence?
Our team has been using a Confluence wiki for several years.  We have a lot of old pages I'd like to archive or delete.  I'm wondering if there is a way to identify pages that have not been modified in over a year.  I don't see any option to accomplish this under the admin tools or search features.

Does anyone know to do this?

答:
Technically you can't archive pages but you can delete them. However, you are able to archive spaces. Thus, If all your old pages are located in same space/spaces you can achieve those spaces and create your new pages in new space.

For finding old pages, I believe you can grab those from the database by checking the lastmodifidate of those content. Atlassian has this documentation that they do have some sample database queries, I believe you can edit those queries base on your need and grab the old pages.

Once you find the pages, if you want to delete from database, you can use the queries from this KB.

FYI, for rest API at the moment you can only grab the pages base on their title or space key not last modified date.

Title: How to find 'old' pages in Confluence?


问:
Is there any way to retrieve a file / folder's unique ID via NodeJS?
The problem I face is simple. I want to keep track of the file/folder even after it has been renamed / deleted etc? Does NodeJS provide a way to access this information a file? I've tried the default file system module fs.stats() : https://nodejs.org/api/fs.html#fs_class_fs_stats . Unfortunately, it does not seem to provide such unique ID referencing for a particular file.

Does there exist such a solution in NodeJS?

Note: I DO NOT want to generate a Unique ID for a file. It's pretty easy to assign a random string to a file and associate the string with this this. But it's the other way around. I want to associate a file with a system wide string of some sort.

Any help is appreciated.

答:
Looking at the link https://nodejs.org/api/fs.html#fs_class_fs_stats

```<code>Stats {
  dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
</code>```

I can see unix inode number.

Can two files have the same inode number?

Two files can have the same inode, but only if they are part of different partitions.
Inodes are only unique on a partition level, not on the whole system.

Thus, in addition to the inode number one also compares the device number.

```<code>var uniqueFileId[fileName] = (Stats.dev + Stats.ino)
</code>```

Body:
Looking at the link https://nodejs.org/api/fs.html#fs_class_fs_stats

Stats {
  dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }

I can see unix inode number.

Can two files have the same inode number?

Two files can have the same inode, but only if they are part of different partitions.
Inodes are only unique on a partition level, not on the whole system.

Thus, in addition to the inode number one also compares the device number.

var uniqueFileId[fileName] = (Stats.dev + Stats.ino)


问:
Not able to read Configuration file Using scala typesafe API
I have a spark/scala project named as Omega

I have a conf file inside Omega/conf/omega.config

I use API's from typesafe to load the config file from  conf/omega.config.
It was working fine and I was able to read the respective value for each key

Now today, For the first time I added some more key-value pairs in my omega.config file and tried to retrieve them from my scala code. It throws

```<code> Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'job_name'
</code>```

This issue started happening after adding new value for the key job_name in my omega.config file.
Also I am not able to read the newly added -key-values, I am still able to read all old values using config. getString method

I am building my spark/scala application using maven.

Omega.config

```<code>input_path="/user/cloudera/data
user_name="surender"
job_name="SAMPLE"
</code>```

I am Not able to access the recently added key "job_name" alone
   package com.pack1

```<code>import com.pack2.ApplicationUtil
object OmegaMain {

  val config_loc = "conf/omega.config"

  def main(args: Array[String]): Unit = {

   val config               = ApplicationUtil.loadConfig(config_loc)
   val jobName              = ApplicationUtil.getFromConfig(config,"job_name")
}
}

package com.pack2
import com.typesafe.config.{Config, ConfigFactory}

object ApplicationUtil {

 def loadConfig(filePath:String):Config={
  val config = ConfigFactory.parseFile(new File(filePath))

  config
 }

  def getFromConfig(config:Config,jobName:String):String={
    config.getString(jobName)
  }

}
</code>```

Could some one help me what went wrong?

答:
You can try something like:

```<code>def loadConfig(filename: String, syntax: ConfigSyntax): Config = {
val in: InputStream = getClass.getResourceAsStream(filename)
if (in == null) return null
val file: File = File.createTempFile(String.valueOf(in.hashCode()), ".conf")
file.deleteOnExit()

val out: FileOutputStream = new FileOutputStream(file)
val buffer: Array[Byte] = new Array(1024)
var bytesRead: Int = in.read(buffer)
while (bytesRead != -1) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer) }
out.close()

val conf: Config = ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setSyntax(syntax).setAllowMissing(false).setOriginDescription("Merged with " + filename))
conf
</code>```

}

filename is some file path in the classpath. If you want to update this method to taking some external file into account, change update the 4th with val file: File = new File("absolute Path of he file")

Body:
I have a spark/scala project named as Omega

I have a conf file inside Omega/conf/omega.config

I use API's from typesafe to load the config file from  conf/omega.config.
It was working fine and I was able to read the respective value for each key

Now today, For the first time I added some more key-value pairs in my omega.config file and tried to retrieve them from my scala code. It throws

 Exception in thread "main" com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'job_name'

This issue started happening after adding new value for the key job_name in my omega.config file.
Also I am not able to read the newly added -key-values, I am still able to read all old values using config. getString method

I am building my spark/scala application using maven.

Omega.config

input_path="/user/cloudera/data
user_name="surender"
job_name="SAMPLE"

I am Not able to access the recently added key "job_name" alone
   package com.pack1

import com.pack2.ApplicationUtil
object OmegaMain {

  val config_loc = "conf/omega.config"

  def main(args: Array[String]): Unit = {

   val config               = ApplicationUtil.loadConfig(config_loc)
   val jobName              = ApplicationUtil.getFromConfig(config,"job_name")
}
}

package com.pack2
import com.typesafe.config.{Config, ConfigFactory}

object ApplicationUtil {

 def loadConfig(filePath:String):Config={
  val config = ConfigFactory.parseFile(new File(filePath))

  config
 }

  def getFromConfig(config:Config,jobName:String):String={
    config.getString(jobName)
  }

}

Could some one help me what went wrong?

Body:
You can try something like:

def loadConfig(filename: String, syntax: ConfigSyntax): Config = {
val in: InputStream = getClass.getResourceAsStream(filename)
if (in == null) return null
val file: File = File.createTempFile(String.valueOf(in.hashCode()), ".conf")
file.deleteOnExit()

val out: FileOutputStream = new FileOutputStream(file)
val buffer: Array[Byte] = new Array(1024)
var bytesRead: Int = in.read(buffer)
while (bytesRead != -1) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer) }
out.close()

val conf: Config = ConfigFactory.parseFile(file, ConfigParseOptions.defaults().setSyntax(syntax).setAllowMissing(false).setOriginDescription("Merged with " + filename))
conf

}

filename is some file path in the classpath. If you want to update this method to taking some external file into account, change update the 4th with val file: File = new File("absolute Path of he file")


问:
GraphQL query to pass mapQueriesToProps via connect() not firing
So, I'm attempting to set the results of a graphQL query to mapQueriesToProps, and then pass the result onto the main interface/view of my app via connect(), but the query is not firing (as confirmed by devTools):

My code is as follows:

App.js

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// import { connect } from 'react-apollo';
import {
  // gql,
  graphql,
  withApollo
} from 'react-apollo';
import gql from 'graphql-tag';
import * as actionCreators from '../actions/actionCreators';
// import client from '../apolloClient';
// import ApolloClient from 'apollo-client';

/*
  Components
  This is where the actual interface / view comes into play
  Everything is in Main - so we import that one
*/

import Main from './Main';

const allPostsCommentsQuery = gql`
  query allPostsCommentsQuery {
    allPostses {
      id
      displaysrc
      caption
      likes
      comments {
        id
        posts {
          id
        }
        text
        user
      }
    }
  }
`;

const mapQueriesToProps = ({ ownProps, state }) => {
  return {
    posts: {
      query: gql`
        query allPostsCommentsQuery {
          allPostses {
            id
            displaysrc
            caption
            likes
            comments {
              id
              posts {
                id
              }
              text
              user
            }
          }
        }
      `,
      // variables: {
      // },
      // forceFetch: false, // optional
      // returnPartialData: false,  // optional
    },
  };
};

export function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

var App = connect(
  mapQueriesToProps,
  mapDispatchToProps
)(Main);

export default App;```
</div>
</div>
</p>

<p>Main.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import React from 'react';
import { Link } from 'react-router';

const Main = React.createClass({

  render() {
    return (
      <div>
        <h1>
          <Link to="/">Flamingo City</Link>
        </h1>
        {/* We use cloneElement here so we can auto pass down props */}
        { React.cloneElement(this.props.children, this.props) }
      </div>
    );
  }

});

export default Main;</code>```

My app.js into which App.js is imported into:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router'
import 'babel-polyfill';
import { ApolloProvider, graphql, gql } from 'react-apollo';
import client from './apolloClient';

/*
  Import Components
*/
import App from './components/App';
import Single from './components/Single';
import PhotoGrid from './components/PhotoGrid';

/* Import CSS */
import css from  './styles/style.styl';

/* Import our data store */
import store, { history } from './store';

/*
  Error Logging
*/
import Raven from 'raven-js';
import { sentry_url } from './data/config';
if(window) {
  Raven.config(sentry_url).install();
}

/*
  Rendering
  This is where we hook up the Store with our actual component and the router
*/
render(
  <ApolloProvider store={store} client={client}>
    { /* Tell the Router to use our enhanced history */ }
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={PhotoGrid} />
        <Route path="/view/:postId" component={Single}></Route>
      </Route>
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
);```

What am I overlooking?

答:
I resolved the issue by doing the following:

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  gql,
  graphql
} from 'react-apollo';
import * as actionCreators from '../actions/actionCreators';

/*
  Components
  This is where the actual interface / view comes into play
  Everything is in Main - so we import that one
*/

import Main from './Main';

const allPostsCommentsQuery = graphql(gql`
  query allPostsCommentsQuery {
    allPostses {
      id
      displaysrc
      caption
      likes
      comments {
        id
        posts {
          id
        }
        text
        user
      }
    }
  }
`);

/*
  This will bind our actions to dispatch (make the fire-able)
  and make the actions available via props
*/

export function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

const App = connect(
  mapDispatchToProps
);

export default App(allPostsCommentsQuery(Main));```

Body:
So, I'm attempting to set the results of a graphQL query to mapQueriesToProps, and then pass the result onto the main interface/view of my app via connect(), but the query is not firing (as confirmed by devTools):

My code is as follows:

App.js

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// import { connect } from 'react-apollo';
import {
  // gql,
  graphql,
  withApollo
} from 'react-apollo';
import gql from 'graphql-tag';
import * as actionCreators from '../actions/actionCreators';
// import client from '../apolloClient';
// import ApolloClient from 'apollo-client';

/*
  Components
  This is where the actual interface / view comes into play
  Everything is in Main - so we import that one
*/

import Main from './Main';

const allPostsCommentsQuery = gql`
  query allPostsCommentsQuery {
    allPostses {
      id
      displaysrc
      caption
      likes
      comments {
        id
        posts {
          id
        }
        text
        user
      }
    }
  }
`;

const mapQueriesToProps = ({ ownProps, state }) => {
  return {
    posts: {
      query: gql`
        query allPostsCommentsQuery {
          allPostses {
            id
            displaysrc
            caption
            likes
            comments {
              id
              posts {
                id
              }
              text
              user
            }
          }
        }
      `,
      // variables: {
      // },
      // forceFetch: false, // optional
      // returnPartialData: false,  // optional
    },
  };
};

export function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

var App = connect(
  mapQueriesToProps,
  mapDispatchToProps
)(Main);

export default App;

Main.js

import React from 'react';
import { Link } from 'react-router';

const Main = React.createClass({

  render() {
    return (

          <Link to="/">Flamingo City</Link>

        {/* We use cloneElement here so we can auto pass down props */}
        { React.cloneElement(this.props.children, this.props) }

    );
  }

});

export default Main;

My app.js into which App.js is imported into:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router'
import 'babel-polyfill';
import { ApolloProvider, graphql, gql } from 'react-apollo';
import client from './apolloClient';

/*
  Import Components
*/
import App from './components/App';
import Single from './components/Single';
import PhotoGrid from './components/PhotoGrid';

/* Import CSS */
import css from  './styles/style.styl';

/* Import our data store */
import store, { history } from './store';

/*
  Error Logging
*/
import Raven from 'raven-js';
import { sentry_url } from './data/config';
if(window) {
  Raven.config(sentry_url).install();
}

/*
  Rendering
  This is where we hook up the Store with our actual component and the router
*/
render(
  <ApolloProvider store={store} client={client}>
    { /* Tell the Router to use our enhanced history */ }
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={PhotoGrid} />
        <Route path="/view/:postId" component={Single}></Route>
      </Route>
    </Router>
  </ApolloProvider>,
  document.getElementById('root')
);

What am I overlooking?


问:
C# how do I use a partially filled array in a method?
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

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

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);
</code>```

答:
You can call a method by reference. You should use from out and ref key word:
https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx

Body:
My instructor wants us to create an array of 10 elements and then fill it with random numbers using console input and then multiply all the numbers together to get the product.  I can't figure out how to pass the array to a method and then successfully get the product.  Do I use a for loop?  I don't think I can use a foreach loop because it could be partially filled.  How do I even pass the array to the method in the first place?

Here's what I have so far to store the values in the array.

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

    bool valid = false;
    do
    {
         Write("Enter an integer value or 0 to stop ");
         string input = ReadLine();
         valid = int.TryParse(input, out userInput);
    } while (!valid);

    if (userInput == 0)
    {
         break;
    }
    array[i] = userInput;
}

product = p.ArrayProduct(array.Length);


问:
C++ static pointer to function
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

```<code>//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}
</code>```

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

```<code>int (X::*staticFunc)(const X&) = NULL;
</code>```

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.

答:
Couple problems here.

First error is that you're not passing a parameter in your attempt to use staticFunc.  This should cause a compiler error that you're not reporting.

Second issue is that your syntax is wrong.  TonyK got that one.

ContentLicense: CC BY-SA 2.5

Title: C++ static pointer to function

Body:
I would like to have a private static pointer to a function in my class. Basically, it would look like this:

//file.h
class X {
private:
    static int (*staticFunc)(const X&);
    ...
public:
    void f();

};

//file.cpp
void X::f()
{
    staticFunc(*this);
}

This gives me an "unresolved external symbol" error. I know that static members must be initialized in the .cpp too, I've tried this:

int (X::*staticFunc)(const X&) = NULL;

but this gives me an "initializing a function" error. It gives me an uglier error if I try to initialize it with an existing function. Without "= NULL", I get the same error.

Thanks.


问:
React Router V4 Path Issues
I'm using React Router Dom V4, my path to my homepage works but my path to my about page doesn't work.

I'm not sure if it's anything to do with the fact I'm using Xampp or not.

Index.js

```<code>import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import App from "./components/App";
import About from "./components/About";

const Root = () => {
    return (
        <Router>
            <div>
                <Route path="/" component={App} />
                <Route path="/about" component={About} />
            </div>
        </Router>
    )
}

render(<Root />, document.getElementById('main'));
</code>```

Header.js

```<code>import React from "react";

const Header = () => {
    return (
        <div>
            <ul>
                <li><a href="/about">About</a></li>
            </ul>
        </div>
    )
}

export default Header;
</code>```

About.js

```<code>import React from "react";

const About = () => {
    return (
        <p>This is the about page</p>
    )
}

export default About;
</code>```

答:
The problem is that you use plain html links, so React will not be called when the user clicks the link. You should use the Link Element from the router-module.

Try the following for the menu:

```<code>import { Link } from "react-router-dom"
....
<li><Link to='/about'>About</Link></li>
</code>```

Title: React Router V4 Path Issues

Body:
I'm using React Router Dom V4, my path to my homepage works but my path to my about page doesn't work.

I'm not sure if it's anything to do with the fact I'm using Xampp or not.

Index.js

import React from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import App from "./components/App";
import About from "./components/About";

const Root = () => {
    return (
        <Router>

                <Route path="/" component={App} />
                <Route path="/about" component={About} />

        </Router>
    )
}

render(<Root />, document.getElementById('main'));

Header.js

import React from "react";

const Header = () => {
    return (

About

    )
}

export default Header;

About.js

import React from "react";

const About = () => {
    return (

This is the about page

    )
}

export default About;

Body:
The problem is that you use plain html links, so React will not be called when the user clicks the link. You should use the Link Element from the router-module.

Try the following for the menu:

import { Link } from "react-router-dom"
....
<li><Link to='/about'>About</Link></li>


问:
Android Google Maps [React Native?] "API key not found. Check that.." Error
Hi I am new to react native. I just made a new application. When I don't have a map component in my application and my other components work fine. However when I add this in my render(){return(..

```<code>  <MapView
    ref={ref => { this.map = ref; }}
    mapType={MAP_TYPES.TERRAIN}
    style={styles.map}
    initialRegion={this.state.region}
    onRegionChange={region => this.onRegionChange(region)}
  />
</code>```

I get the error:

I did a search of the project folder to find a AndroidMainfest.xml and I found a couple. I changed the one in: \android\app\build\intermediates\manifests\full\debug

from this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- Include required permissions for Google Maps API to run. -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>
</code>```

To this:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- Include required permissions for Google Maps API to run. -->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC-V3J1Wz4wqgHqrqffIeZqhVM0gDfTsIg" />

    </application>

</manifest>
</code>```

I even just tried it with only the meta-deta API Key one.

Some other information:
I got the API key from here: https://developers.google.com/maps/documentation/android-api/signup.

After I changed it I just saved the file and restarted the simulator restarted the app with react-native run-android in the directory with command prompt. I'm not sure if this is the correct way to "Rebuild" the project.

I am using the Airbnb react-native-maps component that Facebook recommends using: https://github.com/airbnb/react-native-maps

I did the npm install react-native-maps --save and react-native link react-native-maps recently because this is a brand new project (error in the new version they provide or something?). The emulator is android 7.1.1.

Here is the SDK Manager for the android studio simulator:

答:
Try to delite from manifest this:

```<code><meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
</code>```

This data you can move to build.gradle config in chapter dependencies:

```<code>compile 'com.google.android.gms:play-services-maps:10.0.1'compile 'com.google.android.gms:play-services-ads:10.0.1'
</code>```

Body:
Hi I am new to react native. I just made a new application. When I don't have a map component in my application and my other components work fine. However when I add this in my render(){return(..

  <MapView
    ref={ref => { this.map = ref; }}
    mapType={MAP_TYPES.TERRAIN}
    style={styles.map}
    initialRegion={this.state.region}
    onRegionChange={region => this.onRegionChange(region)}
  />

I get the error:

I did a search of the project folder to find a AndroidMainfest.xml and I found a couple. I changed the one in: \android\app\build\intermediates\manifests\full\debug

from this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

To this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pickup_sports_app"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="com.pickup_sports_app.MainApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pickup_sports_app.MainActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
        <activity
            android:name="com.google.android.gms.common.api.GoogleApiActivity"
            android:exported="false"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyC-V3J1Wz4wqgHqrqffIeZqhVM0gDfTsIg" />

    </application>

</manifest>

I even just tried it with only the meta-deta API Key one.

Some other information:
I got the API key from here: https://developers.google.com/maps/documentation/android-api/signup.

After I changed it I just saved the file and restarted the simulator restarted the app with react-native run-android in the directory with command prompt. I'm not sure if this is the correct way to "Rebuild" the project.

I am using the Airbnb react-native-maps component that Facebook recommends using: https://github.com/airbnb/react-native-maps

I did the npm install react-native-maps --save and react-native link react-native-maps recently because this is a brand new project (error in the new version they provide or something?). The emulator is android 7.1.1.

Here is the SDK Manager for the android studio simulator:

Body:
Try to delite from manifest this:

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>

This data you can move to build.gradle config in chapter dependencies:

compile 'com.google.android.gms:play-services-maps:10.0.1'compile 'com.google.android.gms:play-services-ads:10.0.1'


问:
Consuming API of certain endpoints using Vue Components within Laravel Application
I have been browsing for a while to find a viable solution.

I have a Laravel application where I have certain endpoints in API route.

I would like to consume the data without needing to log into application itself. I would appreciate if some body can guide me in the right direction. I have looked into Passport, however I wouldn't like to pass certain information like client_id or client_secret in ajax calls as they can easily be seen.

答:
You cannot have both. You cannot protect a route, then call it without authenticating. Then there is no point protecting it in the first place if you can access unauthenticated. Make your life easier, define the same route twice. Once in the middleware, once out of the middleware.

```<code>Route::get('link', 'LinkController@get');

Route::group(['middleware' => 'auth:api'], function(){
    Route::get('link', 'LinkController@get');
});
</code>```

Now you have both, protected and unprotected routes. But, as I said, not it's literally unprotected because anyone can access it without authenticating.

Body:
You cannot have both. You cannot protect a route, then call it without authenticating. Then there is no point protecting it in the first place if you can access unauthenticated. Make your life easier, define the same route twice. Once in the middleware, once out of the middleware.

Route::get('link', 'LinkController@get');

Route::group(['middleware' => 'auth:api'], function(){
    Route::get('link', 'LinkController@get');
});

Now you have both, protected and unprotected routes. But, as I said, not it's literally unprotected because anyone can access it without authenticating.


问:
Does Rebol really have an equivalent for javascript prototype property?
Gregogy has made a post about rebol and javascript here http://blog.revolucent.net/2009/05/javascript-rebol.html

But as I'm going deeper into comparing javascript and rebol, I can't see what's the equivalent of rebol for javascript prototype. Because extending an object instance from another one with make in rebol isn't exactly like javascript prototype property as js prototype allows to extend ALL instances at once.

So am I mistaken or is there an equivalent of the code below for rebol:

```<code><html>
<head>
</head>

<body>
  <script>
    function Person(firstName, lastName, sex) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.whoAreYou = function() {
        alert( "I've been built with Constructor and my name is " + this.firstName + " " + this.lastName);
      }
      this.WhatIsYourSex = function() {
        alert(this.sex);
      }
    };

    Person.prototype.sex = "Man";

  </script>

  <script>
    JaneDoe = new Person("Jane", "Doe");
    JaneDoe.whoAreYou();
    JaneDoe.WhatIsYourSex();
    alert("Are you sure?");
    JaneDoe.sex = "Woman";
    JaneDoe.WhatIsYourSex();
  </script>

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

Update: I don't care about syntactic sugar of course. Nothing prevents extension in R2 by just redefining an object. My question is not about extension of an object INSTANCE but about extension of ALL INSTANCES at once: that's what js prototype property allows.

So to reformulate my question:
Can Rebol allow to also extend AUTOMATICALLY ALL INSTANCES of children by extending the parent class like javascript can whatever the syntax I don't care ?

For performance sure I see the difference between R2 and R3 for one instance but as for language functional feature I don't have automatic extension of all children objects which is a big burden as I'll have to manage them myself which will be quite slow since it's not done by the system itself. What if I want to create a framework like jquery which heavily relies on this kind of feature ? It would be a great hassle.

答:
I guess you will not like this from some reason:

```<code>person: context [
    firstName: secondName: none
    whoAreYou: does [print [firstName secondName]]
    WhatIsYourSex: does [print sex]
]
extend person 'sex "male"
JaneDoe: make person [firstName: "Jane" secondName: "Doe"]
JaneDoe/whoAreYou
JaneDoe/WhatIsYourSex
ask "Are you sure?"
JaneDoe/sex: "female"
JaneDoe/WhatIsYourSex
</code>```

I must say, that I would not use code like this one in real as I don't see reason why I should mix data with functions. It's just a try to mimic your JS code.

But I guess, you have wrong example and you want to show this:

```<code><script>
    JaneDoe = new Person("Jane", "Doe");
    DoeJane = new Person("Doe", "Jane");
    Person.prototype.sex = "Man";
    JaneDoe.WhatIsYourSex();
    DoeJane.WhatIsYourSex();
</script>
</code>```

Than I must say, that in REBOL something like this is not supported, at least now.

Body:
Gregogy has made a post about rebol and javascript here http://blog.revolucent.net/2009/05/javascript-rebol.html

But as I'm going deeper into comparing javascript and rebol, I can't see what's the equivalent of rebol for javascript prototype. Because extending an object instance from another one with make in rebol isn't exactly like javascript prototype property as js prototype allows to extend ALL instances at once.

So am I mistaken or is there an equivalent of the code below for rebol:

Update: I don't care about syntactic sugar of course. Nothing prevents extension in R2 by just redefining an object. My question is not about extension of an object INSTANCE but about extension of ALL INSTANCES at once: that's what js prototype property allows.

So to reformulate my question:
Can Rebol allow to also extend AUTOMATICALLY ALL INSTANCES of children by extending the parent class like javascript can whatever the syntax I don't care ?

For performance sure I see the difference between R2 and R3 for one instance but as for language functional feature I don't have automatic extension of all children objects which is a big burden as I'll have to manage them myself which will be quite slow since it's not done by the system itself. What if I want to create a framework like jquery which heavily relies on this kind of feature ? It would be a great hassle.

Body:
I guess you will not like this from some reason:

person: context [
    firstName: secondName: none
    whoAreYou: does [print [firstName secondName]]
    WhatIsYourSex: does [print sex]
]
extend person 'sex "male"
JaneDoe: make person [firstName: "Jane" secondName: "Doe"]
JaneDoe/whoAreYou
JaneDoe/WhatIsYourSex
ask "Are you sure?"
JaneDoe/sex: "female"
JaneDoe/WhatIsYourSex

I must say, that I would not use code like this one in real as I don't see reason why I should mix data with functions. It's just a try to mimic your JS code.

But I guess, you have wrong example and you want to show this:

<script>
    JaneDoe = new Person("Jane", "Doe");
    DoeJane = new Person("Doe", "Jane");
    Person.prototype.sex = "Man";
    JaneDoe.WhatIsYourSex();
    DoeJane.WhatIsYourSex();
</script>

Than I must say, that in REBOL something like this is not supported, at least now.


问:
Why do we stop after reaching this term? Lambda Calculus
I'm calculating the normal form of a lambda Term. I also have the solution so I know that my steps until the "end" were right.
The given term is

```<code>(\a.\b.(\x.a b x)(\y. b y x) a) (\f. f f)g
</code>```

and the normalform of that is

```<code>    g g (\y. g y x)(\f. f f)
</code>```

I also got this but then I continued and I do not understand why this is the final term. I continued with

```<code>g g g (\f. f f) x
</code>```

and then

```<code>g g g x x
</code>```

But apparently I went too far, do you know why you are supposed to stop earlier?

答:
It's not a matter of stopping earlier. You're misinterpreting the syntax of lambda calculus.

By convention, when we write A B C, we mean (A B) C, not A (B C); that is, function application is left associative.

Therefore

```<code>g g (\y. g y x)(\f. f f)
</code>```

parses as

```<code>((g g) (\y. (g y) x)) (\f. f f)
</code>```

In particular, (g g) is applied to (\y. g y x), whereas (\y. g y x) is not applied to (\f. f f).

Body:
I'm calculating the normal form of a lambda Term. I also have the solution so I know that my steps until the "end" were right.
The given term is

(\a.\b.(\x.a b x)(\y. b y x) a) (\f. f f)g

and the normalform of that is

    g g (\y. g y x)(\f. f f)

I also got this but then I continued and I do not understand why this is the final term. I continued with

g g g (\f. f f) x

and then

g g g x x

But apparently I went too far, do you know why you are supposed to stop earlier?

Body:
It's not a matter of stopping earlier. You're misinterpreting the syntax of lambda calculus.

By convention, when we write A B C, we mean (A B) C, not A (B C); that is, function application is left associative.

Therefore

g g (\y. g y x)(\f. f f)

parses as

((g g) (\y. (g y) x)) (\f. f f)

In particular, (g g) is applied to (\y. g y x), whereas (\y. g y x) is not applied to (\f. f f).


问:
Trigger after create table
I need when I create a new table, insert it with the name of the table in another already existing table. I had planned to use a trigger, but I can not find documentation on how to do this. Do you have any idea?

Thank you!

答: There's nothing in MySQL allowing the definition of a trigger to fire upon table creation, sorry to say.</p>

Title: Trigger after create table


问:
Basic trouble with Python lists in Numba; what's going on?
I'm a beginner to Numba. For the life in me I can't get a Numba function to manipulate a simple list.

Heck, I can't even figure out how to specify the signature.

Here's the example. What's wrong? (What's a "reflected list"?) And how do I fix it?

```<code>from numba import *
from numba.types import *

@jit(List(int64)(List(int64)), nopython=True)
def foo(a): a[0] += a[0]; return a

foo([1])
</code>```

gives

```<code>Traceback (most recent call last):
  File "<pyshell#5>", in <module>
    foo([1])
  File "numba\dispatcher.py", line 219, in _explain_matching_error
    raise TypeError(msg)
TypeError: No matching definition for argument type(s) reflected list(int64)
</code>```

答:
I haven't found any documentation on the subject, but from the things that came up when I Googled the topic and dug through the source code, a "reflected" list is one where changes to the list have to be visible (reflected) in Python after a JITted function is done with it. Reflected lists are treated as a different type from non-reflected lists in the Numba type system, for reasons I do not know. The concept may be specific to nopython mode; I'm not sure, and I can't test it.

You've declared that your function takes a non-reflected list, but it needs to take a reflected list. You need to add reflected=True to the inner List(int64) call, and possibly the outer one as well.

Body:
I'm a beginner to Numba. For the life in me I can't get a Numba function to manipulate a simple list.

Heck, I can't even figure out how to specify the signature.

Here's the example. What's wrong? (What's a "reflected list"?) And how do I fix it?

from numba import *
from numba.types import *

@jit(List(int64)(List(int64)), nopython=True)
def foo(a): a[0] += a[0]; return a

foo([1])

gives

Traceback (most recent call last):
  File "<pyshell#5>", in <module>
    foo([1])
  File "numba\dispatcher.py", line 219, in _explain_matching_error
    raise TypeError(msg)
TypeError: No matching definition for argument type(s) reflected list(int64)


问:
Dynamic links in php
I'm almost embarrassed asking this question since I know it should be quite simple yet I can't find an answer to it.

I have a html page with php code in it, that displays let's say a list of companies in a table. I want to make the names of the companies in the table be hyperlinks, such that when a user clicks on a company name, he/she is taken to a page that shows that company's details.

The issue is I cannot have a static page for each company because this list of companies can change every day. So the 'company details' page should be generated dynamically based on what the user clicks.

I am not sure how to approach this. all the questions I see out there seem to talk about static links and pages for static data.

Any guidance is be appreciated!

答:
Every company in the table should have an ID property.

Then when you create the link, do something like this:

```<code><a href="/company_details.php?id=<?php echo $companyId; ?>">Company Name</a>
</code>```

In your company_details.php you can get the ID of the company from $_GET['id'].

That way you only have one page company_details.php for all companies.

Title: Dynamic links in php

Body:
Every company in the table should have an ID property.

Then when you create the link, do something like this:

<a href="/company_details.php?id=<?php echo $companyId; ?>">Company Name</a>

In your company_details.php you can get the ID of the company from $_GET['id'].

That way you only have one page company_details.php for all companies.


问:
Merge multiple arrays based on their index using javascript
I need to merge two arrays into a single array.  I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

    <title></title>

```

答:
You can use Array#map in plain javascript.

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];

var newArray = array1.map((e, i) => e + array2[i]);
console.log(newArray);```
</div>
</div>
</p>

<p>If you use map on array1 then first parameter is current value of array1 in loop and the second parameter is index of that element in array. So you can match current element in array1 with elements from other arrays with the same index using index.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var array3 = ["f", "d", "s", "a"];

var newArray = array1.map(function(value, index) {
  return value + array2[index] + array3[index];
});
console.log(newArray);</code>```

Body:
You can use Array#map in plain javascript.

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];

var newArray = array1.map((e, i) => e + array2[i]);
console.log(newArray);

If you use map on array1 then first parameter is current value of array1 in loop and the second parameter is index of that element in array. So you can match current element in array1 with elements from other arrays with the same index using index.

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var array3 = ["f", "d", "s", "a"];

var newArray = array1.map(function(value, index) {
  return value + array2[index] + array3[index];
});
console.log(newArray);


问:
Get URL headers without the HTML
A bit of a strange question. Is there a way to ask a webserver to return only the headers and not the HTML itself ?

I want to ask a server for a URL and see if its valid (not 404/500/etc) and follow the redirections (if present) but not get the actual HTML content.

Thanks

Preferably a way to do this in Ruby

答:
This is exactly what HEAD HTTP method does.

For Ruby, there is a beautiful gem, much simpler than the low-level net/http that allows you to perform HEAD requests.

```<code>gem install rest-open-uri
</code>```

then

```
irb> require 'rubygems'
=> true
irb> require 'rest-open-uri'
=> true
irb> sio = open("http://stackoverflow.com", :method => :head)
=> #
irb> sio.meta
=> {"expires"=>"Tue, 30 Nov 2010 18:08:47 GMT", "last-modified"=>"Tue, 30 Nov 2010 18:07:47 GMT", "content-type"=>"text/html; charset=utf-8", "date"=>"Tue, 30 Nov 2010 18:08:27 GMT", "content-length"=>"193779", "cache-control"=>"public, max-age=18", "vary"=>"*"}
irb> sio.status
=> ["200", "OK"]
```

It follows redirections. You have to rescue for SocketError when host doesn't exists or OpenURI::HTTPError if file doesn't exists.

If you want something more powerfull have a look at Mechanize or HTTParty.

Title: Get URL headers without the HTML

Body:
This is exactly what HEAD HTTP method does.

For Ruby, there is a beautiful gem, much simpler than the low-level net/http that allows you to perform HEAD requests.

gem install rest-open-uri

then

irb> require 'rubygems'
=> true
irb> require 'rest-open-uri'
=> true
irb> sio = open("http://stackoverflow.com", :method => :head)
=> #
irb> sio.meta
=> {"expires"=>"Tue, 30 Nov 2010 18:08:47 GMT", "last-modified"=>"Tue, 30 Nov 2010 18:07:47 GMT", "content-type"=>"text/html; charset=utf-8", "date"=>"Tue, 30 Nov 2010 18:08:27 GMT", "content-length"=>"193779", "cache-control"=>"public, max-age=18", "vary"=>"*"}
irb> sio.status
=> ["200", "OK"]

It follows redirections. You have to rescue for SocketError when host doesn't exists or OpenURI::HTTPError if file doesn't exists.

If you want something more powerfull have a look at Mechanize or HTTParty.


问:
Modified comparator for priority_queue of C++ not working properly
In the code given below, I am trying to keep some values in priority_queue sorted accordingly their key values, which are stored in the "key" vector. And then, I am changing the key values to see if the comparator working properly or not. Here, when I change the key[8] to 10, value 8 changes its position in the queue correctly. But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly. It should be positioned at the top of the queue, as it's key value is the smallest, but it's not.

Is my way of writing the code of the comparator wrong? Or, It's something else that I am not doing correctly?

I want to know the correct way to modify the comparator of priority queue if I want to sort values in ascending order accordingly to their key values.

```<code>#include <bits/stdc++.h>
using namespace std;
vector <int> key(1000);
struct comp{
    bool operator()(int a,int b)const{
        return key[a]>key[b];
    }
};
int main()
{
    priority_queue <int,vector<int>,comp> q,temp;
    for(int a=0;a<10;a++){
        int n=rand()%16;
        key[a]=n;
        q.push(a);
    }
    while(!q.empty()){
        temp=q;
        while(!temp.empty()){
            cout<< temp.top() << "(" << key[temp.top()] << ") ";
            temp.pop();
        }
        cout<<endl<<endl;
        int u,v;
        cin>> u >> v;
        key[u]=v;
    }
    return 0;
}
</code>```

答:
The intent and the code are reasonable enough, but the issue is much more fundamental. The problem is that std::priority_queue does not support decrease key operation out-of-the-box.

In order to perform such operations, you would need to manually maintain the list of keys and call std::make_heap, std::push_heap from <algorithm>.

See this for a more detailed answer: https://stackoverflow.com/a/9210662/1045285

As a side note, consider instead including:

```<code>#include <priority_queue>
</code>```

Body:
In the code given below, I am trying to keep some values in priority_queue sorted accordingly their key values, which are stored in the "key" vector. And then, I am changing the key values to see if the comparator working properly or not. Here, when I change the key[8] to 10, value 8 changes its position in the queue correctly. But when I changed the key[2] to -1, it changed it's position in the queue, but not correctly. It should be positioned at the top of the queue, as it's key value is the smallest, but it's not.

Is my way of writing the code of the comparator wrong? Or, It's something else that I am not doing correctly?

I want to know the correct way to modify the comparator of priority queue if I want to sort values in ascending order accordingly to their key values.

#include <bits/stdc++.h>
using namespace std;
vector <int> key(1000);
struct comp{
    bool operator()(int a,int b)const{
        return key[a]>key[b];
    }
};
int main()
{
    priority_queue <int,vector<int>,comp> q,temp;
    for(int a=0;a<10;a++){
        int n=rand()%16;
        key[a]=n;
        q.push(a);
    }
    while(!q.empty()){
        temp=q;
        while(!temp.empty()){
            cout<< temp.top() << "(" << key[temp.top()] << ") ";
            temp.pop();
        }
        cout<<endl<<endl;
        int u,v;
        cin>> u >> v;
        key[u]=v;
    }
    return 0;
}

Body:
The intent and the code are reasonable enough, but the issue is much more fundamental. The problem is that std::priority_queue does not support decrease key operation out-of-the-box.

In order to perform such operations, you would need to manually maintain the list of keys and call std::make_heap, std::push_heap from <algorithm>.

See this for a more detailed answer: https://stackoverflow.com/a/9210662/1045285

As a side note, consider instead including:

#include <priority_queue>