问:
Random string generator: Unicode out of range?
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}
</code>```

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}
</code>```

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

答:
With these methods you can specify valid characters, or accept all of them.</p>

```<code>    public static string RandomString(int len)
    {
        var array = Enumerable.Range(char.MinValue, char.MaxValue - char.MinValue + 1).Select(x => (char)x).ToArray();
        return RandomString(len, array);
    }

    private static string RandomString(int len, char[] array)
    {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        while (sb.Length < len)
            sb.Append(array[r.Next(array.Length-1)]);
        return sb.ToString();
    }
</code>```

Body:
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

Body:
With these methods you can specify valid characters, or accept all of them.

    public static string RandomString(int len)
    {
        var array = Enumerable.Range(char.MinValue, char.MaxValue - char.MinValue + 1).Select(x => (char)x).ToArray();
        return RandomString(len, array);
    }

    private static string RandomString(int len, char[] array)
    {
        Random r = new Random();
        StringBuilder sb = new StringBuilder();
        while (sb.Length < len)
            sb.Append(array[r.Next(array.Length-1)]);
        return sb.ToString();
    }


来源: stackexchange

问:
SQL Error 1064 - Import Error
I exported a database as a backup that was working fine. When I imported the database to the same exact server, folder, etc. I got this error:

There is a chance that you may have found a bug in the SQL parser.
  Please examine your query closely, and check that the quotes are
  correct and not mis-matched. Other possible failure causes may be that
  you are uploading a file with binary outside of a quoted text area.
  You can also try your query on the MySQL command line interface. The
  MySQL server error output below, if there is any, may also help you in
  diagnosing the problem. If you still have problems or if the parser
  fails where the command line interface succeeds, please reduce your
  SQL query input to the single query that causes problems, and submit a
  bug report with the data chunk in the CUT section below:
  ----BEGIN CUT---- eNo1jUEKwjAURIXu/inmADHkpwYxu1JCu0iTmFQ9gYtushP09qaCs3oMjxmXc8wWI2PU8C5YMDSY
  qayt7oiWT7l6CyON7NWxV5LpVjJiERgmF1aBu2vmY6sY5xwX11Ql9YXSMlicGhtKc9otEcs+1Es+
  w2/19SY/hMniWen3Qd3hny8nMiDI
  ----END CUT----
  ----BEGIN RAW---- ERROR: C1 C2 LEN: 1 2 11 STR:

MySQL: 5.5.30-30.1 USR OS, AGENT, VER: Win CHROME 5.0.29 PMA: 4.0.5
  PHP VER,OS: 5.3.17 Linux LANG: en SQL:

  ----END RAW----

SQL query:

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near '' at line 1

The only problem seems to be that my index page is missing content, the main content actually. All of these files are .sql.

I then dropped all my tables and imported the original database from April of last year. Obviously, this database is missing all the account info, order info, etc. for all my customers as well as all the changes that have been made to my products.

When I compare the two databases the first 11 lines seem to be the problem but I don't know how to fix it. The first 11 lines of the file that DO NOT WORK are:

```<code>-- phpMyAdmin SQL Dump
-- version 4.0.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 22, 2013 at 01:28 PM
-- Server version: 5.5.30-30.1
-- PHP Version: 5.3.17

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
</code>```

The first 11 lines of the file that DOES WORK are:

```<code>-- phpMyAdmin SQL Dump
-- version 3.4.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 09, 2012 at 05:50 AM
-- Server version: 5.1.61
-- PHP Version: 5.2.17

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
</code>```

I hve tried to simply copy and paste the 11 lines from the working file to the file that does not work and get another error.

I know this is a long post and I apologize but I have been struggling with this for hours and really need some help.

Thanks

答: I had a blank line at the end of the dump file. Removing the line fixed my issue.</p>

ContentLicense: CC BY-SA 3.0

Title: SQL Error 1064 - Import Error

Body:
I exported a database as a backup that was working fine. When I imported the database to the same exact server, folder, etc. I got this error:

There is a chance that you may have found a bug in the SQL parser.
  Please examine your query closely, and check that the quotes are
  correct and not mis-matched. Other possible failure causes may be that
  you are uploading a file with binary outside of a quoted text area.
  You can also try your query on the MySQL command line interface. The
  MySQL server error output below, if there is any, may also help you in
  diagnosing the problem. If you still have problems or if the parser
  fails where the command line interface succeeds, please reduce your
  SQL query input to the single query that causes problems, and submit a
  bug report with the data chunk in the CUT section below:
  ----BEGIN CUT---- eNo1jUEKwjAURIXu/inmADHkpwYxu1JCu0iTmFQ9gYtushP09qaCs3oMjxmXc8wWI2PU8C5YMDSY
  qayt7oiWT7l6CyON7NWxV5LpVjJiERgmF1aBu2vmY6sY5xwX11Ql9YXSMlicGhtKc9otEcs+1Es+
  w2/19SY/hMniWen3Qd3hny8nMiDI
  ----END CUT----
  ----BEGIN RAW---- ERROR: C1 C2 LEN: 1 2 11 STR:

MySQL: 5.5.30-30.1 USR OS, AGENT, VER: Win CHROME 5.0.29 PMA: 4.0.5
  PHP VER,OS: 5.3.17 Linux LANG: en SQL:

  ----END RAW----

SQL query:

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near '' at line 1

The only problem seems to be that my index page is missing content, the main content actually. All of these files are .sql.

I then dropped all my tables and imported the original database from April of last year. Obviously, this database is missing all the account info, order info, etc. for all my customers as well as all the changes that have been made to my products.

When I compare the two databases the first 11 lines seem to be the problem but I don't know how to fix it. The first 11 lines of the file that DO NOT WORK are:

-- phpMyAdmin SQL Dump
-- version 4.0.5
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 22, 2013 at 01:28 PM
-- Server version: 5.5.30-30.1
-- PHP Version: 5.3.17

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

The first 11 lines of the file that DOES WORK are:

-- phpMyAdmin SQL Dump
-- version 3.4.10.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Apr 09, 2012 at 05:50 AM
-- Server version: 5.1.61
-- PHP Version: 5.2.17

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

I hve tried to simply copy and paste the 11 lines from the working file to the file that does not work and get another error.

I know this is a long post and I apologize but I have been struggling with this for hours and really need some help.

Thanks


答:
Here is simple Function that you can generate Random string </p>

```<code> public static string RandomString(int length)
        {
            string functionReturnValue = null;
            Random MyRandom = new Random();
            functionReturnValue = null;
            for (int MyLoop = 1; MyLoop <= length; MyLoop++)
            {
                if (MyLoop % 2 == 1)
                {
                    functionReturnValue = functionReturnValue + Convert.ToChar(MyRandom.Next(97, 123));
                }
                if (MyLoop % 2 == 0)
                {
                    functionReturnValue = functionReturnValue + MyRandom.Next(1, 10);
                }
            }

            return functionReturnValue;
        }
</code>```

Title: Random string generator: Unicode out of range?

Body:
Here is simple Function that you can generate Random string

 public static string RandomString(int length)
        {
            string functionReturnValue = null;
            Random MyRandom = new Random();
            functionReturnValue = null;
            for (int MyLoop = 1; MyLoop <= length; MyLoop++)
            {
                if (MyLoop % 2 == 1)
                {
                    functionReturnValue = functionReturnValue + Convert.ToChar(MyRandom.Next(97, 123));
                }
                if (MyLoop % 2 == 0)
                {
                    functionReturnValue = functionReturnValue + MyRandom.Next(1, 10);
                }
            }

            return functionReturnValue;
        }


