问:
When I compile my program,it displays "segmentaion fault (or) segmentation fault(core dumped)
When I compile my program, it displays

segmentaion fault (or) segmentation fault(core dumped)

My code seems to be working sometimes it gives the number of knight moves on the whole chessBoard, when moved on a square randomly chosen from all other paths, possibly a knight can take,but this doesn't seem to work always(just for simplicity,I have taken 5x5 chessboard ), why is this happening,what can i do to fix it?

#include <iostream>
#include <array>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
     array<array<int , 5>,5> chessBoard = {};
     array<int , 8> horizontal = {2,1,-1,-2,-2,-1,1,2};
     array<int , 8> vertical = {-1,-2,-2,-1,1,2,2,1};
     array<int, 8> temp ={};
     int count = 0 , t = 0 ,index;
     int cR = 4 , cC = 4 ,square =  1;
     srand(static_cast<unsigned>(time(0)));

     do
     {
       t = 0;
       for(size_t i = 0;i < 8;i++ )
       {
          cR += vertical[i];
          cC += horizontal[i];

          if(cR > 0 && cR < 8 && cC > 0 && cC < 8 && chessBoard[cR][cC] != -1)
          {
             temp[t] = i;
             t++;

          }
          cR -= vertical[i];
          cC -= horizontal[i];

       }
       if(t > 0)
       {
         index = rand() % t;
         chessBoard[cR][cC] = -1;
         cR += vertical[temp[index]];
         cC += horizontal[temp[index]];
         count++;
       }

       for(size_t j=0;j< t;j++)
         temp[j] = 0;

       square++;
   }while(square <= 25);

    cout<<"count is "<<count;
    return 0;

}
```

The error is Segmentation fault or sometimes it displays Segmentation fault (core dumped),what is wrong?

答:
Replace

```<code>array<array<int , 5>,5> chessBoard = {};
</code>```

by

```<code>array<array<int,8>,8> chessBoard;
</code>```

A segmentation fault is when your program tries to access memory that it's not allowed to.

This does not happen when you compile, but when you run the program.

Body:
When I compile my program, it displays

segmentaion fault (or) segmentation fault(core dumped)

My code seems to be working sometimes it gives the number of knight moves on the whole chessBoard, when moved on a square randomly chosen from all other paths, possibly a knight can take,but this doesn't seem to work always(just for simplicity,I have taken 5x5 chessboard ), why is this happening,what can i do to fix it?

#include <iostream>
#include <array>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
     array<array<int , 5>,5> chessBoard = {};
     array<int , 8> horizontal = {2,1,-1,-2,-2,-1,1,2};
     array<int , 8> vertical = {-1,-2,-2,-1,1,2,2,1};
     array<int, 8> temp ={};
     int count = 0 , t = 0 ,index;
     int cR = 4 , cC = 4 ,square =  1;
     srand(static_cast<unsigned>(time(0)));

     do
     {
       t = 0;
       for(size_t i = 0;i < 8;i++ )
       {
          cR += vertical[i];
          cC += horizontal[i];

          if(cR > 0 && cR < 8 && cC > 0 && cC < 8 && chessBoard[cR][cC] != -1)
          {
             temp[t] = i;
             t++;

          }
          cR -= vertical[i];
          cC -= horizontal[i];

       }
       if(t > 0)
       {
         index = rand() % t;
         chessBoard[cR][cC] = -1;
         cR += vertical[temp[index]];
         cC += horizontal[temp[index]];
         count++;
       }

       for(size_t j=0;j< t;j++)
         temp[j] = 0;

       square++;
   }while(square <= 25);

    cout<<"count is "<<count;
    return 0;

}

The error is Segmentation fault or sometimes it displays Segmentation fault (core dumped),what is wrong?

Body:
Replace

array<array<int , 5>,5> chessBoard = {};

by

array<array<int,8>,8> chessBoard;

A segmentation fault is when your program tries to access memory that it's not allowed to.

This does not happen when you compile, but when you run the program.


来源: stackexchange

问:
ERROR: Could not get unknown property 'appcompat' for project ':app' of type org.gradle.api.Project
Error rising while Building Gradle of a code I found online.

```<code>    implement "com.android.support:appcompat-v7:$project.appcompat"
    implement "com.android.support:cardview-v7:$project.appcompat"
    implement "com.android.support:recyclerview-v7:$project.appcompat"
    implement "android.arch.lifecycle:runtime:$project.arch"
    implement "android.arch.lifecycle:extensions:$project.arch"
    implement "com.squareup.retrofit2:retrofit:$project.retrofit"
    implement "com.squareup.retrofit2:converter-gson:$project.retrofit"
    annotationProcessor "android.arch.lifecycle:compiler:$project.arch"
    implement "com.android.support.constraint:constraint-layout:$project.constraintLayout"
    implement "com.android.support:support-v4:$project.appcompat"