问:
To show only file name without the entire directory path
ls /home/user/new/*.txt prints all txt files in that directory. However it prints the output as follows:

```<code>[me@comp]$ ls /home/user/new/*.txt
/home/user/new/file1.txt    /home/user/new/file2.txt    /home/user/new/file3.txt
</code>```

and so on.

I want to run the ls command not from the /home/user/new/ directory thus I have to give the full directory name, yet I want the output to be only as

```<code>[me@comp]$ ls /home/user/new/*.txt
file1.txt    file2.txt    file3.txt
</code>```

I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.

答:
(cd dir && ls)

will only output filenames in dir. Use ls -1 if you want one per line.

(Changed ; to && as per Sactiw's comment).

Body:
ls /home/user/new/*.txt prints all txt files in that directory. However it prints the output as follows:

[me@comp]$ ls /home/user/new/*.txt
/home/user/new/file1.txt    /home/user/new/file2.txt    /home/user/new/file3.txt

and so on.

I want to run the ls command not from the /home/user/new/ directory thus I have to give the full directory name, yet I want the output to be only as

[me@comp]$ ls /home/user/new/*.txt
file1.txt    file2.txt    file3.txt

I don't want the entire path. Only filename is needed. This issues has to be solved using ls command, as its output is meant for another program.

ContentLicense: CC BY-SA 4.0


问:
Hybris-Solid Concepts of hybris
Can anyone please tell me the solid concepts of hybris ? I have google it but could not find any exact answer .This is the question asked in Interview .</p>

答:
SOLID is an acronym that refer to the 5 first principles of object-oriented design.

It's a generic concept that should be followed in hybris. However hybris follows the same principle so you don't have to  worry about an "hybris version" of SOLID.

It's briefly mentionned here (look for SRP) : Code Review Check

Title: Hybris-Solid Concepts of hybris


问:
Using Adhoc or push notifications to transfer data between Ipad/Ipod/Computer
I have quite a few questions to ask about these issues. I'm an intern for a company that wants to use Ipads and Ipod touches along with a simulation. We want to connect around twenty Ipod touches with an Ipad. Students will answer a question on the iPod touch which that result should be sent to the Ipad(instructor) and then the instructor "pushes" the next question for the iTouches. Needless to say, I'm not sure where to even start to make this idea come true, I've been looking up AdHoc stuff and that seems like it's mainly for distribution as opposed to devices actually "talking" with one another. If anyone has any helpful tutorials, links, etc. that would be an amazing answer of how to start this project. Thank you!

So far I've found these links:
http://mobiforge.com/developing/story/programming-apple-push-notification-services
This mainly focuses on applications that aren't active at the time but still need to push data, correct? We don't need to worry about that, the student will only have that app up at the time.

http://www.macoscoders.com/2009/05/17/iphone-apple-push-notification-service-apns/
Also found this
http://www.knowing.net/index.php/monotouch-ad-hoc-distribution-tutorial/
Mainly about distribution again

答:
What you are thinking of is AdHoc distribution, which is a method of deploying an app to a limited number of devices (200) without going through the App Store.  But applications built using an AdHoc provisioning profile are tied to specific devices, and expire after a few months (it's mainly intended for testing).

Push notifications don't apply in this case.  They are used when you want to push some data from an Internet server to notify the user about an app that may not be running.

Provided your pile of iPod Touches and iPad have wi-fi access, GameKit would get you up and running quickly.  However, I believe an iPad is limited to 16 peers.

ContentLicense: CC BY-SA 2.5


问:
How to fetch user and page/company posts from linkedin
I have been checking the available linkedin API methods but cant see on how to fetch post by user and by page/company. What I need to do is that, user can enter username or a page/company name then, fetch news posts by it. Maybe you know some workarounds. Thanks

References:
https://developer.linkedin.com/docs/rest-api
https://apigee.com/console/linkedin?authTypeVal=oauth2&afterSuccessfulAuth=true

答:
Detail Infomation
  For search user

```<code>https://api.linkedin.com/v1/people/~
</code>```

Method : GET

Add a format=json URL argument to the end of your API call.

Add this
    HTTP header to your API call: x-li-format: json

Body:
Detail Infomation
  For search user

https://api.linkedin.com/v1/people/~

Method : GET

Add a format=json URL argument to the end of your API call.

Add this
    HTTP header to your API call: x-li-format: json


问:
angular2/javascript - NgFor looping through array inside of object
I have my own object with data which I loop through using ngFor. However there is an array part in the object, which I want to loop through as well in a

Currently it looks like this. However I don't want the complete string in one

 I just want one piece of the array there.

Relevant Code:

tier.model

```<code>export class Tier {
  constructor (
    public id: number,
    public title: string,
    public rewards: any[],
    public price: number
  )
  {}
}
</code>```

component:

```<code>export class PackagesComponent {  //will be renamed to TierComponent
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      ['Server access - Simple', 'Win something small', 'and so on'],
      5.00),
    new Tier(
      11,
      'Second Tier',
      ['Server access - Standard', 'Win something medium', 'and so on and on'],
      10.00),
    new Tier(
      12,
      'Third Tier',
      ['Server access - Advanced', 'Win something big', 'and so on and on and on'],
      10.00)
  ]
</code>```

template:

```<code><div class="row">
  <div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <ul class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tiers">
        {{ reward.rewards }}
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
</code>```

In the end it should look like this:

Something else I tried was this:

```<code><div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <!-- Show Mode -->
    <ul *ngIf="!editMode || tierToEdit != tier" class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tiers; let i=index">
        {{ reward.rewards[i] }}
      </li>
</code>```

Which than gave me the first element of the first array, the second element of the second array and the third element of the third array:

Hope this is not to confusing, still very new to angular/javascript, sorry for possibly asking stupid question or using wrong terms :) Thank you very much!

答:
You need to iterate on nested array in 2nd *ngFor as well, Like :

```<code> <div class="row">
   <div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <ul class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tier.rewards">
        {{reward}}
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
 </div>
</div>
</code>```

Body:
I have my own object with data which I loop through using ngFor. However there is an array part in the object, which I want to loop through as well in a

Currently it looks like this. However I don't want the complete string in one

 I just want one piece of the array there.

Relevant Code:

tier.model

export class Tier {
  constructor (
    public id: number,
    public title: string,
    public rewards: any[],
    public price: number
  )
  {}
}

component:

export class PackagesComponent {  //will be renamed to TierComponent
  public tierToEdit: Tier;
  editMode = false;
  tiers: Tier[] = [
    new Tier(
      10,
      'First Tier',
      ['Server access - Simple', 'Win something small', 'and so on'],
      5.00),
    new Tier(
      11,
      'Second Tier',
      ['Server access - Standard', 'Win something medium', 'and so on and on'],
      10.00),
    new Tier(
      12,
      'Third Tier',
      ['Server access - Advanced', 'Win something big', 'and so on and on and on'],
      10.00)
  ]

template:

        {{ tier.title }}

        {{ reward.rewards }}

{{ tier.price }}

        Edit
        SaveYes
        Get

In the end it should look like this:

Something else I tried was this:

        {{ tier.title }}

        {{ reward.rewards[i] }}

Which than gave me the first element of the first array, the second element of the second array and the third element of the third array:

Hope this is not to confusing, still very new to angular/javascript, sorry for possibly asking stupid question or using wrong terms :) Thank you very much!

Body:
You need to iterate on nested array in 2nd *ngFor as well, Like :

 <div class="row">
   <div  class="col-md-4" *ngFor="let tier of tiers; let i=index;">
    <ul class="pricing-table">
      <li class="plan-name">
        {{ tier.title }}
      </li>
      <li *ngFor="let reward of tier.rewards">
        {{reward}}
      </li>
      <p class="plan-price">{{ tier.price }}</p>
      <li class="plan-action">
        <a class="btn btn-primary" (click)="onEdit(tier)">Edit</a>
        <a class="btn btn-success" (click)="this.clickSave()">SaveYes</a>
        <a class="btn btn-warning" >Get</a>
      </li>
    </ul>
 </div>
</div>


问:
How do I iterate through a ManyToManyField in django-jinja project?
I am trying to create a blog app which has posts and each posts have title, date, link and tags.

This is my models.py

```<code># models.py
from django.db import models

class Tag(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Post(models.Model):
    title = models.CharField(max_length=300)
    date = models.DateTimeField()
    link = models.URLField()
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.title

    @property
    def tags_name(self):
        return [x.name for x in self.tags]

    class Meta:
        ordering = ('date',)
</code>```

This is my views.py

```<code># views.py
from django.conf.urls import url, include
from django.views.generic import ListView
from blog.models import Post

urlpatterns = [
    url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date"), template_name="blog/blog_list.html")),
]
</code>```

This is my blog_list.html

```<code><!-- blog_list.html -->
{% extends "mysite/layout.html" %}

{% block content %}
  <h1>my blog posts</h1>
  <ul>
    {% for post in object_list %}
      <li><span class="title"><a href="{{ post.link }}">{{ post.title }}</a></span></li>
      <p>{{ post.date|date:"d-m-Y" }}</p>
    {% endfor %}
  </ul>
{% endblock %}

{% block sidebar %}
  <h4 id="sidenav">tags</h4>
  {% for post in object_list %}
    <ul>
      <!-- I want to show the tags here -->
    </ul>
  {% endfor %}
{% endblock %}
</code>```

In the blog_list.html, I am showing all the post details and on the sidebar, I want to show all the tags present from all the blog posts available. Since post.tags is ManyToManyField, how can I iterate through it?

答:
You want to use .all in the template to get all the elements in the relationship:

```<code>{% for tag in post.tags.all %}
    {{ tag }}
{% endfor %}
</code>```

Thanks to @hansTheFranz for correcting my bracket issue.

Regarding not repeating tags, this would be very difficult with the current context. You might want to look into instead getting the posts in your View and extracting the tags there, where you have more freedom to check for duplicates. Something like this:

```<code>def tags(request):
    posts = Post.objects.all()
    tag_list = []
    for post in posts:
        tags = post.tags.all()
        for tag in tag:
            if not (tag in tag_list):
                tag_list.append(tag)
    context_dict = { "tags": tag_list, "posts": posts }
    return render(request, 'blog/blog_list.html', context_dict)

urlpatterns = [
    url(r'^$', tags, name="tags"),
]
</code>```

And then change your template to be more like:

```<code>{% block sidebar %}
  <h4 id="sidenav">tags</h4>
    <ul>
      {% for tag in tags %}
        <li>{{ tag }}</li>
      {% endfor %}
    </ul>
{% endblock %}
</code>```

Additionally, instead of referencing object_list you can now access the list of posts by referencing posts, because we have defined the list of posts as such in our context dictionary, which is being passed to the template.

I'm afraid I have not tested this and it may not be very efficient, but roughly speaking it should work. A lecturer at my university wrote this book: http://www.tangowithdjango.com/book17/, which encourages more of a style of writing views as I have done: separate from the URLs. If anything I've done seems unclear or contrary, you may want to have a look at the book and see if anything there makes more sense.

Body:
I am trying to create a blog app which has posts and each posts have title, date, link and tags.

This is my models.py

# models.py
from django.db import models

class Tag(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Post(models.Model):
    title = models.CharField(max_length=300)
    date = models.DateTimeField()
    link = models.URLField()
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.title

    @property
    def tags_name(self):
        return [x.name for x in self.tags]

    class Meta:
        ordering = ('date',)

This is my views.py

# views.py
from django.conf.urls import url, include
from django.views.generic import ListView
from blog.models import Post

urlpatterns = [
    url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date"), template_name="blog/blog_list.html")),
]

This is my blog_list.html

{% extends "mysite/layout.html" %}

{% block content %}

my blog posts

    {% for post in object_list %}

{{ post.title }}

{{ post.date|date:"d-m-Y" }}

    {% endfor %}

{% endblock %}

{% block sidebar %}

tags

  {% for post in object_list %}

  {% endfor %}
{% endblock %}

In the blog_list.html, I am showing all the post details and on the sidebar, I want to show all the tags present from all the blog posts available. Since post.tags is ManyToManyField, how can I iterate through it?

Body:
You want to use .all in the template to get all the elements in the relationship:

{% for tag in post.tags.all %}
    {{ tag }}
{% endfor %}

Thanks to @hansTheFranz for correcting my bracket issue.

Regarding not repeating tags, this would be very difficult with the current context. You might want to look into instead getting the posts in your View and extracting the tags there, where you have more freedom to check for duplicates. Something like this:

def tags(request):
    posts = Post.objects.all()
    tag_list = []
    for post in posts:
        tags = post.tags.all()
        for tag in tag:
            if not (tag in tag_list):
                tag_list.append(tag)
    context_dict = { "tags": tag_list, "posts": posts }
    return render(request, 'blog/blog_list.html', context_dict)

urlpatterns = [
    url(r'^$', tags, name="tags"),
]

And then change your template to be more like:

{% block sidebar %}
  <h4 id="sidenav">tags</h4>
    <ul>
      {% for tag in tags %}
        <li>{{ tag }}</li>
      {% endfor %}
    </ul>
{% endblock %}

Additionally, instead of referencing object_list you can now access the list of posts by referencing posts, because we have defined the list of posts as such in our context dictionary, which is being passed to the template.

I'm afraid I have not tested this and it may not be very efficient, but roughly speaking it should work. A lecturer at my university wrote this book: http://www.tangowithdjango.com/book17/, which encourages more of a style of writing views as I have done: separate from the URLs. If anything I've done seems unclear or contrary, you may want to have a look at the book and see if anything there makes more sense.


问:
How to send "back to normal" notifications in Jenkins Declarative Pipeline?
I'm trying to convert an existing Jenkins Pipeline to the new Declarative Pipeline and I was wondering how to handle correctly mail notifications ?

I'm currently using this code:

```<code>node {
   try {

      ...

      currentBuild.result = 'SUCCESS'
   } catch (any) {
       currentBuild.result = 'FAILURE'
       throw any
   } finally {
       step([$class: 'Mailer',
           notifyEveryUnstableBuild: true,
           recipients: "baptiste.wicht@gmail.com",
           sendToIndividuals: true])
   }
}
</code>```

It works well, but I don't see how to use the new declarative syntax for this. I think something could be done by using post() and the different notifications, but I don't know exactly how. I've tried this:

```<code>post {
    always {
        step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "baptiste.wicht@gmail.com",
            sendToIndividuals: true])
    }
}
</code>```

But the problem is that it does not send any "Back to normal" mail.

How can I used the Mailer plugin in a Jenkins declarative pipeline in order to send "Back to normal" mails ?

Should use again a try/catch around all declarative syntax ?

答:
Problem is that in the post section of declarative the currentBuild.result is not set to SUCCESS. FAILURE and ABORTED is set though. So the behaviour here seems to be inconsistent at the moment.

I've improved my answer from How to get same Mailer behaviour for Jenkins pipeline to handle this case better:

```<code>pipeline {
  agent any
  stages {
      stage('test') {
        steps {
            echo 'some steps'
            // error("Throw exception for testing purpose..")
        }
      }
  }
  post {
      always {
          script {
              if (currentBuild.result == null) {
                  currentBuild.result = 'SUCCESS'
              }
          }
          step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "test@test.com",
            sendToIndividuals: true])
      }
  }
}
</code>```

Body:
I'm trying to convert an existing Jenkins Pipeline to the new Declarative Pipeline and I was wondering how to handle correctly mail notifications ?

I'm currently using this code:

node {
   try {

      ...

      currentBuild.result = 'SUCCESS'
   } catch (any) {
       currentBuild.result = 'FAILURE'
       throw any
   } finally {
       step([$class: 'Mailer',
           notifyEveryUnstableBuild: true,
           recipients: "baptiste.wicht@gmail.com",
           sendToIndividuals: true])
   }
}

It works well, but I don't see how to use the new declarative syntax for this. I think something could be done by using post() and the different notifications, but I don't know exactly how. I've tried this:

post {
    always {
        step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "baptiste.wicht@gmail.com",
            sendToIndividuals: true])
    }
}

But the problem is that it does not send any "Back to normal" mail.

How can I used the Mailer plugin in a Jenkins declarative pipeline in order to send "Back to normal" mails ?

Should use again a try/catch around all declarative syntax ?

Body:
Problem is that in the post section of declarative the currentBuild.result is not set to SUCCESS. FAILURE and ABORTED is set though. So the behaviour here seems to be inconsistent at the moment.

I've improved my answer from How to get same Mailer behaviour for Jenkins pipeline to handle this case better:

pipeline {
  agent any
  stages {
      stage('test') {
        steps {
            echo 'some steps'
            // error("Throw exception for testing purpose..")
        }
      }
  }
  post {
      always {
          script {
              if (currentBuild.result == null) {
                  currentBuild.result = 'SUCCESS'
              }
          }
          step([$class: 'Mailer',
            notifyEveryUnstableBuild: true,
            recipients: "test@test.com",
            sendToIndividuals: true])
      }
  }
}


问:
Getting unknown property: yii\db\ActiveQuery::reg_no
I need help on this, I have a model

```<code>/**
 * This is the model class for table "student_attachment_details".
 *
 * @property integer $createdBy
 * @property string $reg_no
 * @property string $county_attached
 * @property string $closest_town
 * @property string $company_attached
 * @property integer $company_phone_number
 * @property string $is_assessed
 * @property string $location_description
 * @property integer $department_id
 * @property string $allocated_staff_id
 */

 class StudentAttachmentDetails extends \yii\db\ActiveRecord
 {
</code>```

But when i try to query the model like this

```<code>$student_details = StudentAttachmentDetails::find()
                                ->where(['allocated_staff_id'=>'no'])
                                ->limit(1);
</code>```

And then try to get a value with this

```<code> $reg_no = $student_details->reg_no;
</code>```

I get this error

```<code>Getting unknown property: yii\db\ActiveQuery::reg_no
</code>```

What am I doing wrong?

答:
the method ActiveRecord::find() returns an ActiveQuery; to access the actual model (in your case of class StudentAttachmentDetails) you need to call a method to execute the ActiveQuery.

something like

```<code>$student_details = StudentAttachmentDetails::find()
                            ->where(['allocated_staff_id'=>'no'])
                            ->limit(1)->one();
</code>```

will give you the record you are looking for. The docs for ActiveRecord::find() can be found here and ActiveQuery::one() here.

Body:
I need help on this, I have a model

/**
 * This is the model class for table "student_attachment_details".
 *
 * @property integer $createdBy
 * @property string $reg_no
 * @property string $county_attached
 * @property string $closest_town
 * @property string $company_attached
 * @property integer $company_phone_number
 * @property string $is_assessed
 * @property string $location_description
 * @property integer $department_id
 * @property string $allocated_staff_id
 */

 class StudentAttachmentDetails extends \yii\db\ActiveRecord
 {

But when i try to query the model like this

$student_details = StudentAttachmentDetails::find()
                                ->where(['allocated_staff_id'=>'no'])
                                ->limit(1);

And then try to get a value with this

 $reg_no = $student_details->reg_no;

I get this error

Getting unknown property: yii\db\ActiveQuery::reg_no

What am I doing wrong?

Body:
the method ActiveRecord::find() returns an ActiveQuery; to access the actual model (in your case of class StudentAttachmentDetails) you need to call a method to execute the ActiveQuery.

something like

$student_details = StudentAttachmentDetails::find()
                            ->where(['allocated_staff_id'=>'no'])
                            ->limit(1)->one();

will give you the record you are looking for. The docs for ActiveRecord::find() can be found here and ActiveQuery::one() here.


问:
Jquery - adding next button to tabs
I am trying to get the next button to tab through the tabs. Any help appreciated. The html is at the Codepen snippet.

Thanks in advance.

```<code>function tabsResponsive() {
    $('.accordion-tabs').each(function(index) {
      $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
    });
    $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
      if (!$(this).hasClass('is-active')) {
        event.preventDefault();
        var accordionTabs = $(this).closest('.accordion-tabs');
        accordionTabs.find('.is-open').removeClass('is-open').hide();

        $(this).next().toggleClass('is-open').toggle();
        accordionTabs.find('.is-active').removeClass('is-active');
        $(this).addClass('is-active');
      } else {
        event.preventDefault();
      }
    });

  }

  function tabsNext() {
    $('.nextContaner__link').click(function() {
      $('.tab-link').each(function(index) {

        if ($(this).hasClass('is-active')) {

          $(this).removeClass('is-active');
          $(this).parent().siblings('li').next('').children('a').addClass('is-active');

        } else {
          event.preventDefault();
        }

        // $(this).removeClass('is-active');
        // $(this).parent().siblings('li').next().children('a').addClass('is-active');
      });
    });
  }
</code>```

答:
Simple , without using a class on link , you've just to check active tab , then set the next tab's link to active and remove from the previous ,

your function should look like

```<code>function tabsNext() {
  $('.nextContaner__link').click(function() {
    var $tab = $(".is-active.tab-link");
    console.log()
    if ($tab.parent().next().hasClass("tab-header-and-content")) {
      $tab.parent().find(".tab-content").hide();
      $tab.parent().next().find("a").addClass("is-active");
      $tab.parent().next().find(".tab-content").show();
      $tab.removeClass("is-active")
    }else {
      $tab.parent().find(".tab-content").hide();
      $tab.removeClass("is-active");
      $(".tab-header-and-content").eq(0).find(".tab-link").addClass("is-active");
      $(".tab-header-and-content .tab-content").eq(0).show();
    }

  });
}
</code>```

bellow a snippet , please exeute it in full screen :

function tabsResponsive() {
  $('.accordion-tabs').each(function(index) {
    $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
  });
  $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
    if (!$(this).hasClass('is-active')) {
      event.preventDefault();
      var accordionTabs = $(this).closest('.accordion-tabs');
      accordionTabs.find('.is-open').removeClass('is-open').hide();

      $(this).next().toggleClass('is-open').toggle();
      accordionTabs.find('.is-active').removeClass('is-active');
      $(this).addClass('is-active');
    } else {
      event.preventDefault();
    }
  });

}

function tabsNext() {
  $('.nextContaner__link').click(function() {
    var $tab = $(".is-active.tab-link");

    if ($tab.parent().next().hasClass("tab-header-and-content")) {
      $tab.parent().find(".tab-content").hide();
      $tab.parent().next().find("a").addClass("is-active");
      $tab.parent().next().find(".tab-content").show();
      $tab.removeClass("is-active")
    }else {
      $tab.parent().find(".tab-content").hide();
      $tab.removeClass("is-active");
      $(".tab-header-and-content").eq(0).find(".tab-link").addClass("is-active");
      $(".tab-header-and-content .tab-content").eq(0).show();
    }

  });
}

//--------------------------------------------------------------------------------------------------------------
// DOCUMENT READY

$(function() {

  tabsResponsive();
  tabsNext();

}); // END DOCUMENT READY

//--------------------------------------------------------------------------------------------------------------
// WINDOW LOAD

$(window).load(function() {
  w = $(window).width();

}); // END WINDOW LOAD

//--------------------------------------------------------------------------------------------------------------
// WINDOW RESIZE

// var resizeTimer;
// $(window).on('resize orientationchange', function() {
//
//   if( w !== $( window ).width() ){
//
//     clearTimeout(resizeTimer);
//
//     //stuff that gets delayed
//     resizeTimer = setTimeout(function() {
//
//
//     }, 600);
//
//
//     w = $( window ).width();
//   }
// });  // END WINDOW RESIZE```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordion-tabs {
  margin-top:40px;
}