</code>```

P.S. Problem is solves as i understood how to use a variable in gradle file

答:
ERROR: Could not get unknown property 'appcompat' for project ':app' of type org.gradle.api.Project

It happens because you are trying to use a property $project.appcompat not defined in your script.

Update your script with something like:

```<code>ext {
    supportLibraryVersion = '28.0.0' //or your version
}
</code>```

and then (pay attention, implementation and not implement)

```<code>dependencies {
    // support libraries
    implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
    //....
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Error rising while Building Gradle of a code I found online.

    implement "com.android.support:appcompat-v7:$project.appcompat"
    implement "com.android.support:cardview-v7:$project.appcompat"
    implement "com.android.support:recyclerview-v7:$project.appcompat"
    implement "android.arch.lifecycle:runtime:$project.arch"
    implement "android.arch.lifecycle:extensions:$project.arch"
    implement "com.squareup.retrofit2:retrofit:$project.retrofit"
    implement "com.squareup.retrofit2:converter-gson:$project.retrofit"
    annotationProcessor "android.arch.lifecycle:compiler:$project.arch"
    implement "com.android.support.constraint:constraint-layout:$project.constraintLayout"
    implement "com.android.support:support-v4:$project.appcompat"

P.S. Problem is solves as i understood how to use a variable in gradle file

Body:
ERROR: Could not get unknown property 'appcompat' for project ':app' of type org.gradle.api.Project

It happens because you are trying to use a property $project.appcompat not defined in your script.

Update your script with something like:

ext {
    supportLibraryVersion = '28.0.0' //or your version
}

and then (pay attention, implementation and not implement)

dependencies {
    // support libraries
    implementation "com.android.support:appcompat-v7:$supportLibraryVersion"
    //....
}


问:
How do I bypass asking end-user for username while adding a blog post using a form and automatically display logged in user as post author?
I am working on a simple blog which has a model Post. I am trying to create a form for adding blog posts (or adding comments to posts for that matter) so that end users don't have to fill out a form box asking the end user for a username. I would like to be able to just ask for a title and body text for a blog post, and when hit post, it will be posted as the authenticated user.

I tried not including 'user' field in fields in forms, but it seems to be mandatory. Maybe I need to just make it hidden somehow using widgets? In templates, I could maybe write the following:

```<code>{% if user.is_authenticated %}
   <p>Posting as {{request.user}}</p>
{% else %}
   <p><a href={% url 'register' %}Please register to add a blog post</a></p>
{% endif %}
</code>```

Though I am not sure, I think it would make more sense to have logic in my views.py file.

Here's my 'blog.models' file:

```<code>class Post(models.Model):
    user            = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
    title           = models.CharField(max_length=200)
    slug            = models.SlugField(unique=True)
    text            = models.TextField()
    published_date  = models.DateTimeField(auto_now=True)
    # pip install Pillow
    image           = models.ImageField(null=True, blank=True,
                                        upload_to='photos/%Y/%m/%d/',)

    def summary(self):
        """Return a summary for very long posts to
        get a glimpse from admin panel"""
        return self.text[:100]

    def _get_unique_slug(self):
        """Assigns a number to the end of a given slug field to prevent
        duplicated slug error. if title of a post is 'ayancik', and another
        user creates another post with the same title, second posts' slug
        is assigned a value: 'ayancik-2'"""
        slug = slugify(self.title)
        unique_slug = slug
        num = 1
        while Post.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        """Automatically assign slug to objects
        by overriding save method"""
        self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

    def pub_date_pretty(self):
        return self.published_date.strftime('%b %e, %Y')

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        # what does kwargs={'slug':self.slug} really achieve here?
        # where would we use 'key-value' pair?
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-published_date',]

class Comment(models.Model):
    post                = models.ForeignKey('blog.Post', on_delete=models.CASCADE,
                             related_name='comments')
    user                = models.CharField(max_length=200)
    text                = models.TextField()
    created_date        = models.DateTimeField(default=timezone.now)
    approved_comment    = models.BooleanField(default=False)

    def approve_comment(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text
</code>```

'blog.forms' file:

```<code>class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'text', 'image']

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('user', 'text',)
</code>```

and 'blog.views' file:

```<code>@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(request)
            post.save()
        else:
            print(post_form.errors)
    else:
            # when not POST request, display the empty form
            # meaning -> if request.method=='GET':
            post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context)

def add_comment_to_post(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail', slug=slug)

    else:
        form = CommentForm()
    template_name = 'blog/add_comment_to_post.html'
    return render(request, template_name , {'form': form })
</code>```

答:
You omit the user in the PostForm:

```<code>class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        # no user
        fields = ['title', 'text', 'image']</code>```

or we can display all fields except 'user' like:

```<code>class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        <b>exclude = ('user', )</b></code>```

and then you add the user to the instance in your view:

```<code>from django.shortcuts import <b>redirect</b>

@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST, <b>request.FILES</b>)

        if post_form.is_valid():
            post = post_form.save(<b>commit=False</b>)
            <b>post.user = request.user</b>
            post.save()
            return <b>redirect('some_view')</b>
    else:
        post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context)</code>```

The commit=False thus prevents the from from saving the Post object to the database.

Since you want to upload an image, you should pass request.FILES [Django-doc] to the PostForm as well, otherwise you will not process uploaded files. You furthermore need to specify that you use enctype="multipart/form-data" in your form:

```<code><form <b>enctype="multipart/form-data"</b> method="POST" action="{% url 'create_post' %}">
    ...
</form></code>```

It is better to use a redirect [Django-doc] in case of a successful POST request, since this is the Post/Redirect/Get pattern [wiki]. By rendering a new form, if the user refreshes the page, he/she would create a second post, which is probably not what you want.

Body:
I am working on a simple blog which has a model Post. I am trying to create a form for adding blog posts (or adding comments to posts for that matter) so that end users don't have to fill out a form box asking the end user for a username. I would like to be able to just ask for a title and body text for a blog post, and when hit post, it will be posted as the authenticated user.

I tried not including 'user' field in fields in forms, but it seems to be mandatory. Maybe I need to just make it hidden somehow using widgets? In templates, I could maybe write the following:

{% if user.is_authenticated %}

Posting as {{request.user}}

{% else %}

<a href={% url 'register' %}Please register to add a blog post

{% endif %}

Though I am not sure, I think it would make more sense to have logic in my views.py file.

Here's my 'blog.models' file:

class Post(models.Model):
    user            = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts')
    title           = models.CharField(max_length=200)
    slug            = models.SlugField(unique=True)
    text            = models.TextField()
    published_date  = models.DateTimeField(auto_now=True)
    # pip install Pillow
    image           = models.ImageField(null=True, blank=True,
                                        upload_to='photos/%Y/%m/%d/',)

    def summary(self):
        """Return a summary for very long posts to
        get a glimpse from admin panel"""
        return self.text[:100]

    def _get_unique_slug(self):
        """Assigns a number to the end of a given slug field to prevent
        duplicated slug error. if title of a post is 'ayancik', and another
        user creates another post with the same title, second posts' slug
        is assigned a value: 'ayancik-2'"""
        slug = slugify(self.title)
        unique_slug = slug
        num = 1
        while Post.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        """Automatically assign slug to objects
        by overriding save method"""
        self.slug = self._get_unique_slug()
        super().save(*args, **kwargs)

    def pub_date_pretty(self):
        return self.published_date.strftime('%b %e, %Y')

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        # what does kwargs={'slug':self.slug} really achieve here?
        # where would we use 'key-value' pair?
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-published_date',]

class Comment(models.Model):
    post                = models.ForeignKey('blog.Post', on_delete=models.CASCADE,
                             related_name='comments')
    user                = models.CharField(max_length=200)
    text                = models.TextField()
    created_date        = models.DateTimeField(default=timezone.now)
    approved_comment    = models.BooleanField(default=False)

    def approve_comment(self):
        self.approved_comment = True
        self.save()

    def __str__(self):
        return self.text

'blog.forms' file:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['user', 'title', 'text', 'image']

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('user', 'text',)

and 'blog.views' file:

@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(request)
            post.save()
        else:
            print(post_form.errors)
    else:
            # when not POST request, display the empty form
            # meaning -> if request.method=='GET':
            post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context)

def add_comment_to_post(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail', slug=slug)

    else:
        form = CommentForm()
    template_name = 'blog/add_comment_to_post.html'
    return render(request, template_name , {'form': form })

Body:
You omit the user in the PostForm:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        # no user
        fields = ['title', 'text', 'image']

or we can display all fields except 'user' like:

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        exclude = ('user', )

and then you add the user to the instance in your view:

from django.shortcuts import redirect

@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST, request.FILES)

        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.user = request.user
            post.save()
            return redirect('some_view')
    else:
        post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context)

The commit=False thus prevents the from from saving the Post object to the database.

Since you want to upload an image, you should pass request.FILES [Django-doc] to the PostForm as well, otherwise you will not process uploaded files. You furthermore need to specify that you use enctype="multipart/form-data" in your form:

<form enctype="multipart/form-data" method="POST" action="{% url 'create_post' %}">
    ...
</form>

It is better to use a redirect [Django-doc] in case of a successful POST request, since this is the Post/Redirect/Get pattern [wiki]. By rendering a new form, if the user refreshes the page, he/she would create a second post, which is probably not what you want.


问:
Print the next month
I want excel to print the date of next month on the next row in line. (There is a counter on the third row)

For example:

```<code>B28 = 01.07.2019
C24 = 01.06.2019
D16 = 01.02.2019
E19 = 01.07.2019
</code>```

Here is the screenshot: https://ibb.co/d0mW8GB

答:
there are many missing parts from your question but i try to create a code to satisfy your needs. You could try:

```<code>Option Explicit

Sub makro3()

    Dim LastColumn As Long, LastRow As Long, Column As Long, Row As Long, Paid As Long

    'In your quetion there is no starting date so i use the current one

    With ThisWorkbook.Sheets("Sheet1")

        LastColumn = .Cells(3, .Columns.Count).End(xlToLeft).Column

        For Column = 2 To LastColumn

            Paid = .Cells(3, Column).Value

            For Row = 1 To Paid

                LastRow = .Cells(.Rows.Count, Column).End(xlUp).Row

                .Cells(LastRow + 1, Column).Value = DateAdd("m", Row, Date)

            Next Row

        Next Column

    End With

End Sub
</code>```

Results:

Title: Print the next month

Body:
I want excel to print the date of next month on the next row in line. (There is a counter on the third row)

For example:

B28 = 01.07.2019
C24 = 01.06.2019
D16 = 01.02.2019
E19 = 01.07.2019

Here is the screenshot: https://ibb.co/d0mW8GB

Body:
there are many missing parts from your question but i try to create a code to satisfy your needs. You could try:

Option Explicit

Sub makro3()

    Dim LastColumn As Long, LastRow As Long, Column As Long, Row As Long, Paid As Long

    'In your quetion there is no starting date so i use the current one

    With ThisWorkbook.Sheets("Sheet1")

        LastColumn = .Cells(3, .Columns.Count).End(xlToLeft).Column

        For Column = 2 To LastColumn

            Paid = .Cells(3, Column).Value

            For Row = 1 To Paid

                LastRow = .Cells(.Rows.Count, Column).End(xlUp).Row

                .Cells(LastRow + 1, Column).Value = DateAdd("m", Row, Date)

            Next Row

        Next Column

    End With

End Sub

Results:


问:
MongoDB slice query into golang
How can i write this below slice query into golang?

```<code>db.con.find({"repoid":1356485},{"contr":{$slice:[0,10]}}).pretty()
</code>```

Tried with this but not working

```<code>DB.C("con").Find(bson.M{"id": ID, "contr": bson.M{"$slice": []interface{}{"$contr", offset, limit}}})
</code>```

does not find anything. Any ideas?

Thank you in advance

答:
With Collection.Find() you can only specify the filter. But what you have is a projection:

```<code>{"contr":{$slice:[0,10]}
</code>```

Projections can be specified using Query.Select(), so this is how you can apply a $slice in projection:

```<code>var results []bson.M // Use your own type here, but this works too

err := DB.C("con").Find(bson.M{"id": ID}).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)

// handle error
</code>```

Also note sure if the property you filter by is "id" or is just a typo and it should be "_id". If the latter, you may also use Collection.FindId() to query by document ID:

```<code>err := DB.C("con").FindId(ID).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)
</code>```

Title: MongoDB slice query into golang

Body:
How can i write this below slice query into golang?

db.con.find({"repoid":1356485},{"contr":{$slice:[0,10]}}).pretty()

Tried with this but not working

DB.C("con").Find(bson.M{"id": ID, "contr": bson.M{"$slice": []interface{}{"$contr", offset, limit}}})

does not find anything. Any ideas?