html {
  line-height: 1.15;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */
}

/* Sections
       ========================================================================== */

/**
     * Remove the margin in all browsers (opinionated).
     */

body {
  margin: 0;
}

/**
     * Add the correct display in IE 9-.
     */

article,
aside,
footer,
header,
nav,
section {
  display: block;
}

/**
     * Correct the font size and margin on `h1` elements within `section` and
     * `article` contexts in Chrome, Firefox, and Safari.
     */

h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

/* Grouping content
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

figcaption,
figure {
  display: block;
}

/**
     * Add the correct margin in IE 8.
     */

figure {
  margin: 1em 40px;
}

/**
     * 1. Add the correct box sizing in Firefox.
     * 2. Show the overflow in Edge and IE.
     */

hr {
  box-sizing: content-box;
  /* 1 */
  height: 0;
  /* 1 */
  overflow: visible;
  /* 2 */
}

/**
     * Add the correct display in IE.
     */

main {
  display: block;
}

/**
     * 1. Correct the inheritance and scaling of font size in all browsers.
     * 2. Correct the odd `em` font sizing in all browsers.
     */

pre {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/* Links
       ========================================================================== */

/**
     * 1. Remove the gray background on active links in IE 10.
     * 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
     */

a {
  background-color: transparent;
  /* 1 */
  -webkit-text-decoration-skip: objects;
  /* 2 */
}

/* Text-level semantics
       ========================================================================== */

/**
     * 1. Remove the bottom border in Chrome 57- and Firefox 39-.
     * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
     */

abbr[title] {
  border-bottom: none;
  /* 1 */
  text-decoration: underline;
  /* 2 */
  text-decoration: underline dotted;
  /* 2 */
}

/**
     * Prevent the duplicate application of `bolder` by the next rule in Safari 6.
     */

b,
strong {
  font-weight: inherit;
}

/**
     * Add the correct font weight in Chrome, Edge, and Safari.
     */

b,
strong {
  font-weight: bolder;
}

/**
     * 1. Correct the inheritance and scaling of font size in all browsers.
     * 2. Correct the odd `em` font sizing in all browsers.
     */

code,
kbd,
samp {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/**
     * Add the correct font style in Android 4.3-.
     */

dfn {
  font-style: italic;
}

/**
     * Add the correct background and color in IE 9-.
     */

mark {
  background-color: #ff0;
  color: #000;
}

/**
     * Add the correct font size in all browsers.
     */

small {
  font-size: 80%;
}

/**
     * Prevent `sub` and `sup` elements from affecting the line height in
     * all browsers.
     */

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/* Embedded content
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

audio,
video {
  display: inline-block;
}

/**
     * Add the correct display in iOS 4-7.
     */

audio:not([controls]) {
  display: none;
  height: 0;
}

/**
     * Remove the border on images inside links in IE 10-.
     */

img {
  border-style: none;
}

/**
     * Hide the overflow in IE.
     */

svg:not(:root) {
  overflow: hidden;
}

/* Forms
       ========================================================================== */

/**
     * 1. Change the font styles in all browsers (opinionated).
     * 2. Remove the margin in Firefox and Safari.
     */

button,
input,
optgroup,
select,
textarea {
  font-family: sans-serif;
  /* 1 */
  font-size: 100%;
  /* 1 */
  line-height: 1.15;
  /* 1 */
  margin: 0;
  /* 2 */
}

/**
     * Show the overflow in IE.
     */

button {
  overflow: visible;
}

/**
     * Remove the inheritance of text transform in Edge, Firefox, and IE.
     * 1. Remove the inheritance of text transform in Firefox.
     */

button,
select {
  /* 1 */
  text-transform: none;
}

/**
     * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
     *    controls in Android 4.
     * 2. Correct the inability to style clickable types in iOS and Safari.
     */

button,
html [type="button"],
[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
}

button,
[type="button"],
[type="reset"],
[type="submit"] {
  /**
       * Remove the inner border and padding in Firefox.
       */
  /**
       * Restore the focus styles unset by the previous rule.
       */
}

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
     * Show the overflow in Edge.
     */

input {
  overflow: visible;
}

/**
     * 1. Add the correct box sizing in IE 10-.
     * 2. Remove the padding in IE 10-.
     */

[type="checkbox"],
[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */
}

/**
     * Correct the cursor style of increment and decrement buttons in Chrome.
     */

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  height: auto;
}

/**
     * 1. Correct the odd appearance in Chrome and Safari.
     * 2. Correct the outline style in Safari.
     */

[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  outline-offset: -2px;
  /* 2 */
  /**
       * Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
       */
}

[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

/**
     * 1. Correct the inability to style clickable types in iOS and Safari.
     * 2. Change font properties to `inherit` in Safari.
     */

::-webkit-file-upload-button {
  -webkit-appearance: button;
  /* 1 */
  font: inherit;
  /* 2 */
}

/**
     * Correct the padding in Firefox.
     */

fieldset {
  padding: 0.35em 0.75em 0.625em;
}

/**
     * 1. Correct the text wrapping in Edge and IE.
     * 2. Correct the color inheritance from `fieldset` elements in IE.
     * 3. Remove the padding so developers are not caught out when they zero out
     *    `fieldset` elements in all browsers.
     */

legend {
  box-sizing: border-box;
  /* 1 */
  display: table;
  /* 1 */
  max-width: 100%;
  /* 1 */
  padding: 0;
  /* 3 */
  color: inherit;
  /* 2 */
  white-space: normal;
  /* 1 */
}

/**
     * 1. Add the correct display in IE 9-.
     * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
     */

progress {
  display: inline-block;
  /* 1 */
  vertical-align: baseline;
  /* 2 */
}

/**
     * Remove the default vertical scrollbar in IE.
     */

textarea {
  overflow: auto;
}

/* Interactive
       ========================================================================== */

/*
     * Add the correct display in Edge, IE, and Firefox.
     */

details {
  display: block;
}

/*
     * Add the correct display in all browsers.
     */

summary {
  display: list-item;
}

/*
     * Add the correct display in IE 9-.
     */

menu {
  display: block;
}

/* Scripting
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

canvas {
  display: inline-block;
}

/**
     * Add the correct display in IE.
     */

template {
  display: none;
}

/* Hidden
       ========================================================================== */

/**
     * Add the correct display in IE 10-.
     */

[hidden] {
  display: none;
}

/* -------------------------------------------------------------
  Sass CSS3 Mixins! The Cross-Browser CSS3 Sass Library
  By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @matthieu_tweets

  List of CSS3 Sass Mixins File to be @imported and @included as you need

  The purpose of this library is to facilitate the use of CSS3 on different browsers avoiding HARD TO READ and NEVER
  ENDING css files

  note: All CSS3 Properties are being supported by Safari 5
  more info: http://www.findmebyip.com/litmus/#css3-properties

------------------------------------------------------------- */

.wrap {
  max-width: 1600px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 10px;
}

.wrap:after {
  content: " ";
  display: block;
  clear: both;
}

.accordion-tabs {
  line-height: 1.5;
  margin-bottom: 1.5em;
  padding: 0;
  width: 100%;
}

.accordion-tabs::after {
  clear: both;
  content: "";
  display: block;
}

.accordion-tabs .tab-header-and-content {
  list-style: none;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-header-and-content {
    display: inline;
  }
}

@media (min-width: 40em) {
  .accordion-tabs .tab-header-and-content:first-child .tab-link {
    border-top: 0;
  }
}

.accordion-tabs .tab-link {
  background-color: #fff;
  color: #333;
  display: block;
  font-weight: bold;
  padding: 0.75em 0;
  text-decoration: none;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-link {
    border-left: 0;
    border-right: 0;
    border-top: 0;
    display: inline-block;
    width: 23%;
    text-align: center;
  }
}

.accordion-tabs .tab-link:hover {
  color: #477dca;
}

.accordion-tabs .tab-link:focus {
  outline: none;
}

.accordion-tabs .tab-link.is-active {
  background-color: #fff;
  color: #0a79bc;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-link.is-active {
    background-color: #fff;
    border-bottom: 2px solid #0a79bc;
    margin-bottom: -1px;
  }
}

.accordion-tabs .tab-content {
  background: #fff;
  display: none;
  padding: 1.5em 1.5em;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-content {
    float: left;
  }
}

.accordion-tabs .nextContainer {
  list-style: none;
  display: block;
  width: 100%;
  clear: both;
}

.accordion-tabs .nextContaner__link {
  padding: 20px;
  display: block;
  float: right;
}</code>```

    Tab Item

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tincidunt pellentesque lorem, id suscipit dolor rutrum id. Morbi facilisis porta volutpat. Fusce adipiscing, mauris quis congue tincidunt, sapien purus suscipit odio, quis dictum odio
        tortor in sem. Ut sit amet libero nec orci mattis fringilla. Praesent eu ipsum in sapien tincidunt molestie sed ut magna. Nam accumsan dui at orci rhoncus pharetra tincidunt elit ullamcorper. Sed ac mauris ipsum. Nullam imperdiet sapien id purus
        pretium id aliquam mi ullamcorper.

    Another Tab

Ut laoreet augue et neque pretium non sagittis nibh pulvinar. Etiam ornare tincidunt orci quis ultrices. Pellentesque ac sapien ac purus gravida ullamcorper. Duis rhoncus sodales lacus, vitae adipiscing tellus pharetra sed. Praesent bibendum lacus
        quis metus condimentum ac accumsan orci vulputate. Aenean fringilla massa vitae metus facilisis congue. Morbi placerat eros ac sapien semper pulvinar. Vestibulum facilisis, ligula a molestie venenatis, metus justo ullamcorper ipsum, congue aliquet
        dolor tortor eu neque. Sed imperdiet, nibh ut vestibulum tempor, nibh dui volutpat lacus, vel gravida magna justo sit amet quam. Quisque tincidunt ligula at nisl imperdiet sagittis. Morbi rutrum tempor arcu, non ultrices sem semper a. Aliquam
        quis sem mi.

    Third

Donec mattis mauris gravida metus laoreet non rutrum sem viverra. Aenean nibh libero, viverra vel vestibulum in, porttitor ut sapien. Phasellus tempor lorem id justo ornare tincidunt. Nulla faucibus, purus eu placerat fermentum, velit mi iaculis
        nunc, bibendum tincidunt ipsum justo eu mauris. Nulla facilisi. Vestibulum vel lectus ac purus tempus suscipit nec sit amet eros. Nullam fringilla, enim eu lobortis dapibus, quam magna tincidunt nibh, sit amet imperdiet dolor justo congue turpis.

    Last Item

Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus dui urna.

    Next

```

Title: Jquery - adding next button to tabs

Body:
I am trying to get the next button to tab through the tabs. Any help appreciated. The html is at the Codepen snippet.

Thanks in advance.

function tabsResponsive() {
    $('.accordion-tabs').each(function(index) {
      $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
    });
    $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
      if (!$(this).hasClass('is-active')) {
        event.preventDefault();
        var accordionTabs = $(this).closest('.accordion-tabs');
        accordionTabs.find('.is-open').removeClass('is-open').hide();

        $(this).next().toggleClass('is-open').toggle();
        accordionTabs.find('.is-active').removeClass('is-active');
        $(this).addClass('is-active');
      } else {
        event.preventDefault();
      }
    });

  }

  function tabsNext() {
    $('.nextContaner__link').click(function() {
      $('.tab-link').each(function(index) {

        if ($(this).hasClass('is-active')) {

          $(this).removeClass('is-active');
          $(this).parent().siblings('li').next('').children('a').addClass('is-active');

        } else {
          event.preventDefault();
        }

        // $(this).removeClass('is-active');
        // $(this).parent().siblings('li').next().children('a').addClass('is-active');
      });
    });
  }

Body:
Simple , without using a class on link , you've just to check active tab , then set the next tab's link to active and remove from the previous ,

your function should look like

function tabsNext() {
  $('.nextContaner__link').click(function() {
    var $tab = $(".is-active.tab-link");
    console.log()
    if ($tab.parent().next().hasClass("tab-header-and-content")) {
      $tab.parent().find(".tab-content").hide();
      $tab.parent().next().find("a").addClass("is-active");
      $tab.parent().next().find(".tab-content").show();
      $tab.removeClass("is-active")
    }else {
      $tab.parent().find(".tab-content").hide();
      $tab.removeClass("is-active");
      $(".tab-header-and-content").eq(0).find(".tab-link").addClass("is-active");
      $(".tab-header-and-content .tab-content").eq(0).show();
    }

  });
}

bellow a snippet , please exeute it in full screen :

function tabsResponsive() {
  $('.accordion-tabs').each(function(index) {
    $(this).children('li').first().children('a').addClass('is-active').next().addClass('is-open').show();
  });
  $('.accordion-tabs').on('click', 'li > a.tab-link', function(event) {
    if (!$(this).hasClass('is-active')) {
      event.preventDefault();
      var accordionTabs = $(this).closest('.accordion-tabs');
      accordionTabs.find('.is-open').removeClass('is-open').hide();

      $(this).next().toggleClass('is-open').toggle();
      accordionTabs.find('.is-active').removeClass('is-active');
      $(this).addClass('is-active');
    } else {
      event.preventDefault();
    }
  });

}

function tabsNext() {
  $('.nextContaner__link').click(function() {
    var $tab = $(".is-active.tab-link");

    if ($tab.parent().next().hasClass("tab-header-and-content")) {
      $tab.parent().find(".tab-content").hide();
      $tab.parent().next().find("a").addClass("is-active");
      $tab.parent().next().find(".tab-content").show();
      $tab.removeClass("is-active")
    }else {
      $tab.parent().find(".tab-content").hide();
      $tab.removeClass("is-active");
      $(".tab-header-and-content").eq(0).find(".tab-link").addClass("is-active");
      $(".tab-header-and-content .tab-content").eq(0).show();
    }

  });
}

//--------------------------------------------------------------------------------------------------------------
// DOCUMENT READY

$(function() {

  tabsResponsive();
  tabsNext();

}); // END DOCUMENT READY

//--------------------------------------------------------------------------------------------------------------
// WINDOW LOAD

$(window).load(function() {
  w = $(window).width();

}); // END WINDOW LOAD