Thank you in advance

Body:
With Collection.Find() you can only specify the filter. But what you have is a projection:

{"contr":{$slice:[0,10]}

Projections can be specified using Query.Select(), so this is how you can apply a $slice in projection:

var results []bson.M // Use your own type here, but this works too

err := DB.C("con").Find(bson.M{"id": ID}).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)

// handle error

Also note sure if the property you filter by is "id" or is just a typo and it should be "_id". If the latter, you may also use Collection.FindId() to query by document ID:

err := DB.C("con").FindId(ID).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)


问:
Exporting shared secret as BYTE array from BCRYPT_SECRET_HANDLE
I'm implementing ECDHE using crypto next generation APIs (CNG). I generate public and private keys successfully. For pre-shared key, I use BCryptSecretAgreement API, which returns me the pre-shared key secret handle (BCRYPT_SECRET_HANDLE).

How can I export the pre-shared key as BYTE array from the BCRYPT_SECRET_HANDLE?

答:
Starting with Windows 10, you can call BCryptDeriveKey() with BCRYPT_KDF_RAW_SECRET.

The resulting key data is the raw secret.

Note 1: bcrypt.h indicates that this format works for "WINBLUE", which would be Windows 8.1, if I understand correctly, but I received STATUS_NOT_SUPPORTED for the use of this KDF type on both Windows 8.1 and Windows Server 2012 R2.  This works, however, on Windows 10.)

Note2: I found the data returned using this KDF type to be little-endian (where everything else in BCrypt is big-endian).  So, to use the value in an otherwise big-endian world, you need to byte-flip the data.

ContentLicense: CC BY-SA 3.0


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答: Try printing out a line everytime you lock a mutex and printing out another line when you unlock it.  Remember to include the function name and the thread id when you print it.  Should give you an idea of when it's locking. Seems like a race condition calling a sleep(0) still causes the CPU to use cycles processing the call to the function.  Therefore causing an inherent sleep.</p>

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: Suroot


问:
Getting a list of documents with a maximum field value from CouchDB view
Let's say I have blog entries like these in my CouchDB database:

```
{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Mary", "postdate":"20110411", "subject":"and this", "message":"blah-blah"}
{"name":"Joe", "postdate":"20110410", "subject":"And other thing", "message":"yada-yada"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}
```

It's pretty easy to get a list of all posts. But how do I get a list of latest posts from all the users?

Like that:

```
{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}
```

答:
You're going to emit the postdate as the key because keys are sorted. For example, this is what your map function will look like...

```<code>function(doc) {
  if(doc.postdate) {
    emit(doc.postdate, doc);
  }
}
</code>```

That will give you all the docs sorted ascending by postdate. If you want descending then query with ?descending=true

Cheers.

Body:
Let's say I have blog entries like these in my CouchDB database:

{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Mary", "postdate":"20110411", "subject":"and this", "message":"blah-blah"}
{"name":"Joe", "postdate":"20110410", "subject":"And other thing", "message":"yada-yada"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}

It's pretty easy to get a list of all posts. But how do I get a list of latest posts from all the users?

Like that:

{"name":"Mary", "postdate":"20110412", "subject":"this", "message":"blah"}
{"name":"Joe", "postdate":"20110411", "subject":"that", "message":"yadda"}
{"name":"Jane", "postdate":"20110409", "subject":"Serious stuff", "message":"Not really"}

Body:
You're going to emit the postdate as the key because keys are sorted. For example, this is what your map function will look like...

function(doc) {
  if(doc.postdate) {
    emit(doc.postdate, doc);
  }
}

That will give you all the docs sorted ascending by postdate. If you want descending then query with ?descending=true

Cheers.


问:
Cannot call Connection.commit in distributed transaction
I am using Weblogic 12c and I am getting the below error while committing distributed transactions in my application.

"java.sql.SQLException: Cannot call Connection.commit in distributed transaction.  Transaction Manager will commit the resource manager when the distributed transaction is committed"

The part of code throwing exception is:

```<code>Session sessionNew = HibernateService.getService().getSession();
sessionNew.connection().commit();
</code>```

This question has been asked several times, but the solution I am seeking is different.
The most common solution is to disable XA transactions to resolve the issue.
But my application contains more than resources like database, JMS etc.
Can anyone please suggest a solution other than the one mentioned above.

Also, I needed to understand if there is any relation between JTA transaction timeout value and the above-mentioned error.

Thanks a lot.

答:
Most likely if you switch @TransactionManagement (TransactionManagementType.CONTAINER) to @TransactionManagement (TransactionManagementType.BEAN) this error will no longer occur.

So you define what you define when you commit, not the server.

Body:
I am using Weblogic 12c and I am getting the below error while committing distributed transactions in my application.

"java.sql.SQLException: Cannot call Connection.commit in distributed transaction.  Transaction Manager will commit the resource manager when the distributed transaction is committed"

The part of code throwing exception is:

Session sessionNew = HibernateService.getService().getSession();
sessionNew.connection().commit();

This question has been asked several times, but the solution I am seeking is different.
The most common solution is to disable XA transactions to resolve the issue.
But my application contains more than resources like database, JMS etc.
Can anyone please suggest a solution other than the one mentioned above.

Also, I needed to understand if there is any relation between JTA transaction timeout value and the above-mentioned error.

Thanks a lot.


问:
App Showing No Internet Connection in PIE version only
My App is working perfectly fine in all android version except Pie version.
In Pie it shows No internet Connection whereas i check it with Wifi and Mobile data..it is no internet problem. This Issue is related to Pie Version.

i Try following solutions:

```<code>    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
</code>```

But both didnt work.

This is my Login button code, in which it comes in OnFailure

```<code>private void onLoginUser(String email, String password) {

    Call<LoginModel> call = ApiClient.getClientInstance().getClientService().userlogin(email, password);

    call.enqueue(new Callback<LoginModel>() {

        @Override
        public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
            mProgressBar.setVisibility(View.GONE);

            LoginModel jsonLoginResult = response.body();

            if (response.code()== 200)  {
                Log.e("Response", response.code() + "");
            }
            if (response.code() == 400 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (response.code() == 404 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (response.code() == 500 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (jsonLoginResult == null ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong("Data not found", mLoginActivity);
                return;
            }

            if (jsonLoginResult != null && response != null && response.isSuccessful() && response.body() != null) {

                String jError = "" ;
                String jMessage = "" ;
                String jUserStatus = "" ;

                try {
                    jError = String.valueOf(jsonLoginResult.getError());
                    jMessage = String.valueOf(jsonLoginResult.getMessage());
                    jUserStatus = String.valueOf(jsonLoginResult.getStatus());
                }catch (NullPointerException e){
                    Log.d("Result", e+"");
                }

                TelephonyManager mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                @SuppressLint("MissingPermission")
                String phone_imei= mTelephonyManager.getDeviceId();
                myPreference.saveString(Constants.IMEI_NUMBER , phone_imei);

                if(jUserStatus.equals(0) || jUserStatus.equalsIgnoreCase("0")){
                    myPreference.saveString(Constants.USER_STATUS , "Disapproved");
                }

                if(jUserStatus.equals(1)|| jUserStatus.equalsIgnoreCase("1")){
                    myPreference.saveString(Constants.USER_STATUS , "Approved");
                }

                if(jUserStatus.equals(3)|| jUserStatus.equalsIgnoreCase("3")){
                    myPreference.saveString(Constants.USER_STATUS , "Under Process");
                }

                if(jError.equalsIgnoreCase("false")){
                    String jUserId = String.valueOf(jsonLoginResult.getId());
                    String jUserApikey = String.valueOf(jsonLoginResult.getApikey());
                    String jUserName = String.valueOf(jsonLoginResult.getName());
                    String jUserEmail = String.valueOf(jsonLoginResult.getEmail().trim());
                    String jUserPhone = String.valueOf(jsonLoginResult.getPhone_no().trim());
                    String jUserRegisterDate = String.valueOf(jsonLoginResult.getCreated_at());
                    String jUserLogin_date = String.valueOf(jsonLoginResult.getLogin_date());
                    String jUserPancardImage = String.valueOf(jsonLoginResult.getPan_card_image());
                    String jUserChequeImage = String.valueOf(jsonLoginResult.getCheque_number_image());
                    String jUserAddressImage = String.valueOf(jsonLoginResult.getAddressProofImage());
                    String jAddress = String.valueOf(jsonLoginResult.getAddress());
                    String jCompanyName = String.valueOf(jsonLoginResult.getCompanyName());
                    String jCountryId = String.valueOf(jsonLoginResult.getCountryId());
                    String jStateId = String.valueOf(jsonLoginResult.getStateId());
                    String jCityId = String.valueOf(jsonLoginResult.getCityId());
                    String jStateName = String.valueOf(jsonLoginResult.getStateName());
                    String jCityName = String.valueOf(jsonLoginResult.getCityName());
                    String jRelationShipManager = String.valueOf(jsonLoginResult.getRelationshipManagerId());

                    Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mUNameLogin.setText("");
                                mPasswordLogin.setText("");
                                Intent i = new Intent(LoginActivity.this, HomeActivity.class);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(i);
                                LoginActivity.this.finish();

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 2000);
                }

                if(jError.equalsIgnoreCase("null")){
                    Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);
                    return;
                }

                if(jError.equalsIgnoreCase("true")){
                    popupMessageDialog(jMessage);
                    //return;
                }
            }

            else {
                assert response != null;
                Utility.getInstance(LoginActivity.this).showSnackBarLong(" "+response.message(), mLoginActivity);
                return;
            }
        }

        @Override
        public void onFailure(Call<LoginModel> call, Throwable t) {
            mProgressBar.setVisibility(View.GONE);
            if (LoginActivity.this != null) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong("No Internet Connection", mLoginActivity);
                return;
            }
        }
    });
</code>```

答:
Try bellow tow thing one remove networkSecurityConfig from your application tag and add bellow Code inside of your application tag and try

```<code> <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:enabled="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/generalnotitle"
        android:usesCleartextTraffic="true">
<uses-library
    android:name="org.apache.http.legacy"
    android:required="false" />
</code>```

Body:
My App is working perfectly fine in all android version except Pie version.
In Pie it shows No internet Connection whereas i check it with Wifi and Mobile data..it is no internet problem. This Issue is related to Pie Version.

i Try following solutions:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"

But both didnt work.

This is my Login button code, in which it comes in OnFailure

private void onLoginUser(String email, String password) {

    Call<LoginModel> call = ApiClient.getClientInstance().getClientService().userlogin(email, password);

    call.enqueue(new Callback<LoginModel>() {

        @Override
        public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
            mProgressBar.setVisibility(View.GONE);

            LoginModel jsonLoginResult = response.body();

            if (response.code()== 200)  {
                Log.e("Response", response.code() + "");
            }
            if (response.code() == 400 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (response.code() == 404 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (response.code() == 500 ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong(response.message(), mLoginActivity);
                return;
            }
            if (jsonLoginResult == null ) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong("Data not found", mLoginActivity);
                return;
            }

            if (jsonLoginResult != null && response != null && response.isSuccessful() && response.body() != null) {

                String jError = "" ;
                String jMessage = "" ;
                String jUserStatus = "" ;

                try {
                    jError = String.valueOf(jsonLoginResult.getError());
                    jMessage = String.valueOf(jsonLoginResult.getMessage());
                    jUserStatus = String.valueOf(jsonLoginResult.getStatus());
                }catch (NullPointerException e){
                    Log.d("Result", e+"");
                }

                TelephonyManager mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                @SuppressLint("MissingPermission")
                String phone_imei= mTelephonyManager.getDeviceId();
                myPreference.saveString(Constants.IMEI_NUMBER , phone_imei);

                if(jUserStatus.equals(0) || jUserStatus.equalsIgnoreCase("0")){
                    myPreference.saveString(Constants.USER_STATUS , "Disapproved");
                }

                if(jUserStatus.equals(1)|| jUserStatus.equalsIgnoreCase("1")){
                    myPreference.saveString(Constants.USER_STATUS , "Approved");
                }

                if(jUserStatus.equals(3)|| jUserStatus.equalsIgnoreCase("3")){
                    myPreference.saveString(Constants.USER_STATUS , "Under Process");
                }

                if(jError.equalsIgnoreCase("false")){
                    String jUserId = String.valueOf(jsonLoginResult.getId());
                    String jUserApikey = String.valueOf(jsonLoginResult.getApikey());
                    String jUserName = String.valueOf(jsonLoginResult.getName());
                    String jUserEmail = String.valueOf(jsonLoginResult.getEmail().trim());
                    String jUserPhone = String.valueOf(jsonLoginResult.getPhone_no().trim());
                    String jUserRegisterDate = String.valueOf(jsonLoginResult.getCreated_at());
                    String jUserLogin_date = String.valueOf(jsonLoginResult.getLogin_date());
                    String jUserPancardImage = String.valueOf(jsonLoginResult.getPan_card_image());
                    String jUserChequeImage = String.valueOf(jsonLoginResult.getCheque_number_image());
                    String jUserAddressImage = String.valueOf(jsonLoginResult.getAddressProofImage());
                    String jAddress = String.valueOf(jsonLoginResult.getAddress());
                    String jCompanyName = String.valueOf(jsonLoginResult.getCompanyName());
                    String jCountryId = String.valueOf(jsonLoginResult.getCountryId());
                    String jStateId = String.valueOf(jsonLoginResult.getStateId());
                    String jCityId = String.valueOf(jsonLoginResult.getCityId());
                    String jStateName = String.valueOf(jsonLoginResult.getStateName());
                    String jCityName = String.valueOf(jsonLoginResult.getCityName());
                    String jRelationShipManager = String.valueOf(jsonLoginResult.getRelationshipManagerId());

                    Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mUNameLogin.setText("");
                                mPasswordLogin.setText("");
                                Intent i = new Intent(LoginActivity.this, HomeActivity.class);
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(i);
                                LoginActivity.this.finish();

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 2000);
                }

                if(jError.equalsIgnoreCase("null")){
                    Utility.getInstance(LoginActivity.this).showSnackBarLong(jMessage, mLoginActivity);
                    return;
                }

                if(jError.equalsIgnoreCase("true")){
                    popupMessageDialog(jMessage);
                    //return;
                }
            }

            else {
                assert response != null;
                Utility.getInstance(LoginActivity.this).showSnackBarLong(" "+response.message(), mLoginActivity);
                return;
            }
        }

        @Override
        public void onFailure(Call<LoginModel> call, Throwable t) {
            mProgressBar.setVisibility(View.GONE);
            if (LoginActivity.this != null) {
                Utility.getInstance(LoginActivity.this).showSnackBarLong("No Internet Connection", mLoginActivity);
                return;
            }
        }
    });

Body:
Try bellow tow thing one remove networkSecurityConfig from your application tag and add bellow Code inside of your application tag and try

 <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:enabled="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:theme="@style/generalnotitle"
        android:usesCleartextTraffic="true">
<uses-library
    android:name="org.apache.http.legacy"
    android:required="false" />


问:
JS Ternary functions with multiple conditions?
I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:

```<code>var inputOneAns = inputOne == "Yes" ? "517" : "518";
</code>```

As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?

```<code>if (inputOne == "Yes"){
    var inputOneAns = "517"
}else if (inputOne == "No"{
    var inputOneAns = "518"
}else{
    var inputOneAns = ""
}
</code>```

Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.

答:
The most elegant and clean way is to take advantage of Object literals:

const Switch = (str) => ({
  "Yes": "517",
  "No": "518",
})[str] || '';

console.log(Switch("Yes")); // 517
console.log(Switch("No"));  // 518
console.log(Switch("Non matching value")); // Empty```

This has the advantage of being both readable and flexible.

Body:
I have been using a ternary operator in JavaScript to modify the value of an object based on user input. I have the following code, which runs as it should:

var inputOneAns = inputOne == "Yes" ? "517" : "518";

As you can see, I am assigning a numeric string value to inputOneAnswhether a user has inputed "Yes" or "No". However, there may be a case that a user has not selected a value (as it is not required). If this input was left blank, I would like to assign an empty string "" to inputOneAns. Is there a wayf or me to embed an ternary operator inside of another ternary operator? To help clarify, here is the same function that I want to accompolish with my ternary function but with if else statements?

if (inputOne == "Yes"){
    var inputOneAns = "517"
}else if (inputOne == "No"{
    var inputOneAns = "518"
}else{
    var inputOneAns = ""
}

Is it possible to include multiple expressions into a ternary function? Is there a better way to accomplish what I am looking for? Thanks for the tips in advance.

Body:
The most elegant and clean way is to take advantage of Object literals:

const Switch = (str) => ({
  "Yes": "517",
  "No": "518",
})[str] || '';

console.log(Switch("Yes")); // 517
console.log(Switch("No"));  // 518
console.log(Switch("Non matching value")); // Empty

This has the advantage of being both readable and flexible.


问:
Bundle several images together for HTTP?
I have a page with several hundreds of small images that need to be loaded when the page is visited. The total amount of data is 11 MB but it still takes upwards of 11 seconds to load the entire page.

Looking at the chrome network profiler, it pretty evident that the majority of time is wasted waiting for connections. A typical image has:

- 0.13 ms    - Request sent

- 240.01 ms  - Waiting (TTFB)

- 1.13 ms    - Content Download

This, with Chrome's policy of only 6 TCP connections in parallal mean that many images wait 10 seconds to be downloaded.

So clearly the problem is in the server that takes a long time to answer each request but unfortunately that's the only piece that I can't control. That server is not going to change and I can't do any caching of technology change.

Is there a way to pack all the images into a single download and then unpack in in JS in the browser? I know about the dataurl method but I was hoping for a way that would avoid the base64 bloat

EDIT:

Note that the images are part of a big SVG in the page so will the sprites solution work in an SVG?

答:
You can use CSS sprite sheets.

Live example: bkmks.com uses this trick to speed up loading lots favicons with a sprite sheet like this.

update: The workflow and syntax are slightly different, but SVG sprites are also possible:

A Guide to Create and Use SVG Sprites

How to Create and Manage SVG Sprites

Since you have raster images inside an SVG, you may also have to do the sprite trick inside the SVG. The SVG image syntax seems to support it.

If the actual images are just pure raster images (the SVG is just a "container"), I would try to remove the SVG layer. This will involve replacing all the references in the HTML to the SVG with references to the CSS sprite sheet.


问:
How to assign list attributes as list names in R
I have a list (414 elements) which contains other lists of different lengths (ranging from 0 to 9). Each of those sublists has different numbers of rows and columns.

Some of the sublists are of length 1 like the one below and have only 1 attribute:

```<code>tables_list[[1]]
     [,1]                         [,2]
[1,] "ID Number"                  "ABCD"
[2,] "Code"                       "1239463"
[3,] "Version"                    "1"
[4,] "Name"                       "ABC"
[5,] "Status"                     "Open"
[6,] "Currency"                   "USD"
[7,] "Average"                    "No"
[8,] "FX Rate"                    "2.47"

attr(,"caption")
[1] "5 && Introduction && NA"

</code>```

Other sublists are of length 2 or higher and have 1 or more attributes like the one below:

```<code>tables_list[[17]]
[[1]]
      [,1]  [,2]                                                  [,3]  [,4]              [,5]            [,6]              [,7]          [,8] [,9]
 [1,] ""    ""                                                    "USD" "Balance"         "Movement in"   "Aggregate"       "Overall"     ""   "Overall"
 [2,] ""    ""                                                    ""    "brought forward" "year"          "annual"          "aggregate"   ""   "funded account"
 [3,] ""    ""                                                    ""    "from previous"   ""              "information"    "adjustments"  ""   ""
 [4,] ""    ""                                                    ""    "year end"        ""              ""                ""            ""   ""
 [5,] ""    ""                                                    ""    "1"               "2"             "3"               "4"           ""   "5"
 [6,] "12"  "Value 1"                                             ""    "0"               "3,275,020"     "3,275,020"       ""            "0"  "3,275,020"
 [7,] "13"  "Value 2"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
 [8,] "14"  "Value 3"                                             ""    "0"               "8,267,862"     "8,267,862"       ""            "0"  "8,267,862"
 [9,] "15"  "Value 4"                                             ""    "0"               "(590,073,321)" "(590,073,321)"   ""            "0"  "(590,073,321)"
[10,] "16"  "Value 5"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[11,] "17"  "Value 6"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[12,] "18"  "Value 7"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[13,] "19"  "Value 8"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[14,] "20"  "Value 9"                                             ""    "0"               "(459,222,782)" "(459,222,782)"   ""            "0"  "(459,222,782)"

[[2]]
     [,1]               [,2]   [,3]                                                                  [,4]
[1,] "Theme"            "Year" "Comment"                                                             "Created"
[2,] "Line 17 Column 2" "N/A"  "Amounts are calculated according to recent standards"                "XXXXXXXXXXXX"
[3,] ""                 ""     "paid by XXXXXXXXXXXXX"                                               ""
attr(,"caption")
[1] "20 && Values for year 2017 && NA"
[2] "20 && Comments for 2017 && NA"
</code>```

This is my code for assigning the attribute to each list in tables_list.

```<code>tables_list <- lapply(tables$page, function(p) {
    cat(p, "\n")
    out <- extract_tables(Path,
                          pages = p,
                          encoding = "UTF-8",
                          method = "stream",
                          output = "matrix")
    #This part of the code points out the title, page of each table and reporting year if applicable so we can keep track of what goes where
    attr(out, "caption") <- paste(as.character(tables$page[tables$page %in% p]), tables$text[tables$page %in% p], tables$Reportingyear[tables$page %in% p], sep = " && ")
    return(out)
  })
</code>```

I cannot figure out a way to assign these attributes as the names of their respective lists. Does anyone have any ideas how to approach this?

答:
If I understand correctly, the following assigns the values of attribute "caption" to each of the sub-lists.

```<code>tables_list <- lapply(tables_list, function(L){
  names(L) <- sapply(L, attr, "caption")
  L
})

tables_list[[2]]$V
#     [,1] [,2]
#[1,]    1    6
#[2,]    2    7
#[3,]    3    8
#[4,]    4    9
#[5,]    5   10
#attr(,"caption")
#[1] "V"
</code>```

Data example creation code.

This creates a list of lists, each of them with matrices as members. The matrices have attribute "caption" set to an uppercase letter.

```<code>tables_list <- list(
  list(matrix(1:6, nrow = 3)),
  list(matrix(1:8, nrow = 4), matrix(1:10, nrow = 5)),
  list(matrix(1:4, nrow = 2), matrix(1:18, nrow = 9), matrix(4:1, nrow = 4))
)

set.seed(1234)
tables_list <- lapply(tables_list, function(L){
  lapply(L, function(M) {
    attr(M, "caption") <- sample(LETTERS, 1)
    M
  })
})
</code>```

Body:
I have a list (414 elements) which contains other lists of different lengths (ranging from 0 to 9). Each of those sublists has different numbers of rows and columns.

Some of the sublists are of length 1 like the one below and have only 1 attribute:

tables_list[[1]]
     [,1]                         [,2]
[1,] "ID Number"                  "ABCD"
[2,] "Code"                       "1239463"
[3,] "Version"                    "1"
[4,] "Name"                       "ABC"
[5,] "Status"                     "Open"
[6,] "Currency"                   "USD"
[7,] "Average"                    "No"
[8,] "FX Rate"                    "2.47"

attr(,"caption")
[1] "5 && Introduction && NA"

Other sublists are of length 2 or higher and have 1 or more attributes like the one below:

tables_list[[17]]
[[1]]
      [,1]  [,2]                                                  [,3]  [,4]              [,5]            [,6]              [,7]          [,8] [,9]
 [1,] ""    ""                                                    "USD" "Balance"         "Movement in"   "Aggregate"       "Overall"     ""   "Overall"
 [2,] ""    ""                                                    ""    "brought forward" "year"          "annual"          "aggregate"   ""   "funded account"
 [3,] ""    ""                                                    ""    "from previous"   ""              "information"    "adjustments"  ""   ""
 [4,] ""    ""                                                    ""    "year end"        ""              ""                ""            ""   ""
 [5,] ""    ""                                                    ""    "1"               "2"             "3"               "4"           ""   "5"
 [6,] "12"  "Value 1"                                             ""    "0"               "3,275,020"     "3,275,020"       ""            "0"  "3,275,020"
 [7,] "13"  "Value 2"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
 [8,] "14"  "Value 3"                                             ""    "0"               "8,267,862"     "8,267,862"       ""            "0"  "8,267,862"
 [9,] "15"  "Value 4"                                             ""    "0"               "(590,073,321)" "(590,073,321)"   ""            "0"  "(590,073,321)"
[10,] "16"  "Value 5"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[11,] "17"  "Value 6"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[12,] "18"  "Value 7"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[13,] "19"  "Value 8"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[14,] "20"  "Value 9"                                             ""    "0"               "(459,222,782)" "(459,222,782)"   ""            "0"  "(459,222,782)"

[[2]]
     [,1]               [,2]   [,3]                                                                  [,4]
[1,] "Theme"            "Year" "Comment"                                                             "Created"
[2,] "Line 17 Column 2" "N/A"  "Amounts are calculated according to recent standards"                "XXXXXXXXXXXX"
[3,] ""                 ""     "paid by XXXXXXXXXXXXX"                                               ""
attr(,"caption")
[1] "20 && Values for year 2017 && NA"
[2] "20 && Comments for 2017 && NA"

This is my code for assigning the attribute to each list in tables_list.

tables_list <- lapply(tables$page, function(p) {
    cat(p, "\n")
    out <- extract_tables(Path,
                          pages = p,
                          encoding = "UTF-8",
                          method = "stream",
                          output = "matrix")
    #This part of the code points out the title, page of each table and reporting year if applicable so we can keep track of what goes where
    attr(out, "caption") <- paste(as.character(tables$page[tables$page %in% p]), tables$text[tables$page %in% p], tables$Reportingyear[tables$page %in% p], sep = " && ")
    return(out)
  })

I cannot figure out a way to assign these attributes as the names of their respective lists. Does anyone have any ideas how to approach this?

Body:
If I understand correctly, the following assigns the values of attribute "caption" to each of the sub-lists.

tables_list <- lapply(tables_list, function(L){
  names(L) <- sapply(L, attr, "caption")
  L
})

tables_list[[2]]$V
#     [,1] [,2]
#[1,]    1    6
#[2,]    2    7
#[3,]    3    8
#[4,]    4    9
#[5,]    5   10
#attr(,"caption")
#[1] "V"

Data example creation code.

This creates a list of lists, each of them with matrices as members. The matrices have attribute "caption" set to an uppercase letter.

tables_list <- list(
  list(matrix(1:6, nrow = 3)),
  list(matrix(1:8, nrow = 4), matrix(1:10, nrow = 5)),
  list(matrix(1:4, nrow = 2), matrix(1:18, nrow = 9), matrix(4:1, nrow = 4))
)

set.seed(1234)
tables_list <- lapply(tables_list, function(L){
  lapply(L, function(M) {
    attr(M, "caption") <- sample(LETTERS, 1)
    M
  })
})


问:
How to store results of a Dynamic Query in a temp table without creating a table?
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

```<code>  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query
</code>```

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

答:
I think it comes from sql concept that it doesn't trust in result of stored procedures and because of that we cannot select on it or store it in a table by 'making in query table' method.
Unless you create a table and define it's columns and sql trust to you and you insert result of it into this table for example take below situation

Create table test (name varchar(10),family varchar(20))

Insert into test
Exec sp-testResult
```

Now if you define wrong column for your table  you will receive query runtime error .actually sql doesn't predict result of sp and leaves it to you to define result of your stored procedure.

Body:
We are writing a stored procedure responsible for getting a stored procedure name and returning a result containing the stored procedure columns and their data types.
However, we bumped into a problem executing a dynamic query to return the results of stored procedure, but we can't store it in a temp table!

You can see our query below:

  DECLARE @ProcName VARCHAR(100)='spGetOraganizationsList',
  @ParamName VARCHAR(100),@DataType VARCHAR(20),
  @Query NVARCHAR(MAX)='EXEC '+'spGetOraganizationsList '

  SELECT  PARAMETER_NAME,DATA_TYPE
  INTO #Tmp
  FROM  information_schema.PARAMETERS
  WHERE SPECIFIC_NAME=@ProcName

  DECLARE ParamCursor CURSOR
  FOR SELECT * FROM #Tmp
  OPEN ParamCursor
  FETCH NEXT FROM ParamCursor
  INTO @ParamName,@DataType

  WHILE @@FETCH_STATUS = 0
  BEGIN
  SET @Query=@Query+@ParamName+'=Null,'
  FETCH NEXT FROM ParamCursor INTO @ParamName,@DataType
  END
  CLOSE ParamCursor
  DEALLOCATE ParamCursor
  DROP TABLE #Tmp

  EXEC sp_executesql @Query

The thing is I can't store the results of it in a temp table,
and OPENROWSET does not accept variables.

Body:
I think it comes from sql concept that it doesn't trust in result of stored procedures and because of that we cannot select on it or store it in a table by 'making in query table' method.
Unless you create a table and define it's columns and sql trust to you and you insert result of it into this table for example take below situation

Create table test (name varchar(10),family varchar(20))

Insert into test
Exec sp-testResult

Now if you define wrong column for your table  you will receive query runtime error .actually sql doesn't predict result of sp and leaves it to you to define result of your stored procedure.


问:
How many maximum number of subqueries can you put in a single hive query?
I am working in MySql. Hive, to be particular.</p>

答: There is no such limit, however, you can refer the documentation for kind of subqueries are supported.</p>


问:
Spring Cloud Stream DLQ, Producer and Consumer Residing under Multiple Application
I have producer in say Application A with the below configuration,

Producer Properties:

```<code>spring.cloud.stream.bindings.packageVersionUpdatesPublishChannel.destination=fabric-exchange
    spring.cloud.stream.bindings.packageVersionUpdatesPublishChannel.producer.requiredGroups=version-updates
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.exchangeType=direct
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.routingKeyExpression='package-version'
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.bindingRoutingKey=package-version
</code>```

And I have a Consumer for the same Queue in an another application say B,

```<code>#Consumer Properties:
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.destination=fabric-exchange
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.group=package-version-updates
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.consumer.max-attempts=1
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.exchangeType=direct
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.durableSubscription=true
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.bindingRoutingKey=package-version
#DLQ
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.autoBindDlq=true
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.dlqDeadLetterExchange=
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.dlq-ttl=30000
#Error Exchange Creation and Bind the Same to Error Queue
spring.cloud.stream.bindings.packageVersionUpdatesErrorPublishChannel.destination=fabric-error-exchange
spring.cloud.stream.bindings.packageVersionUpdatesErrorPublishChannel.producer.requiredGroups=package-version-updates-error
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.exchangeType=direct
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.routingKeyExpression='packageversionupdateserror'
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.bindingRoutingKey=packageversionupdateserror
</code>```

Now say for example if the Application A boots first, then the Queue version-updates would be created without any dead letter queue associated with it.

And now the when the Application B starts, this is the exception I get and the channel gets shudtdown, I think this is because app B is trying to re-create the queue with a different configuration

inequivalent arg 'x-dead-letter-exchange' for queue 'fabric-exchange.version-updates' in vhost '/': received the value 'DLX' of type 'longstr' but current is none

Can anyone please let me know, how do i solve this, where my requirement is to create a Queue in App A and App-A would simple produce the messages onto this queue

And App-B would consume the same and my requirement is to support re-tries after X amount of time through DLQ

答:
required-groups is simply a convenience to provision the consumer queue when the producer starts, to avoid losing messages if the producer starts first.

You must use identical exchange/queue/binding configuration on both sides.

Body:
I have producer in say Application A with the below configuration,

Producer Properties:

spring.cloud.stream.bindings.packageVersionUpdatesPublishChannel.destination=fabric-exchange
    spring.cloud.stream.bindings.packageVersionUpdatesPublishChannel.producer.requiredGroups=version-updates
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.exchangeType=direct
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.routingKeyExpression='package-version'
    spring.cloud.stream.rabbit.bindings.packageVersionUpdatesPublishChannel.producer.bindingRoutingKey=package-version

And I have a Consumer for the same Queue in an another application say B,

#Consumer Properties:
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.destination=fabric-exchange
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.group=package-version-updates
spring.cloud.stream.bindings.packageVersionUpdatesConsumerChannel.consumer.max-attempts=1
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.exchangeType=direct
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.durableSubscription=true
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.bindingRoutingKey=package-version
#DLQ
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.autoBindDlq=true
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.dlqDeadLetterExchange=
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesConsumerChannel.consumer.dlq-ttl=30000
#Error Exchange Creation and Bind the Same to Error Queue
spring.cloud.stream.bindings.packageVersionUpdatesErrorPublishChannel.destination=fabric-error-exchange
spring.cloud.stream.bindings.packageVersionUpdatesErrorPublishChannel.producer.requiredGroups=package-version-updates-error
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.exchangeType=direct
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.routingKeyExpression='packageversionupdateserror'
spring.cloud.stream.rabbit.bindings.packageVersionUpdatesErrorPublishChannel.producer.bindingRoutingKey=packageversionupdateserror

Now say for example if the Application A boots first, then the Queue version-updates would be created without any dead letter queue associated with it.

And now the when the Application B starts, this is the exception I get and the channel gets shudtdown, I think this is because app B is trying to re-create the queue with a different configuration

inequivalent arg 'x-dead-letter-exchange' for queue 'fabric-exchange.version-updates' in vhost '/': received the value 'DLX' of type 'longstr' but current is none

Can anyone please let me know, how do i solve this, where my requirement is to create a Queue in App A and App-A would simple produce the messages onto this queue

And App-B would consume the same and my requirement is to support re-tries after X amount of time through DLQ


问:
How to create a conditional string that's based on two variables without a bunch of if elses (JavaScript)
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}
```

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

答:
1st - Use ES6 string templates

```<code>let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = `The url 1 is ${ url1 } and url 2 is ${ url2 }`;
} else if (!url1 && url2) {
  finalString = `There isnt data for url1. Url2 is ${ url2 }`;
} else if (url1 && !url2) {
  finalString = `The url 1 is ${ url1 }. There isnt data for url2`;
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}
</code>```

2nd - unify and extract

```<code>const urls = {
  url1: containsData1 ? "http://test" : null,
  url2: containsData2 ? "http://test" : null,
}

const assertData = name => urls[name] ? `${name} is ${urls[name]}` : `isnt data for ${name}`

let finalString = `${assertData('url1')}. ${assertData('url2')}`
</code>```

Body:
I am trying to create a custom string to be shown to the user, which is based on two variables.

Here is the example that I am trying to build:

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = 'The url 1 is ' + url1 + ' and url 2 is ' + url2;
} else if (!url1 && url2) {
  finalString = 'There isnt data for url1. Url2 is ' + url2;
} else if (url1 && !url2) {
  finalString = 'The url 1 is ' + url1 + '. There isnt data for url2';
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}

However I would like to this in a proper way, without using this bunch of if elses, any suggestions on how to accomplish this?

Thanks.

Body:
1st - Use ES6 string templates

let url1;
let url2;
if (containsData1) {
  url1 = "http://test";
}

if (containsData2) {
  url2 = "http://test2";
}

let finalString = '';
if (url1 && url2) {
  finalString = `The url 1 is ${ url1 } and url 2 is ${ url2 }`;
} else if (!url1 && url2) {
  finalString = `There isnt data for url1. Url2 is ${ url2 }`;
} else if (url1 && !url2) {
  finalString = `The url 1 is ${ url1 }. There isnt data for url2`;
} else if (!url1 && !url2) {
  finalString = 'There isnt data for url1. There isnt data for url2';
}

2nd - unify and extract

const urls = {
  url1: containsData1 ? "http://test" : null,
  url2: containsData2 ? "http://test" : null,
}

const assertData = name => urls[name] ? `${name} is ${urls[name]}` : `isnt data for ${name}`

let finalString = `${assertData('url1')}. ${assertData('url2')}`


问:
Colormaps with a colorscale AND one color for unwanted values
I would like to plot a grid of 3 variables (same min, same max, same spacing) in 3D and I would like each point on the grid to have a specific color according to a function f which is a function of these 3 variables except for when the values of the function are superior to a specific threshold for which I assign another color.

The code below as what I have tried so far:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.colors
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import math
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

%matplotlib notebook

x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t)