//--------------------------------------------------------------------------------------------------------------
// WINDOW RESIZE

// var resizeTimer;
// $(window).on('resize orientationchange', function() {
//
//   if( w !== $( window ).width() ){
//
//     clearTimeout(resizeTimer);
//
//     //stuff that gets delayed
//     resizeTimer = setTimeout(function() {
//
//
//     }, 600);
//
//
//     w = $( window ).width();
//   }
// });  // END WINDOW RESIZE

.accordion-tabs {
  margin-top:40px;
}

html {
  line-height: 1.15;
  /* 1 */
  -ms-text-size-adjust: 100%;
  /* 2 */
  -webkit-text-size-adjust: 100%;
  /* 2 */
}

/* Sections
       ========================================================================== */

/**
     * Remove the margin in all browsers (opinionated).
     */

body {
  margin: 0;
}

/**
     * Add the correct display in IE 9-.
     */

article,
aside,
footer,
header,
nav,
section {
  display: block;
}

/**
     * Correct the font size and margin on `h1` elements within `section` and
     * `article` contexts in Chrome, Firefox, and Safari.
     */

h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

/* Grouping content
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

figcaption,
figure {
  display: block;
}

/**
     * Add the correct margin in IE 8.
     */

figure {
  margin: 1em 40px;
}

/**
     * 1. Add the correct box sizing in Firefox.
     * 2. Show the overflow in Edge and IE.
     */

hr {
  box-sizing: content-box;
  /* 1 */
  height: 0;
  /* 1 */
  overflow: visible;
  /* 2 */
}

/**
     * Add the correct display in IE.
     */

main {
  display: block;
}

/**
     * 1. Correct the inheritance and scaling of font size in all browsers.
     * 2. Correct the odd `em` font sizing in all browsers.
     */

pre {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/* Links
       ========================================================================== */

/**
     * 1. Remove the gray background on active links in IE 10.
     * 2. Remove gaps in links underline in iOS 8+ and Safari 8+.
     */

a {
  background-color: transparent;
  /* 1 */
  -webkit-text-decoration-skip: objects;
  /* 2 */
}

/* Text-level semantics
       ========================================================================== */

/**
     * 1. Remove the bottom border in Chrome 57- and Firefox 39-.
     * 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
     */

abbr[title] {
  border-bottom: none;
  /* 1 */
  text-decoration: underline;
  /* 2 */
  text-decoration: underline dotted;
  /* 2 */
}

/**
     * Prevent the duplicate application of `bolder` by the next rule in Safari 6.
     */

b,
strong {
  font-weight: inherit;
}

/**
     * Add the correct font weight in Chrome, Edge, and Safari.
     */

b,
strong {
  font-weight: bolder;
}

/**
     * 1. Correct the inheritance and scaling of font size in all browsers.
     * 2. Correct the odd `em` font sizing in all browsers.
     */

code,
kbd,
samp {
  font-family: monospace, monospace;
  /* 1 */
  font-size: 1em;
  /* 2 */
}

/**
     * Add the correct font style in Android 4.3-.
     */

dfn {
  font-style: italic;
}

/**
     * Add the correct background and color in IE 9-.
     */

mark {
  background-color: #ff0;
  color: #000;
}

/**
     * Add the correct font size in all browsers.
     */

small {
  font-size: 80%;
}

/**
     * Prevent `sub` and `sup` elements from affecting the line height in
     * all browsers.
     */

sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sub {
  bottom: -0.25em;
}

sup {
  top: -0.5em;
}

/* Embedded content
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

audio,
video {
  display: inline-block;
}

/**
     * Add the correct display in iOS 4-7.
     */

audio:not([controls]) {
  display: none;
  height: 0;
}

/**
     * Remove the border on images inside links in IE 10-.
     */

img {
  border-style: none;
}

/**
     * Hide the overflow in IE.
     */

svg:not(:root) {
  overflow: hidden;
}

/* Forms
       ========================================================================== */

/**
     * 1. Change the font styles in all browsers (opinionated).
     * 2. Remove the margin in Firefox and Safari.
     */

button,
input,
optgroup,
select,
textarea {
  font-family: sans-serif;
  /* 1 */
  font-size: 100%;
  /* 1 */
  line-height: 1.15;
  /* 1 */
  margin: 0;
  /* 2 */
}

/**
     * Show the overflow in IE.
     */

button {
  overflow: visible;
}

/**
     * Remove the inheritance of text transform in Edge, Firefox, and IE.
     * 1. Remove the inheritance of text transform in Firefox.
     */

button,
select {
  /* 1 */
  text-transform: none;
}

/**
     * 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`
     *    controls in Android 4.
     * 2. Correct the inability to style clickable types in iOS and Safari.
     */

button,
html [type="button"],
[type="reset"],
[type="submit"] {
  -webkit-appearance: button;
  /* 2 */
}

button,
[type="button"],
[type="reset"],
[type="submit"] {
  /**
       * Remove the inner border and padding in Firefox.
       */
  /**
       * Restore the focus styles unset by the previous rule.
       */
}

button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
  border-style: none;
  padding: 0;
}

button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
  outline: 1px dotted ButtonText;
}

/**
     * Show the overflow in Edge.
     */

input {
  overflow: visible;
}

/**
     * 1. Add the correct box sizing in IE 10-.
     * 2. Remove the padding in IE 10-.
     */

[type="checkbox"],
[type="radio"] {
  box-sizing: border-box;
  /* 1 */
  padding: 0;
  /* 2 */
}

/**
     * Correct the cursor style of increment and decrement buttons in Chrome.
     */

[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
  height: auto;
}

/**
     * 1. Correct the odd appearance in Chrome and Safari.
     * 2. Correct the outline style in Safari.
     */

[type="search"] {
  -webkit-appearance: textfield;
  /* 1 */
  outline-offset: -2px;
  /* 2 */
  /**
       * Remove the inner padding and cancel buttons in Chrome and Safari on macOS.
       */
}

[type="search"]::-webkit-search-cancel-button,
[type="search"]::-webkit-search-decoration {
  -webkit-appearance: none;
}

/**
     * 1. Correct the inability to style clickable types in iOS and Safari.
     * 2. Change font properties to `inherit` in Safari.
     */

::-webkit-file-upload-button {
  -webkit-appearance: button;
  /* 1 */
  font: inherit;
  /* 2 */
}

/**
     * Correct the padding in Firefox.
     */

fieldset {
  padding: 0.35em 0.75em 0.625em;
}

/**
     * 1. Correct the text wrapping in Edge and IE.
     * 2. Correct the color inheritance from `fieldset` elements in IE.
     * 3. Remove the padding so developers are not caught out when they zero out
     *    `fieldset` elements in all browsers.
     */

legend {
  box-sizing: border-box;
  /* 1 */
  display: table;
  /* 1 */
  max-width: 100%;
  /* 1 */
  padding: 0;
  /* 3 */
  color: inherit;
  /* 2 */
  white-space: normal;
  /* 1 */
}

/**
     * 1. Add the correct display in IE 9-.
     * 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.
     */

progress {
  display: inline-block;
  /* 1 */
  vertical-align: baseline;
  /* 2 */
}

/**
     * Remove the default vertical scrollbar in IE.
     */

textarea {
  overflow: auto;
}

/* Interactive
       ========================================================================== */

/*
     * Add the correct display in Edge, IE, and Firefox.
     */

details {
  display: block;
}

/*
     * Add the correct display in all browsers.
     */

summary {
  display: list-item;
}

/*
     * Add the correct display in IE 9-.
     */

menu {
  display: block;
}

/* Scripting
       ========================================================================== */

/**
     * Add the correct display in IE 9-.
     */

canvas {
  display: inline-block;
}

/**
     * Add the correct display in IE.
     */

template {
  display: none;
}

/* Hidden
       ========================================================================== */

/**
     * Add the correct display in IE 10-.
     */

[hidden] {
  display: none;
}

/* -------------------------------------------------------------
  Sass CSS3 Mixins! The Cross-Browser CSS3 Sass Library
  By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @matthieu_tweets

  List of CSS3 Sass Mixins File to be @imported and @included as you need

  The purpose of this library is to facilitate the use of CSS3 on different browsers avoiding HARD TO READ and NEVER
  ENDING css files

  note: All CSS3 Properties are being supported by Safari 5
  more info: http://www.findmebyip.com/litmus/#css3-properties

------------------------------------------------------------- */

.wrap {
  max-width: 1600px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 10px;
}

.wrap:after {
  content: " ";
  display: block;
  clear: both;
}

.accordion-tabs {
  line-height: 1.5;
  margin-bottom: 1.5em;
  padding: 0;
  width: 100%;
}

.accordion-tabs::after {
  clear: both;
  content: "";
  display: block;
}

.accordion-tabs .tab-header-and-content {
  list-style: none;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-header-and-content {
    display: inline;
  }
}

@media (min-width: 40em) {
  .accordion-tabs .tab-header-and-content:first-child .tab-link {
    border-top: 0;
  }
}