#masking high values with the highest interesting value: maxV
mfflat = ma.masked_greater(fflat, maxV)
mfflat = mfflat.filled(maxV)

#normalizing values and mapping to veridis cmap:
cmap = matplotlib.cm.get_cmap('viridis')
norm = matplotlib.colors.Normalize(vmin=min(mfflat), vmax=maxV) #(vmax=maxV=max(mfflat))
colors = [cmap(norm(value)) for value in mfflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
```

The problem is that now all the "unwanted high values", i.e. values > maxV have the same colors as my "maximal wanted values", i.e. maxV ...

I would like all my "unwanted values" outside of my veridis colorscale and giving them another unique color.

Thanks for your help !
Cheers

答:
Thanks to ImportanceOfBeingErnest for the answer, I just had to use: cmap.set_over, here is the corrected code:

```<code>x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t)

cmap = plt.cm.get_cmap('viridis')
cmap.set_over(color=(0,0,0), alpha=0.5)
norm = matplotlib.colors.Normalize(vmin=minV, vmax=maxV)
colors = [cmap(norm(value)) for value in fflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
</code>```

In the meantime I have found a workaround by creating the "colors" list selectively which is of course not as clean as using cmap.set_over:

```<code>colors=[]
for value in fflat:
    if minV <= value <= maxV:
        colors.append(cmap(norm(value)))
    else:
        colors.append((255/258,255/258,255/258,0))
</code>```

Body:
I would like to plot a grid of 3 variables (same min, same max, same spacing) in 3D and I would like each point on the grid to have a specific color according to a function f which is a function of these 3 variables except for when the values of the function are superior to a specific threshold for which I assign another color.

The code below as what I have tried so far:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.colors
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import math
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

%matplotlib notebook

x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t)

#masking high values with the highest interesting value: maxV
mfflat = ma.masked_greater(fflat, maxV)
mfflat = mfflat.filled(maxV)

#normalizing values and mapping to veridis cmap:
cmap = matplotlib.cm.get_cmap('viridis')
norm = matplotlib.colors.Normalize(vmin=min(mfflat), vmax=maxV) #(vmax=maxV=max(mfflat))
colors = [cmap(norm(value)) for value in mfflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)

The problem is that now all the "unwanted high values", i.e. values > maxV have the same colors as my "maximal wanted values", i.e. maxV ...

I would like all my "unwanted values" outside of my veridis colorscale and giving them another unique color.

Thanks for your help !
Cheers

Body:
Thanks to ImportanceOfBeingErnest for the answer, I just had to use: cmap.set_over, here is the corrected code:

x = np.arange(0.001, 0.175, 0.01)
y = np.arange(0.001, 0.175, 0.01)
z = np.arange(0.001, 0.175, 0.01)

X, Y, Z = np.meshgrid(x, y, z)

def function(X,Y,Z):
   '''function of (X,Y,Z) going from 0 to high values'''
   return(f)

f=function(X,Y,Z)

#flatten the f array (I think there is a function to flatten an array but I have seen it to late)
fflat=[]
for l in f:
    for p in l:
        for t in p:
            fflat.append(t)

cmap = plt.cm.get_cmap('viridis')
cmap.set_over(color=(0,0,0), alpha=0.5)
norm = matplotlib.colors.Normalize(vmin=minV, vmax=maxV)
colors = [cmap(norm(value)) for value in fflat]

#plot
ax.scatter(X, Y, Z, color=colors, s=10, alpha=1)
cax, _ = matplotlib.colorbar.make_axes(ax)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)

In the meantime I have found a workaround by creating the "colors" list selectively which is of course not as clean as using cmap.set_over:

colors=[]
for value in fflat:
    if minV <= value <= maxV:
        colors.append(cmap(norm(value)))
    else:
        colors.append((255/258,255/258,255/258,0))


问:
Matlab optimproblem: Possible to use 3rd party ILP solver?
I've been browsing the Matlab's [mixed] integer linear program ([M]ILP) commands/classes documentation to see if there is a way to define an "optimization problem" (optimproblem) and call out to an external [M]ILP solver using an API rather than using the native intlinprog.  I haven't yet found any indication that this is possible, short of converting the problem to matrix/solver-based format (prob2struct) and creating my own intermediate ILP data file.  That would be beyond what I am willing to do.

Is there in fact no way to directly invoke a 3rd party solver?

If there is a way, can someone please direct me to the proper documentation page?

If there is in fact no way, can someone please confirm this?

Thanks.

Clarification: Question emphasizes use of optimproblem

I appreciate the answers and comments to date, but I realize from them that I need to emphasize a key point in the question. My aim is to exploit the high level problem specification of optimproblem, which uses Matlab's array syntax to compactly represent a large number of constraints, lengthy inner products for them, and for the objective function.  This is the so-called problem-based approach, which is akin in high level to AMPL.

In contrast, my impression from initial browsings of the cited documents on 3rd party solvers is that their inputs are at a lower level of abstraction.  This is the so-called solver-based approach, which colleagues have also called the "matrix level", for the following reason: The archetypal arrays x, Aeq, beq, Aineq, bineq, etc., are assumed to have been composed, and it is up to the analyst to keep track of which elements in x correspond to which (more) real-world parameters, i.e., those in the problem-based approach.

I was hoping that there was a way to use optimproblem and have it use a 3rd party solver so that I don't have to deal with the matrix level.  An example of the latter would be using prob2struct to generate arrays to explicitly pass to external solvers via Matlab APIs (if they have them).  I want to avoid this because I don't want to keep track of which problem-based variables map to which solver-based variables, especially since the former is often of high dimensionality. Granted, varindex simplifies the bookkeeping, but not having to code for such bookkeeping is much preferable.

答: According to TMW, the answer is "no" at present (May 30, 2019).</p>


问:
How to deal with relative path in Junits between Maven and Intellij
I have a maven project with a module

```<code>/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt
</code>```

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

```<code>  new File("foo/bar.txt")
</code>```

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?

答:
a) Don't use Files, use InputStreams. get your InputStream via

```<code>ClassLoader.getSystemResourceAsStream("foo/bar.xml")
</code>```

Most APIs that deal with Files are happy with InputStreams as well.

b) Don't use foo directories, use directories both maven and your IDE know about (i.e. put them in src/main/resources or src/test/resources, so they are on the Class Path)

c) If you have an API that absolutely needs a File, not an InputStream, you can still do

```<code>new File(ClassLoader.getSystemResource("foo/bar.xml").toURI())
</code>```

Body:
I have a maven project with a module

/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

So to open the file bar.txt  :

  new File("foo/bar.txt")

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

Is there a way to deal with that ?

Body:
a) Don't use Files, use InputStreams. get your InputStream via

ClassLoader.getSystemResourceAsStream("foo/bar.xml")

Most APIs that deal with Files are happy with InputStreams as well.

b) Don't use foo directories, use directories both maven and your IDE know about (i.e. put them in src/main/resources or src/test/resources, so they are on the Class Path)

c) If you have an API that absolutely needs a File, not an InputStream, you can still do

new File(ClassLoader.getSystemResource("foo/bar.xml").toURI())


问:
Embedding dynamic script when page scrolls
I am trying to add an iframe which consist of form . I am inserting this iframe when the page is loaded already and scrolled at some position ,I have used jquery this script is working fine it appending that script tag  under that div but the thing it should load iframe at that place.  please help out

please point out whats wrong in this question

i found that iframe is generated by script its not loaded first itself

$(document).ready(function() {
  var element_position = $('#Banner').offset().top;

  $(window).one('scroll', function() {

    if (y_scroll_pos < 300) {
      //do stuff
      $('#form1').load("http://www.samisite.com/test-csb2nf/ifform/somejsthatgenrateiframe");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="Banner"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-in">
  <script id="form1"></script></code>```

答: Use lazyload! I suggest you this one that supports iframes: https://apoorv.pro/lozad.js/</p>


问:
Best way to get file list in dir sorted by added date
I have to delete the oldest file in dir when the newest added file exceed the used space limit. I don't know why the sorted list files = sorted(os.listdir(DIR), key=os.path.getctime) do not contain on first element the oldest file ( in this case file named 'file_1')

code

```<code>    print('START: Cycle no. ', cycle)
    time.sleep(1)
    print('Saving {0} files. {1} MB each'.format(FILES_NUM, MB_FILE_SIZE))
    i = 1
    while (i < FILES_NUM):
        usage = psutil.disk_usage(DIR)
        used = usage.used // (2**20)
        # print('Uzyta pamiec: ', used)
        if (used < 50): # 50 MB
            print('Saving file_{}'.format(i))
            with open("file_{}".format(i), 'wb') as f:
                f.write(os.urandom(FILE_SIZE))
        else:
            files = sorted(os.listdir(DIR), key=os.path.getctime)
            print('Files list: ', files)
            os.remove(files[0])
            print('Deleted oldest file: ',files[0])
        i = i + 1

    print('KONIEC: Cycle no. ', cycle)
    print('Deleting the content of the card...')
</code>```

results

EDIT:
I know that the next file after deletion should have the ending in the file name one larger than the previous addition. In this example should be Saving file_22 instead of Saving file_23. The 22nd 'i' is used in deletion process, but how can I overcome this issue?

答:
You sort files by ctime not alphabetically so don't assume the oldest file will be file_1. Let's see this using a simplified version of your code:

```<code>import os
import sys

from datetime import datetime

FILES_NUM = 10
FILE_SIZE = 10

def main():
    for i in range(1, FILES_NUM + 1):
        if i == 5: # Assume disk usage has been exceeded
            files = sorted(os.listdir('.'), key=os.path.getctime)
            files = [
                f'{i} - {datetime.fromtimestamp(os.path.getctime(i))}'
                for i in files
                if i.startswith('file_')
            ]
            print(f'Files list: {files}')
            print(f'Deleted oldest file: {files[0]}')

        print(f'Saving file{i}')
        with open(f'file_{i}', 'wb') as f:
            f.write(os.urandom(FILE_SIZE))

if __name__ == '__main__':
    main()
</code>```

First run (no files):

```<code>$ python test.py
Saving file1
Saving file2
Saving file3
Saving file4
Files list: ['file_1 - 2019-05-30 15:36:36.366754', 'file_2 - 2019-05-30 15:36:36.367754', 'file_4 - 2019-05-30 15:36:36.367754', 'file_3 - 2019-05-30 15:36:36.367754']
Deleted oldest file: file_1 - 2019-05-30 15:36:36.366754
Saving file5
Saving file6
Saving file7
Saving file8
Saving file9
Saving file10
</code>```

Seconds run (old files already exist):

```<code>$ python test.py
Saving file1
Saving file2
Saving file3
Saving file4
Files list: ['file_6 - 2019-05-30 15:36:36.367754', 'file_5 - 2019-05-30 15:36:36.367754', 'file_7 - 2019-05-30 15:36:36.367754', 'file_8 - 2019-05-30 15:36:36.368754', 'file_10 - 2019-05-30 15:36:36.368754', 'file_9 - 2019-05-30 15:36:36.368754', 'file_1 - 2019-05-30 15:37:00.360535', 'file_2 - 2019-05-30 15:37:00.361535', 'file_4 - 2019-05-30 15:37:00.361535', 'file_3 - 2019-05-30 15:37:00.361535']
Deleted oldest file: file_6 - 2019-05-30 15:36:36.367754
Saving file5
Saving file6
Saving file7
Saving file8
Saving file9
Saving file10
</code>```

As you can see the oldest file during second run is file_6. That's because when disk usage is above the threshold, we enter the if branch where we sort and list existing files, only 1-4 files were created at that point so 5-10 are still older.

Please also note that ctime is the time of the last metadata change on UNIX systems (file ownership, permissions, not a content modification). You can try mtime to sort by a modification date.

The index issue should be also fixed now after the logic in the code has been slightly changed.

Note: example is using Python 3.7+

Body:
I have to delete the oldest file in dir when the newest added file exceed the used space limit. I don't know why the sorted list files = sorted(os.listdir(DIR), key=os.path.getctime) do not contain on first element the oldest file ( in this case file named 'file_1')

code

    print('START: Cycle no. ', cycle)
    time.sleep(1)
    print('Saving {0} files. {1} MB each'.format(FILES_NUM, MB_FILE_SIZE))
    i = 1
    while (i < FILES_NUM):
        usage = psutil.disk_usage(DIR)
        used = usage.used // (2**20)
        # print('Uzyta pamiec: ', used)
        if (used < 50): # 50 MB
            print('Saving file_{}'.format(i))
            with open("file_{}".format(i), 'wb') as f:
                f.write(os.urandom(FILE_SIZE))
        else:
            files = sorted(os.listdir(DIR), key=os.path.getctime)
            print('Files list: ', files)
            os.remove(files[0])
            print('Deleted oldest file: ',files[0])
        i = i + 1

    print('KONIEC: Cycle no. ', cycle)
    print('Deleting the content of the card...')

results

EDIT:
I know that the next file after deletion should have the ending in the file name one larger than the previous addition. In this example should be Saving file_22 instead of Saving file_23. The 22nd 'i' is used in deletion process, but how can I overcome this issue?

Body:
You sort files by ctime not alphabetically so don't assume the oldest file will be file_1. Let's see this using a simplified version of your code:

import os
import sys

from datetime import datetime

FILES_NUM = 10
FILE_SIZE = 10

def main():
    for i in range(1, FILES_NUM + 1):
        if i == 5: # Assume disk usage has been exceeded
            files = sorted(os.listdir('.'), key=os.path.getctime)
            files = [
                f'{i} - {datetime.fromtimestamp(os.path.getctime(i))}'
                for i in files
                if i.startswith('file_')
            ]
            print(f'Files list: {files}')
            print(f'Deleted oldest file: {files[0]}')

        print(f'Saving file{i}')
        with open(f'file_{i}', 'wb') as f:
            f.write(os.urandom(FILE_SIZE))

if __name__ == '__main__':
    main()

First run (no files):

$ python test.py
Saving file1
Saving file2
Saving file3
Saving file4
Files list: ['file_1 - 2019-05-30 15:36:36.366754', 'file_2 - 2019-05-30 15:36:36.367754', 'file_4 - 2019-05-30 15:36:36.367754', 'file_3 - 2019-05-30 15:36:36.367754']
Deleted oldest file: file_1 - 2019-05-30 15:36:36.366754
Saving file5
Saving file6
Saving file7
Saving file8
Saving file9
Saving file10

Seconds run (old files already exist):

$ python test.py
Saving file1
Saving file2
Saving file3
Saving file4
Files list: ['file_6 - 2019-05-30 15:36:36.367754', 'file_5 - 2019-05-30 15:36:36.367754', 'file_7 - 2019-05-30 15:36:36.367754', 'file_8 - 2019-05-30 15:36:36.368754', 'file_10 - 2019-05-30 15:36:36.368754', 'file_9 - 2019-05-30 15:36:36.368754', 'file_1 - 2019-05-30 15:37:00.360535', 'file_2 - 2019-05-30 15:37:00.361535', 'file_4 - 2019-05-30 15:37:00.361535', 'file_3 - 2019-05-30 15:37:00.361535']
Deleted oldest file: file_6 - 2019-05-30 15:36:36.367754
Saving file5
Saving file6
Saving file7
Saving file8
Saving file9
Saving file10

As you can see the oldest file during second run is file_6. That's because when disk usage is above the threshold, we enter the if branch where we sort and list existing files, only 1-4 files were created at that point so 5-10 are still older.

Please also note that ctime is the time of the last metadata change on UNIX systems (file ownership, permissions, not a content modification). You can try mtime to sort by a modification date.

The index issue should be also fixed now after the logic in the code has been slightly changed.

Note: example is using Python 3.7+