.accordion-tabs .tab-link {
  background-color: #fff;
  color: #333;
  display: block;
  font-weight: bold;
  padding: 0.75em 0;
  text-decoration: none;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-link {
    border-left: 0;
    border-right: 0;
    border-top: 0;
    display: inline-block;
    width: 23%;
    text-align: center;
  }
}

.accordion-tabs .tab-link:hover {
  color: #477dca;
}

.accordion-tabs .tab-link:focus {
  outline: none;
}

.accordion-tabs .tab-link.is-active {
  background-color: #fff;
  color: #0a79bc;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-link.is-active {
    background-color: #fff;
    border-bottom: 2px solid #0a79bc;
    margin-bottom: -1px;
  }
}

.accordion-tabs .tab-content {
  background: #fff;
  display: none;
  padding: 1.5em 1.5em;
}

@media (min-width: 40em) {
  .accordion-tabs .tab-content {
    float: left;
  }
}

.accordion-tabs .nextContainer {
  list-style: none;
  display: block;
  width: 100%;
  clear: both;
}

.accordion-tabs .nextContaner__link {
  padding: 20px;
  display: block;
  float: right;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="accordion-tabs">
  <li class="tab-header-and-content">
    <a href="javascript:void(0)" class="is-active tab-link">Tab Item</a>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras tincidunt pellentesque lorem, id suscipit dolor rutrum id. Morbi facilisis porta volutpat. Fusce adipiscing, mauris quis congue tincidunt, sapien purus suscipit odio, quis dictum odio
        tortor in sem. Ut sit amet libero nec orci mattis fringilla. Praesent eu ipsum in sapien tincidunt molestie sed ut magna. Nam accumsan dui at orci rhoncus pharetra tincidunt elit ullamcorper. Sed ac mauris ipsum. Nullam imperdiet sapien id purus
        pretium id aliquam mi ullamcorper.</p>
    </div>
  </li>
  <li class="tab-header-and-content">
    <a href="javascript:void(0)" class="tab-link">Another Tab</a>
    <div class="tab-content">
      <p>Ut laoreet augue et neque pretium non sagittis nibh pulvinar. Etiam ornare tincidunt orci quis ultrices. Pellentesque ac sapien ac purus gravida ullamcorper. Duis rhoncus sodales lacus, vitae adipiscing tellus pharetra sed. Praesent bibendum lacus
        quis metus condimentum ac accumsan orci vulputate. Aenean fringilla massa vitae metus facilisis congue. Morbi placerat eros ac sapien semper pulvinar. Vestibulum facilisis, ligula a molestie venenatis, metus justo ullamcorper ipsum, congue aliquet
        dolor tortor eu neque. Sed imperdiet, nibh ut vestibulum tempor, nibh dui volutpat lacus, vel gravida magna justo sit amet quam. Quisque tincidunt ligula at nisl imperdiet sagittis. Morbi rutrum tempor arcu, non ultrices sem semper a. Aliquam
        quis sem mi.</p>
    </div>
  </li>
  <li class="tab-header-and-content">
    <a href="javascript:void(0)" class="tab-link">Third</a>
    <div class="tab-content">
      <p>Donec mattis mauris gravida metus laoreet non rutrum sem viverra. Aenean nibh libero, viverra vel vestibulum in, porttitor ut sapien. Phasellus tempor lorem id justo ornare tincidunt. Nulla faucibus, purus eu placerat fermentum, velit mi iaculis
        nunc, bibendum tincidunt ipsum justo eu mauris. Nulla facilisi. Vestibulum vel lectus ac purus tempus suscipit nec sit amet eros. Nullam fringilla, enim eu lobortis dapibus, quam magna tincidunt nibh, sit amet imperdiet dolor justo congue turpis.</p>
    </div>
  </li>
  <li class="tab-header-and-content">
    <a href="javascript:void(0)" class="tab-link">Last Item</a>
    <div class="tab-content">
      <p>Sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Phasellus dui urna.</p>
    </div>
  </li>

  <li class="nextContainer">
    <a href="javascript:void(0)" class="nextContaner__link">Next</a>
  </li>
</ul>


问:
JVM heap sizing in VMware guests
This question is probably better phrased: how does running a Java server on a hypervisor such as VMware ESX affect the Java heap?

Access to JVM heap is random from the OS/hypervisor perspective

It is difficult to for guest OS or hypervisor to optimize memory that is randomly accessed

Given this, can the hypervisor detect unused pages in JVM heap?

The conventional wisdom for Java server applications is that performance is best if you allocate all the heap at JVM startup, rather than allowing the heap to be dynamically resized as the need arises. In other words, if you set the heap size to 1GB, your Java process will grab 1GB of contiguous virtual address space (+ whatever is needed for the binaries), memory which is no longer available to other applications.

Is VMware smart enough to detect that some of this heap is in fact unused? How does this affect GC performance? Would it be better to let the heap be dynamically resized in VMware? What GC strategies work best with VMware guests?

Also, would anyone point me towards guidelines for tuning JVM heaps in virtualized environments?

答:
Related to my question:

Here is a PDF that provides a broad overview of considerations for running Java on VMware guests: link text

OwnerDisplayName: Rob

Title: JVM heap sizing in VMware guests

LastEditorDisplayName: Rob


问:
Display images with Greek in filenames
I'm building an e-shop in greek and i've come across an important issue regarding the image filenames that users upload to the linux server. If the filename contains greek chars then the file is uploaded normally but the images won't display in the browser. It's important to us that greek filenames are supported as we are counting on searches in greek for both web and image results on Google.</p>

答:
Why aren't they displaying?  Do you have an example?

I guess your options depend on how the images are being stored and served back to the users.  One thing you could do, in order to preserve the Greek text on the page for search results, may be to serve up the files with a non-Greek name and write the Greek part to the image's alt tag.

This, however, is assuming that you're storing the image files in conjunction with a database of some kind which would contain the necessary meta-data.  Basically, upon upload, the image's meta-data (alt text, maybe mime type, anything else important about it) would be written to a record in a database table and then the image file itself can be saved on the file system.  Its actual file name could just be the primary key from the table, which can just be an auto-increment field.

Title: Display images with Greek in filenames


问:
How to write nested loops that resample and increase sample size
I am new to loops in R and I need help with writing multiple nested loops. I have a data frame where a row represents counts of species from one site within a region. There are 50 regions, and the number of sites among regions is unequal. For each region I need to calculate a diversity index based on incrementingly increasing the number sites, and replicating this 1000x for each incremental step. For instance:

```<code>R1 <- subset(df, region=="1") #this needs to be completed for all 50 regions
R1$region<-NULL

max<-nrow(R1)-1

iter <- 1000 #the number of iterations
n <- 1 # the number of rows to be sampled. This needs to increase until
“max”
outp <- rep(NA, iter)

for (i in 1:iter){
  d <- sample(1:nrow(R1), size = n, replace=FALSE)
  bootdata <- R1[d,]
  x <- colSums(bootdata) #this is not applicable until n>1
  outp[i] <- 1/diversity(x, index = "simpson")
}
</code>```

Here is a sample dataset

```<code>structure(list(region = c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L), Sp1 = c(31L,
85L, 55L, 71L, 81L, 22L, 78L, 64L), Sp2 = c(10L, 84L, 32L, 86L,
47L, 93L, 55L, 35L), Sp3 = c(86L, 56L, 4L, 8L, 55L, 47L, 51L,
95L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-8L), .Names = c("region", "Sp1", "Sp2", "Sp3"), spec = structure(list(
cols = structure(list(region = structure(list(), class =
c("collector_integer",
"collector")), Sp1 = structure(list(), class = c("collector_integer",
"collector")), Sp2 = structure(list(), class = c("collector_integer",
"collector")), Sp3 = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("region", "Sp1", "Sp2", "Sp3")),
default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))
</code>```

In short, for each region I need to calculate “simpson’s” index for each site, randomly resampled 1000 times. Then, I need to calculate the index again for 2 sites after each column has been summed, 1000 times. Then 3 sites etc until max.

I also struggle in writing output. I am looking to have one dataframe for each region with columns that represent 1000 iterations of n until max.

Many thanks in advance

答:
You can write a function that works on a generic region at a time. Then you split your data by region into a list and apply your custom function to each list element using sapply.

```<code>bootstrapByRegion <- function(R) {
  rgn <- unique(R$region)
  message(sprintf("Processing %s", rgn))
  R$region <- NULL

  nmax <- nrow(R)-1

  if (nmax == 0) stop(sprintf("Trying to work on one row. No dice. Manually exclude region %s or handle otherwise.", rgn))

  iter <- 1000 #the number of iterations
  # pre-allocate the result
  output <- matrix(NA, nrow = iter, ncol = nmax)

  for (i in 1:nmax) {
    i <- 1
    output[, i] <- replicate(iter, expr = {
      d <- sample(1:nrow(R), size = i, replace=FALSE)
      bootdata <- R[d, , drop = FALSE]
      x <- colSums(bootdata) #this is not applicable until n>1
      outp <- 1/diversity(x, index = "simpson")
      outp
    })
  }
  output
}

xy <- split(df, f = df$region)
result <- sapply(xy, FUN = bootstrapByRegion) # list element is taken as R
</code>```

Since region 3 has only one row, it will not work (because of the nrow(R)-1). You can exclude these regions in a number of ways. Here's one.

```<code>result <- sapply(xy[sapply(xy, nrow) > 1], FUN = bootstrapByRegion)
</code>```

Body:
I am new to loops in R and I need help with writing multiple nested loops. I have a data frame where a row represents counts of species from one site within a region. There are 50 regions, and the number of sites among regions is unequal. For each region I need to calculate a diversity index based on incrementingly increasing the number sites, and replicating this 1000x for each incremental step. For instance:

R1 <- subset(df, region=="1") #this needs to be completed for all 50 regions
R1$region<-NULL

max<-nrow(R1)-1

iter <- 1000 #the number of iterations
n <- 1 # the number of rows to be sampled. This needs to increase until
“max”
outp <- rep(NA, iter)

for (i in 1:iter){
  d <- sample(1:nrow(R1), size = n, replace=FALSE)
  bootdata <- R1[d,]
  x <- colSums(bootdata) #this is not applicable until n>1
  outp[i] <- 1/diversity(x, index = "simpson")
}

Here is a sample dataset

structure(list(region = c(1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L), Sp1 = c(31L,
85L, 55L, 71L, 81L, 22L, 78L, 64L), Sp2 = c(10L, 84L, 32L, 86L,
47L, 93L, 55L, 35L), Sp3 = c(86L, 56L, 4L, 8L, 55L, 47L, 51L,
95L)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-8L), .Names = c("region", "Sp1", "Sp2", "Sp3"), spec = structure(list(
cols = structure(list(region = structure(list(), class =
c("collector_integer",
"collector")), Sp1 = structure(list(), class = c("collector_integer",
"collector")), Sp2 = structure(list(), class = c("collector_integer",
"collector")), Sp3 = structure(list(), class = c("collector_integer",
"collector"))), .Names = c("region", "Sp1", "Sp2", "Sp3")),
default = structure(list(), class = c("collector_guess",
"collector"))), .Names = c("cols", "default"), class = "col_spec"))

In short, for each region I need to calculate “simpson’s” index for each site, randomly resampled 1000 times. Then, I need to calculate the index again for 2 sites after each column has been summed, 1000 times. Then 3 sites etc until max.

I also struggle in writing output. I am looking to have one dataframe for each region with columns that represent 1000 iterations of n until max.

Many thanks in advance

Body:
You can write a function that works on a generic region at a time. Then you split your data by region into a list and apply your custom function to each list element using sapply.

bootstrapByRegion <- function(R) {
  rgn <- unique(R$region)
  message(sprintf("Processing %s", rgn))
  R$region <- NULL

  nmax <- nrow(R)-1

  if (nmax == 0) stop(sprintf("Trying to work on one row. No dice. Manually exclude region %s or handle otherwise.", rgn))

  iter <- 1000 #the number of iterations
  # pre-allocate the result
  output <- matrix(NA, nrow = iter, ncol = nmax)

  for (i in 1:nmax) {
    i <- 1
    output[, i] <- replicate(iter, expr = {
      d <- sample(1:nrow(R), size = i, replace=FALSE)
      bootdata <- R[d, , drop = FALSE]
      x <- colSums(bootdata) #this is not applicable until n>1
      outp <- 1/diversity(x, index = "simpson")
      outp
    })
  }
  output
}

xy <- split(df, f = df$region)
result <- sapply(xy, FUN = bootstrapByRegion) # list element is taken as R

Since region 3 has only one row, it will not work (because of the nrow(R)-1). You can exclude these regions in a number of ways. Here's one.

result <- sapply(xy[sapply(xy, nrow) > 1], FUN = bootstrapByRegion)


问:
runner technique for weaving elements of linked list
I've been reading the cracking the coding interview book. I am a bit stuck on implementing the runner technique for weaving elements of a linked list. The book goes as follows:

"Suppose you had a linked list a1->a2....->an->b1->b2....bn, and you want to rearrange it into a1->b1->a2->b2->.....an->bn. You don't know the length of the linked list but all you know is that it is an even number.

You could have one pointer p1 (fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the endpoint. Then, move p1 back to the front and begin "weaving" the elements. On each iteration, p2 selects an element and inserts it after p1."

Now I understand the technique up to the point before weaving starts. So, right before weaving, we basically have (for n=4 elements)

```<code>p1      p2
a1->a2->b1->b2
</code>```

Now, if I understand correctly, I have to move the element pointed to by p2 (i.e. b1) and insert it after p1, in other words

```<code>p1.next = p2
</code>```

which would result in the following list (?)

```<code>a1->b1->b2
</code>```

How does the algorithm proceed from here?

I found this question but it seems to suggest that the above step would result in

```<code>a1->b1->a2->b2
</code>```

which I do not see how. I am probably missing something fundamental here.

答:
The algorithms presented by Adam Stelmaszczyk, Igor Tandetnik and four_lines are correct; one only has to take care with the terminating condition otherwise the final nullptr that terminates the list can become lost. four_lines advocates handling this before doing the weaving. Or it can be done during the weaving by checking:</p>

```<code>#include "stdafx.h"
#include <iostream>

namespace
{
    struct elem
    {
        int val;
        elem* next;
        elem() : val(-1), next(nullptr) {}
    };
}

int main()
{
    // setup single-linked list of elements (an array here makes it easy...)
    const int SIZE = 12; // even number
    elem elems[SIZE];
    for (int x = 0; x < SIZE - 1; ++x) { elems[x].next = &elems[x + 1]; }
    for (int x = 0; x < SIZE; ++x) { elems[x].val = x; }

    // divide the list using ptrs pf, ps to point at first part, second part
    elem* pf = elems;
    elem* ps = elems;
    do
    {
        pf = pf->next;
        pf = pf->next;
        ps = ps->next;
    } while (pf != nullptr);
    pf = elems; // move pf back to start

    // weave first and second parts of list using pf and ps
    do
    {
        // update pf element next-ptr to point at ps, then move pf to its original next element
        elem* oldpfnext = pf->next;
        pf->next = ps;
        pf = oldpfnext;
        // if ps element is not at end, update ps element next-ptr to point the new location of pf
        elem* oldpsnext = ps->next;
        if (nullptr != ps->next)
        {
            ps->next = pf;
        }
        // now move ps to its original next element (even if null)...
        ps = oldpsnext;
    } while (nullptr != ps); // ... and stop if we are now at end

    return 0;
}
</code>```

Body:
I've been reading the cracking the coding interview book. I am a bit stuck on implementing the runner technique for weaving elements of a linked list. The book goes as follows:

"Suppose you had a linked list a1->a2....->an->b1->b2....bn, and you want to rearrange it into a1->b1->a2->b2->.....an->bn. You don't know the length of the linked list but all you know is that it is an even number.

You could have one pointer p1 (fast pointer) move every two elements for every one move that p2 makes. When p1 hits the end of the linked list, p2 will be at the endpoint. Then, move p1 back to the front and begin "weaving" the elements. On each iteration, p2 selects an element and inserts it after p1."

Now I understand the technique up to the point before weaving starts. So, right before weaving, we basically have (for n=4 elements)

p1      p2
a1->a2->b1->b2

Now, if I understand correctly, I have to move the element pointed to by p2 (i.e. b1) and insert it after p1, in other words

p1.next = p2

which would result in the following list (?)

a1->b1->b2

How does the algorithm proceed from here?

I found this question but it seems to suggest that the above step would result in

a1->b1->a2->b2

which I do not see how. I am probably missing something fundamental here.

Body:
The algorithms presented by Adam Stelmaszczyk, Igor Tandetnik and four_lines are correct; one only has to take care with the terminating condition otherwise the final nullptr that terminates the list can become lost. four_lines advocates handling this before doing the weaving. Or it can be done during the weaving by checking:

#include "stdafx.h"
#include <iostream>

namespace
{
    struct elem
    {
        int val;
        elem* next;
        elem() : val(-1), next(nullptr) {}
    };
}

int main()
{
    // setup single-linked list of elements (an array here makes it easy...)
    const int SIZE = 12; // even number
    elem elems[SIZE];
    for (int x = 0; x < SIZE - 1; ++x) { elems[x].next = &elems[x + 1]; }
    for (int x = 0; x < SIZE; ++x) { elems[x].val = x; }

    // divide the list using ptrs pf, ps to point at first part, second part
    elem* pf = elems;
    elem* ps = elems;
    do
    {
        pf = pf->next;
        pf = pf->next;
        ps = ps->next;
    } while (pf != nullptr);
    pf = elems; // move pf back to start

    // weave first and second parts of list using pf and ps
    do
    {
        // update pf element next-ptr to point at ps, then move pf to its original next element
        elem* oldpfnext = pf->next;
        pf->next = ps;
        pf = oldpfnext;
        // if ps element is not at end, update ps element next-ptr to point the new location of pf
        elem* oldpsnext = ps->next;
        if (nullptr != ps->next)
        {
            ps->next = pf;
        }
        // now move ps to its original next element (even if null)...
        ps = oldpsnext;
    } while (nullptr != ps); // ... and stop if we are now at end

    return 0;
}