问:
Incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

```<code>  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}
</code>```

While this is the the Activity class that the Above Fragment is been called from.

```<code> @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}
</code>```

So am getting the following errors:

```<code>Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
</code>```

答:
Use this

```<code>Bundle args= new Bundle();
args.putParcelableArrayList(POST_TOTAL, postTotal);
fragment.setArguments(bundle);
</code>```

instead of

```<code> Bundle args = new Bundle();
 args.putString(POST_TOTAL, postTotal);
 fragment.setArguments(args);
</code>```

After this you can get back this data by using

```<code>Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist  = extras.getParcelableArrayList("arraylist");
</code>```

Body:
Am trying to pass a List<> from an activity to a fragment.

When an imageView is clicked; the onClick event triggers a call to the server that takes the userId of the user that clicked on the imageView and the userId of the users profile you want to see.i have an interface that  that takes the response gotten from the server, which is then sent to a new fragment class. The problem am having is that i cannot pass a List<> through the bundle.

This is the newInstance of the fragment class and the parameter am trying to send across

  public static HomeUserProfileFragment newInstance(String postTotal, String followersTotal
        , String followingTotal, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    HomeUserProfileFragment fragment = new HomeUserProfileFragment();
    Bundle args = new Bundle();
    args.putString(POST_TOTAL, postTotal);
    args.putString(FOLLOWERS_TOTAL, followersTotal);
    args.putString(FOLLOWING_TOTAL, followingTotal);
    args.putStringArrayList(UPLOAD_POST_LIST,uploadPostList);
    args.putStringArrayList(FOLLOWERS_LIST,followersList);
    args.putStringArrayList(FOLLOWING_LIST, followingList);
    fragment.setArguments(args);
    return fragment;
}

While this is the the Activity class that the Above Fragment is been called from.

 @Override
public void onClickUserProfile(String post, String followers, String following, List<UploadPost> uploadPostList, List<FollowUser> followersList, List<FollowUser> followingList) {

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.frame_container,   HomeUserProfileFragment.newInstance(post, followers, following,uploadPostList,followersList,followingList))
            .addToBackStack(null)
            .commit();
}

So am getting the following errors:

Error:(56, 50) error: incompatible types: List<UploadPost> cannot be converted to ArrayList<String>
Error:(57, 48) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>
Error:(58, 49) error: incompatible types: List<FollowUser> cannot be converted to ArrayList<String>

Body:
Use this

Bundle args= new Bundle();
args.putParcelableArrayList(POST_TOTAL, postTotal);
fragment.setArguments(bundle);

instead of

 Bundle args = new Bundle();
 args.putString(POST_TOTAL, postTotal);
 fragment.setArguments(args);

After this you can get back this data by using

Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist  = extras.getParcelableArrayList("arraylist");


来源: stackexchange

问:
To use or not to use SSL? Why use SSL always?
The argument for using SSL is to prevent some malicious user who has gone through the pains of snooping your traffic being able to read your traffic. So while it may make sense if you are using an unsecured wireless (non WPA2) network to use SSL when logging on to your bank account or giving your credit card number, I find it difficult to see it's neccessaity in more common business cases.

Why even bother with SSL?  (when your client is not going to be on an unsecured wireless network)

The only way someone can snoop your particular HTTP connections and data therein is if they have admin access to your router (and then only if there is some facility to monitor/copy traffic), installed some tool on your machine (a key logger of course would by pass SSL anyway) or they monitor you at the ISP (for which a warrant is required in most jurisdictions).

Update Warning Some jurisdictions are not as free as you may think, particularly the 1st and 2nd world, e.g. in the UK, government may soon not require a warrant: http://en.wikipedia.org/wiki/Communications_Data_Bill_2008 which will probably entail the ability to read websites as they were historically (i.e. decrypt SSL) and the US's "Patriot Act" http://en.wikipedia.org/wiki/US_Patriot_Act#Title_II:_Surveillance_procedures

Furthermore:

Accepting SSL connections server side adds significant load as the establishing of a connection is processor intensive (during the generation of secret keys).

Publicly trusted SSL certificates have to be purchased from a 3rd Party periodically

UPDATE: I am actually using SSL, though I thought it worthwhile to ask the question anyway. Certainly I think there are time SSL is not necessary. Maybe this could be turned into a community wiki of the pros and cons of SSL? If so how?

There seems to be commonly occurring myth in the answers below: "anyone between you and the server can eavesdrop on you"...

This is not not possible on the Internet as the low level TCP routers only forward packets where they have to go and even in the same session can be routed through different routes, and no one can look at these packets except in extreme cases - technically or lawfully.

As for someone at the ISP looking at your traffic I wonder why they would signal you out and look at the 'so important data' which no doubt is boring to them, this is also illegal without a warrant.

On your LAN (except wireless) unless you are using a dinosaur Hub which broadcasts every packet there is no way listen on someone else's traffic - this is not possible because the hardware simply does not send the packets to you even if you have your network card in promiscuous mode and are using a sniffing tool such as Snort or Wireshark.

Passive ARP poisoning is one way to  listen in but has to be done internally and should be picked up as name conflicts etc. start occuring and often the default gateway would be static so would be v. difficult cause the default gateway will be on before you.

答:
The problem is that using, say, WPA2 only secures the connection between your computer and the router. There is a large piece of unsecured network between the router and the destination - that's the design of the internet. You don't know who is along the path and there could be any number of malicious (or just nosey) listeners out there. They may not even be in your jurisdiction so preventing eavesdropping may well be impossible.

SSL gives you an encrypted tunnel all the way to the other end.

If you're talking about a small company LAN where no traffic leaves the internal network then sure, don't bother with SSL if you don't want to. But if anything sensitive goes across the internet then you really want to use SSL to stop anyone seeing it. It's all about how important the information is.

One thing to be aware of is that many websites use cookies to remember login information. If those cookies go across the internet in the clear then it is fairly trivial to hijack the session - think FireSheep. Thus, you need to be very careful about what you consider to be "sensitive" information. Given that many business applications are moving to remote servers (I think the young'uns call it "the cloud") this is not a minor issue.

Long story short, use SSL if there is anything you don't want anyone else to see going across a network that is not entirely in your control.

OwnerDisplayName: anon

LastEditorDisplayName: anon

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
"This field is required" when field is populated on Django modelForm
After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:

forms.py:

```<code>class UploadFileForm(forms.ModelForm):

    class Meta:
        model = Job
        fields = ['jobID',
            'original_file']
        labels = {  'jobID': _('Job ID'),
                    'original_file': _('File'),}
        error_messages = {
            'jobID': {'max_length': _("Job ID is limited to 50 characters."),
            },
            NON_FIELD_ERRORS: {
                'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
            }
        }
</code>```

models.py:

```<code>from __future__ import unicode_literals

from django.db import models
from django.utils import timezone

class Job(models.Model):
    user = models.ForeignKey('auth.User')
    original_file = models.FileField()
    jobID = models.CharField(max_length=50)
    rev = models.IntegerField()
    create_date = models.DateTimeField(default = timezone.now)

    def save(self):
        "Get last value of rev considering jobID and User and increment"
        "see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
        last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
        if last_rev:
            rev = last_rev[0].rev + 1
        else:
            rev = 1
        super(Job,self).save()

    def __unicode__(self):
        return self.jobID + " rev " + str(self.rev)

    class Meta:
        indexes = [
            models.Index(fields=['user','jobID']),
        ]
        unique_together = ("user","jobID","rev")
        ordering = ['-create_date']
</code>```

views.py

```<code>from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job

# Create your views here.
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request,'precheck/prestage.html')
    else:
            form = UploadFileForm()
    return render(request, 'precheck/upload.html',{'form': form})

def success(request):
    return render(request, 'precheck/prestage.html')
</code>```

upload.html

```<code>{% extends 'base.html' %}

{% block content %}

<h2>Upload File</h2>

{% if error %}
{{ error }}
<br />
<br />
{% endif %}

<form method = "POST" action="{% url 'precheck:upload' %}">
    {% csrf_token %}

    {{ form.as_p }}

    <br />
    <input type="submit" class="btn btn-primary" value="Upload">

</form>

{% endblock %}
</code>```

I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.

EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:

```<code><form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">
</code>```

答: The error is not for jobID, but for original_file. This is because you are not using the enctype="multipart/form-data" attribute on the form element.

Body:
After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:

forms.py:

class UploadFileForm(forms.ModelForm):

    class Meta:
        model = Job
        fields = ['jobID',
            'original_file']
        labels = {  'jobID': _('Job ID'),
                    'original_file': _('File'),}
        error_messages = {
            'jobID': {'max_length': _("Job ID is limited to 50 characters."),
            },
            NON_FIELD_ERRORS: {
                'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
            }
        }

models.py:

from __future__ import unicode_literals

from django.db import models
from django.utils import timezone

class Job(models.Model):
    user = models.ForeignKey('auth.User')
    original_file = models.FileField()
    jobID = models.CharField(max_length=50)
    rev = models.IntegerField()
    create_date = models.DateTimeField(default = timezone.now)

    def save(self):
        "Get last value of rev considering jobID and User and increment"
        "see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
        last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
        if last_rev:
            rev = last_rev[0].rev + 1
        else:
            rev = 1
        super(Job,self).save()

    def __unicode__(self):
        return self.jobID + " rev " + str(self.rev)

    class Meta:
        indexes = [
            models.Index(fields=['user','jobID']),
        ]
        unique_together = ("user","jobID","rev")
        ordering = ['-create_date']

views.py

from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job

# Create your views here.
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render(request,'precheck/prestage.html')
    else:
            form = UploadFileForm()
    return render(request, 'precheck/upload.html',{'form': form})

def success(request):
    return render(request, 'precheck/prestage.html')

upload.html

{% extends 'base.html' %}

{% block content %}

Upload File

{% if error %}
{{ error }}

{% endif %}

<form method = "POST" action="{% url 'precheck:upload' %}">
    {% csrf_token %}

    {{ form.as_p }}

    <input type="submit" class="btn btn-primary" value="Upload">

</form>

{% endblock %}

I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.

EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:

<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">


问:
Why does Visual Studio 2012 prevent saving aspx pages that have not been validated?
My company recently migrated to Visual Studio 2012 and I am using it to develop web application using ASPX pages. The pages are split with the C# in a code-behind file. After using 2012 for a couple weeks now, I noticed something: if my ASPX page does not correctly validate to the HTML5 standard (i.e. I am missing a closing tag somewhere), the page will not save. This problem does not occur in the code-behind file, nor does it occur on Razor pages.

I briefly looked through the standard Visual Studio settings pages, but cannot find a setting to allow invalid code to be saved. I also have Resharper installed (as well as the Productivity Power Tools), but cannot find a setting in either of those extensions that seem to relate to my issue. If it matters, the project I am working on is part of a TFS solution.

Has anyone else experienced this issue? If so, does anyone know of a setting that might have caused this that I may be overlooking?

Update: Since posting this, I have noticed that I am unable to save even after the page has been validated. It can take up to a minute before Visual Studio allows me to save the page. The length of time may be related to the amount of text that I entered before trying to save.

Update 2: After talking to a coworker who has a similar set of extensions, I determined that Resharper must be causing the problem. If anyone knows of a Resharper 7 setting that may be causing this, please let me know. I can't tell if this is a bug or an intended feature.

Final Update: Thank you to all who offered assistance, but after installing the Visual Studio Update 1, I no longer notice the problem. It seems to have been a bug that was fixed with the update.

答:
Grrr, still happening in 2015, and I don't even have ReSharper or Productivity Power Tools installed.  I found a workaround.  I quit VS, said YES to saving the items in the popup, reopened it, and found that they were saved to older statuses.  I re-changed the code, saved (took many seconds but probably less than a minute), and recompiled, and the changes took this time.

It was nice that when I quit and saved (unsuccessfully), it at least showed that the code was in an older state, instead of showing the newer code with a perpetual asterisk.

I'd never seen this before, and hope never to again.


问:
Accesing $this outside foreach loop Jquery
```<code>jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var elements = {};
    var max;
    jQuery(variable).find('.form-checkboxes .form-type-checkbox label.option').each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;
        elements = this;
    });

    elements.parent('div').siblings().css('height',temp);
}
</code>```

I am using this code, but the value of 'elements' become empty outside the loop. but inside it's working.

Help me out !

答:
No need to re-wrap variable as it's already a jQuery object.

Your elements is a regular object, rather than a collection of jQuery elements. If you want this to store a list of jQuery elements, simply declare it as a variable and set it to a selector.

You're doing console.log(height), but your function heightAdjustment() doesn't return anything. I've added return temp; so that the function returns the height to which the affected elements were set.

```<code>var elements;

jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var max;
    elements = variable.find('.form-checkboxes .form-type-checkbox label.option');
    elements.each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;
    });

    elements.parent('div').siblings().css('height',temp);
    return temp;
}
</code>```

Body:
jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var elements = {};
    var max;
    jQuery(variable).find('.form-checkboxes .form-type-checkbox label.option').each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;
        elements = this;
    });

    elements.parent('div').siblings().css('height',temp);
}

I am using this code, but the value of 'elements' become empty outside the loop. but inside it's working.

Help me out !

Body:
No need to re-wrap variable as it's already a jQuery object.

Your elements is a regular object, rather than a collection of jQuery elements. If you want this to store a list of jQuery elements, simply declare it as a variable and set it to a selector.

You're doing console.log(height), but your function heightAdjustment() doesn't return anything. I've added return temp; so that the function returns the height to which the affected elements were set.

var elements;

jQuery('.webform-component-checkboxes').each(function(){
    var height = heightAdjustment(jQuery(this));
    console.log(height);
});

function heightAdjustment(variable){
    var temp = 0;
    var max;
    elements = variable.find('.form-checkboxes .form-type-checkbox label.option');
    elements.each(function() {
        max = jQuery(this).parent().css('height');
        temp = temp > max ? temp : max ;
    });

    elements.parent('div').siblings().css('height',temp);
    return temp;
}


问:
Optimizing on R a code for a matrix which get the row/col names from a file and data values for other
Ok, so first I need to say sorry if I'm not very clear with the explanation because english is not my native language

For my studies I had to write a code to arrange the data from a txt file, a BLAST clustering output to be precise. The data was a file with:

```<code>##Gen_name_1; Gen_name_2; Identity_Percentage
</code>```

Since the matches were for several genes, I had a Clustering_Output.txt file with ~89.000.000 rows with 3 columns. From there I did a file with just the genes names, called "Clean_names.txt", which had all the names without repeating them,in a file with ~94.000 gene names and 1 column.

As requested, the head of the data looks something like:
(used these random names I found because I have no access to the original file)

```<code>> head(gene_data)
       V1       V2      V3
1 EDGARDO  EDGARDO 100.000
2 EDGARDO    EDITH  96.482
3 EDGARDO  EDUARDO  97.911
4 EDGARDO EFR\x90N  99.040
5 EDGARDO    ELENA  95.690
6 EDGARDO    ELIAS  95.340

> head(list)
        V1
1  EDGARDO
2    EDITH
3  EDMUNDO
4  EDUARDO
5   EFRAIN
6 EFR\x90N

> head(name_list)
[1] "EDGARDO"  "EDITH"    "EDMUNDO"  "EDUARDO"  "EFRAIN"   "EFR\x90N"
</code>```

I needed to create a matrix to send all this data to another program, and the prerequisites of that program are:

A square matrix,

Numbers are percentages from 0 to 1,

Only the diagonal can have "1"'s,

If there is no match, a "0" must be placed

It does not have row/col names

So, after hitting my head against a wall for a time, I did it on R, because I don't know much R .... but I know less of other computing language, and came out with this code.

I don't know if there is another way to do this, and searched on the internet to something similar, but found nothing this specific

```<code>    ##Read Files##

    gene_data = read.table("Clustering_Output.txt", header = F, sep=";",dec=",",stringsAsFactors=FALSE)
    list = read.table("Clean_names.txt", header=F,stringsAsFactors=FALSE)
    name_list=as.character(list$V1)
    percentages=gene_data$V3
    print('File Load Ready')

    ##Get the lengths to create matrix##

    n=length(list$V1)
    t=length(gene_data$V1)
    print('Length vectors Ready')

    ##Create matrix##

    m=matrix(0, nrow=n, ncol=n)
    print('Matrix Created')

    ##Set matrix row/col names##

    colnames(m)=name_list[]
    rownames(m)=name_list[]
    print('Row/Col Names Assigned')

    ##Replace one by one the Identity from data into the matrix##

    for (i in 1:t){
      ##Read first data column##

      query=as.character(gene_data[i,1])
      ##Read second data column##

      hit=as.character(gene_data[i,2])

      ##Get identity percentage##
      identity=percentages[i]

      ##To just get 1's on the diagonal##
      if(isTRUE(query!=hit) && identity==100){
        identity=99.99
      }

      ##Search row/column on the matrix##
      find_row=as.integer(match(hit, name_list))
      find_col=as.integer(match(query, name_list))

      ##Replace value##
      m[find_row,find_col]=(identity/100)

      ##Release some memory.... or something like that I read##
      gc()
    }

    print('Replacement Ready')
    ##Save to a file##

    from_count=1
    to_count=1
    for(w in 1:n){
      to_count=from_count+1

    ##If n is not pair the save won't work, so I added an NA lines which can be easily deleted after##

        if(to_count>(n-1)){
          m=rbind(m,NA)
          write.table(m[from_count:to_count,], "Test2.txt", append=TRUE, col.names=FALSE, row.names=FALSE, dec=",")
          break
        }

      ##Create the file and save 2 rows at a time##
      ##I don't know why saving 1 row saved it as a column, but 2 or more at a time worked fine##

      write.table(m[from_count:to_count,], "Test2.txt", append=TRUE, col.names=FALSE, row.names=FALSE, dec=",")
      from_count=to_count+1
    }

    print ('Done :3')
</code>```

The matrix I get looks like this

Ending matrix

The codes works fine on a small matrix but takes a lot of time in a big one like the one I have now. (used the 'bigmemory' package at first, but I could run the code without it, so removed that part)

My problem, and hence, the question is, I don't know any other way to handle a ~94.000 x 94.000 matrix without crashing the server we have here, but I don't know how long it will take, tested the code in a 11x11 matrix and took about 3 seconds, so a matrix that big will take .... I don't know, years? ...And yes, I forgot to put a counter inside the replacement part, so I don't know how long we'll have to wait, or how far the code has reached.
So now I'm trying to get a better version of this code in case I have to shut it down, but since my computing language is very limited I'd like ask for some help here.

Is there a way to improve this script? Maybe you can see something I'm missing, or you just know some more than I do.

Sorry if this is asked on another post, but searched the site and couldn't find it, and because I based my code on a lot of info I got from here I believe that here are the people that can improve it.

答:
Like I said, it's tough without a small working test sample, but here's a try.

Generate some example data:

```<code>library(data.table)
library(gtools)

#Generate some test data
name_list <- c("EDGARDO", "EDITH", "EDMUNDO",
               "EDUARDO", "EFRAIN", "EFR\x90N")
dat <- data.table(permutations(length(name_list),
                               2,
                               name_list,
                               repeats.allowed = TRUE))
dat[, V3 := runif(dim(dat)[1], 0, 1)]
dat[V1 == V2, V3 := 1]

# Now, like your example, lets add a gene that doesn't have values against other genes
dat <- rbind(dat, data.table(V1 = "NEWGENE", V2 = "NEWGENE", V3 = 1))
dat
</code>```

Results in dataset:

```<code>         V1      V2         V3
 1: EDGARDO EDGARDO 1.00000000
 2: EDGARDO   EDITH 0.52602966
 3: EDGARDO EDMUNDO 0.22507335
 4: EDGARDO EDUARDO 0.48641176
 5: EDGARDO   EFRN 0.37021480
 6: EDGARDO  EFRAIN 0.98335018
 7:   EDITH EDGARDO 0.38831912
 8:   EDITH   EDITH 1.00000000
 9:   EDITH EDMUNDO 0.62329755
10:   EDITH EDUARDO 0.13654020
11:   EDITH   EFRN 0.96746949
12:   EDITH  EFRAIN 0.51507181
13: EDMUNDO EDGARDO 0.16307033
14: EDMUNDO   EDITH 0.62190230
15: EDMUNDO EDMUNDO 1.00000000
16: EDMUNDO EDUARDO 0.66877152
17: EDMUNDO   EFRN 0.41891590
18: EDMUNDO  EFRAIN 0.32334499
19: EDUARDO EDGARDO 0.83525532
20: EDUARDO   EDITH 0.14381704
21: EDUARDO EDMUNDO 0.19281595
22: EDUARDO EDUARDO 1.00000000
23: EDUARDO   EFRN 0.30811955
24: EDUARDO  EFRAIN 0.36330054
25:   EFRN EDGARDO 0.78394648
26:   EFRN   EDITH 0.19337868
27:   EFRN EDMUNDO 0.01776581
28:   EFRN EDUARDO 0.40660787
29:   EFRN   EFRN 1.00000000
30:   EFRN  EFRAIN 0.42184495
31:  EFRAIN EDGARDO 0.34280880
32:  EFRAIN   EDITH 0.86648331
33:  EFRAIN EDMUNDO 0.45510805
34:  EFRAIN EDUARDO 0.53376487
35:  EFRAIN   EFRN 0.96384333
36:  EFRAIN  EFRAIN 1.00000000
37: NEWGENE NEWGENE 1.00000000
</code>```

You can then make this a wide table using dcast.

dat2 <- dcast(dat, V1 ~ V2, value.var = "V3", drop = FALSE, fill = 0)

```<code>        V1   EDGARDO     EDITH    EDMUNDO   EDUARDO    EFRAIN     EFRN NEWGENE
1: EDGARDO 1.0000000 0.5260297 0.22507335 0.4864118 0.9833502 0.3702148       0
2:   EDITH 0.3883191 1.0000000 0.62329755 0.1365402 0.5150718 0.9674695       0
3: EDMUNDO 0.1630703 0.6219023 1.00000000 0.6687715 0.3233450 0.4189159       0
4: EDUARDO 0.8352553 0.1438170 0.19281595 1.0000000 0.3633005 0.3081196       0
5:  EFRAIN 0.3428088 0.8664833 0.45510805 0.5337649 1.0000000 0.9638433       0
6:   EFRN 0.7839465 0.1933787 0.01776581 0.4066079 0.4218450 1.0000000       0
7: NEWGENE 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000       1
</code>```

This is likely much faster than building the matrix by hand. If you need it in matrix format:

as.matrix(dat2[, !"V1"])

```<code>       EDGARDO     EDITH    EDMUNDO   EDUARDO    EFRAIN     EFRN NEWGENE
[1,] 1.0000000 0.5260297 0.22507335 0.4864118 0.9833502 0.3702148       0
[2,] 0.3883191 1.0000000 0.62329755 0.1365402 0.5150718 0.9674695       0
[3,] 0.1630703 0.6219023 1.00000000 0.6687715 0.3233450 0.4189159       0
[4,] 0.8352553 0.1438170 0.19281595 1.0000000 0.3633005 0.3081196       0
[5,] 0.3428088 0.8664833 0.45510805 0.5337649 1.0000000 0.9638433       0
[6,] 0.7839465 0.1933787 0.01776581 0.4066079 0.4218450 1.0000000       0
[7,] 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000       1
</code>```

You can write dat2 to file:

```<code>write.table(dat2,
            file = "dat.csv",
            sep = ",",
            quote = FALSE,
            row.names = FALSE)
</code>```

Or, if you're going to use it in R, saveRDS(dat2, "dat2.rds").

Body:
Ok, so first I need to say sorry if I'm not very clear with the explanation because english is not my native language

For my studies I had to write a code to arrange the data from a txt file, a BLAST clustering output to be precise. The data was a file with:

##Gen_name_1; Gen_name_2; Identity_Percentage

Since the matches were for several genes, I had a Clustering_Output.txt file with ~89.000.000 rows with 3 columns. From there I did a file with just the genes names, called "Clean_names.txt", which had all the names without repeating them,in a file with ~94.000 gene names and 1 column.

As requested, the head of the data looks something like:
(used these random names I found because I have no access to the original file)

> head(gene_data)
       V1       V2      V3
1 EDGARDO  EDGARDO 100.000
2 EDGARDO    EDITH  96.482
3 EDGARDO  EDUARDO  97.911
4 EDGARDO EFR\x90N  99.040
5 EDGARDO    ELENA  95.690
6 EDGARDO    ELIAS  95.340

> head(list)
        V1
1  EDGARDO
2    EDITH
3  EDMUNDO
4  EDUARDO
5   EFRAIN
6 EFR\x90N

> head(name_list)
[1] "EDGARDO"  "EDITH"    "EDMUNDO"  "EDUARDO"  "EFRAIN"   "EFR\x90N"

I needed to create a matrix to send all this data to another program, and the prerequisites of that program are:

A square matrix,

Numbers are percentages from 0 to 1,

Only the diagonal can have "1"'s,

If there is no match, a "0" must be placed

It does not have row/col names

So, after hitting my head against a wall for a time, I did it on R, because I don't know much R .... but I know less of other computing language, and came out with this code.

I don't know if there is another way to do this, and searched on the internet to something similar, but found nothing this specific

    ##Read Files##

    gene_data = read.table("Clustering_Output.txt", header = F, sep=";",dec=",",stringsAsFactors=FALSE)
    list = read.table("Clean_names.txt", header=F,stringsAsFactors=FALSE)
    name_list=as.character(list$V1)
    percentages=gene_data$V3
    print('File Load Ready')

    ##Get the lengths to create matrix##

    n=length(list$V1)
    t=length(gene_data$V1)
    print('Length vectors Ready')

    ##Create matrix##

    m=matrix(0, nrow=n, ncol=n)
    print('Matrix Created')

    ##Set matrix row/col names##

    colnames(m)=name_list[]
    rownames(m)=name_list[]
    print('Row/Col Names Assigned')

    ##Replace one by one the Identity from data into the matrix##

    for (i in 1:t){
      ##Read first data column##

      query=as.character(gene_data[i,1])
      ##Read second data column##

      hit=as.character(gene_data[i,2])

      ##Get identity percentage##
      identity=percentages[i]

      ##To just get 1's on the diagonal##
      if(isTRUE(query!=hit) && identity==100){
        identity=99.99
      }

      ##Search row/column on the matrix##
      find_row=as.integer(match(hit, name_list))
      find_col=as.integer(match(query, name_list))

      ##Replace value##
      m[find_row,find_col]=(identity/100)

      ##Release some memory.... or something like that I read##
      gc()
    }

    print('Replacement Ready')
    ##Save to a file##

    from_count=1
    to_count=1
    for(w in 1:n){
      to_count=from_count+1

    ##If n is not pair the save won't work, so I added an NA lines which can be easily deleted after##

        if(to_count>(n-1)){
          m=rbind(m,NA)
          write.table(m[from_count:to_count,], "Test2.txt", append=TRUE, col.names=FALSE, row.names=FALSE, dec=",")
          break
        }

      ##Create the file and save 2 rows at a time##
      ##I don't know why saving 1 row saved it as a column, but 2 or more at a time worked fine##

      write.table(m[from_count:to_count,], "Test2.txt", append=TRUE, col.names=FALSE, row.names=FALSE, dec=",")
      from_count=to_count+1
    }

    print ('Done :3')

The matrix I get looks like this

Ending matrix

The codes works fine on a small matrix but takes a lot of time in a big one like the one I have now. (used the 'bigmemory' package at first, but I could run the code without it, so removed that part)

My problem, and hence, the question is, I don't know any other way to handle a ~94.000 x 94.000 matrix without crashing the server we have here, but I don't know how long it will take, tested the code in a 11x11 matrix and took about 3 seconds, so a matrix that big will take .... I don't know, years? ...And yes, I forgot to put a counter inside the replacement part, so I don't know how long we'll have to wait, or how far the code has reached.
So now I'm trying to get a better version of this code in case I have to shut it down, but since my computing language is very limited I'd like ask for some help here.

Is there a way to improve this script? Maybe you can see something I'm missing, or you just know some more than I do.

Sorry if this is asked on another post, but searched the site and couldn't find it, and because I based my code on a lot of info I got from here I believe that here are the people that can improve it.

Body:
Like I said, it's tough without a small working test sample, but here's a try.

Generate some example data:

library(data.table)
library(gtools)

#Generate some test data
name_list <- c("EDGARDO", "EDITH", "EDMUNDO",
               "EDUARDO", "EFRAIN", "EFR\x90N")
dat <- data.table(permutations(length(name_list),
                               2,
                               name_list,
                               repeats.allowed = TRUE))
dat[, V3 := runif(dim(dat)[1], 0, 1)]
dat[V1 == V2, V3 := 1]

# Now, like your example, lets add a gene that doesn't have values against other genes
dat <- rbind(dat, data.table(V1 = "NEWGENE", V2 = "NEWGENE", V3 = 1))
dat

Results in dataset:

         V1      V2         V3
 1: EDGARDO EDGARDO 1.00000000
 2: EDGARDO   EDITH 0.52602966
 3: EDGARDO EDMUNDO 0.22507335
 4: EDGARDO EDUARDO 0.48641176
 5: EDGARDO   EFRN 0.37021480
 6: EDGARDO  EFRAIN 0.98335018
 7:   EDITH EDGARDO 0.38831912
 8:   EDITH   EDITH 1.00000000
 9:   EDITH EDMUNDO 0.62329755
10:   EDITH EDUARDO 0.13654020
11:   EDITH   EFRN 0.96746949
12:   EDITH  EFRAIN 0.51507181
13: EDMUNDO EDGARDO 0.16307033
14: EDMUNDO   EDITH 0.62190230
15: EDMUNDO EDMUNDO 1.00000000
16: EDMUNDO EDUARDO 0.66877152
17: EDMUNDO   EFRN 0.41891590
18: EDMUNDO  EFRAIN 0.32334499
19: EDUARDO EDGARDO 0.83525532
20: EDUARDO   EDITH 0.14381704
21: EDUARDO EDMUNDO 0.19281595
22: EDUARDO EDUARDO 1.00000000
23: EDUARDO   EFRN 0.30811955
24: EDUARDO  EFRAIN 0.36330054
25:   EFRN EDGARDO 0.78394648
26:   EFRN   EDITH 0.19337868
27:   EFRN EDMUNDO 0.01776581
28:   EFRN EDUARDO 0.40660787
29:   EFRN   EFRN 1.00000000
30:   EFRN  EFRAIN 0.42184495
31:  EFRAIN EDGARDO 0.34280880
32:  EFRAIN   EDITH 0.86648331
33:  EFRAIN EDMUNDO 0.45510805
34:  EFRAIN EDUARDO 0.53376487
35:  EFRAIN   EFRN 0.96384333
36:  EFRAIN  EFRAIN 1.00000000
37: NEWGENE NEWGENE 1.00000000

You can then make this a wide table using dcast.

dat2 <- dcast(dat, V1 ~ V2, value.var = "V3", drop = FALSE, fill = 0)

        V1   EDGARDO     EDITH    EDMUNDO   EDUARDO    EFRAIN     EFRN NEWGENE
1: EDGARDO 1.0000000 0.5260297 0.22507335 0.4864118 0.9833502 0.3702148       0
2:   EDITH 0.3883191 1.0000000 0.62329755 0.1365402 0.5150718 0.9674695       0
3: EDMUNDO 0.1630703 0.6219023 1.00000000 0.6687715 0.3233450 0.4189159       0
4: EDUARDO 0.8352553 0.1438170 0.19281595 1.0000000 0.3633005 0.3081196       0
5:  EFRAIN 0.3428088 0.8664833 0.45510805 0.5337649 1.0000000 0.9638433       0
6:   EFRN 0.7839465 0.1933787 0.01776581 0.4066079 0.4218450 1.0000000       0
7: NEWGENE 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000       1

This is likely much faster than building the matrix by hand. If you need it in matrix format:

as.matrix(dat2[, !"V1"])

       EDGARDO     EDITH    EDMUNDO   EDUARDO    EFRAIN     EFRN NEWGENE
[1,] 1.0000000 0.5260297 0.22507335 0.4864118 0.9833502 0.3702148       0
[2,] 0.3883191 1.0000000 0.62329755 0.1365402 0.5150718 0.9674695       0
[3,] 0.1630703 0.6219023 1.00000000 0.6687715 0.3233450 0.4189159       0
[4,] 0.8352553 0.1438170 0.19281595 1.0000000 0.3633005 0.3081196       0
[5,] 0.3428088 0.8664833 0.45510805 0.5337649 1.0000000 0.9638433       0
[6,] 0.7839465 0.1933787 0.01776581 0.4066079 0.4218450 1.0000000       0
[7,] 0.0000000 0.0000000 0.00000000 0.0000000 0.0000000 0.0000000       1

You can write dat2 to file:

write.table(dat2,
            file = "dat.csv",
            sep = ",",
            quote = FALSE,
            row.names = FALSE)

Or, if you're going to use it in R, saveRDS(dat2, "dat2.rds").


问:
When/How is a BLE GATT Notify/Indicate is send on physical layer
I read the bluetooth core spec. V4.2 /BLE (..)

The communication in connection state is always  master initiated, slave returns data afterwards.
The master here is a GATT client talking to GATT server (peripheral device).

I do not understand the GATT Feature "notify" respectively how it works via the lower layers when the master always has to request before sending data.

Someone knows how it works ?

答:
BLE is timeslotted. In connected state, there are connection events that happen periodically, with an interval called connectionInterval.

Each connection event is master initiated, which means the master sends the first packet within the connection event.

In order to keep the connection alive, slave has to send a packet (and get it acknowledged) at least once every supervisionTimeout. There are other timeouts that make the slave respond before that anyway, one of which is the slaveLatency, i.e. the number of connection events a slave can ignore before having to respond to master (even if not responding is not a cause for disconnection, it can cause other problems in the protocol, and thus disconnections). On the other hand, master should send a packet on each connection event.

connectionInterval, slaveLatency and supervisionTimeout are the timing part of the connection parameters in the spec.  Connection interval ranges from 7.5 ms to 4 seconds, slaveLatency from 0 (then slave should respond on every connection event) to the number of connection events corresponding to supervisionTimeout / 2. (See 6.B.4.5.1 for the full definition)

So, basically, any payload (including GATT notifications) is queued in the slave or master's stack buffers until the next connection event happens. Whatever the direction (slave to master or master to slave), party has to wait for the next connection event to sends its packets.

Inside a given connection event, each party sends a packet in turn, optionally without any useful payload, until nobody has nothing to send any more. (See 6.B.4.5.6)

That means a notification is queued at most for connectionInterval, if radio gets the packet transmitted on the first try.

That's why connection parameters have to be negotiated properly, and that's also why they are different depending on the device type. For instance, a HID (mouse, keyboard, remote control) is generally allowed to connect with a connection interval under 10 ms, while heart rate monitor usually gets a connection interval over a second.


问:
Swift debugging on Linux - Missing Backtrace
I have a crash which I am trying to locate, and even building the application as debug and executing it I don't seem to get any symbolic information.

The output I receive at the console is:

```<code>fatal error: unexpectedly found nil while unwrapping an Optional value
Current stack trace:
0    libswiftCore.so                    0x00007f1c51ca51c0 swift_reportError + 120
1    libswiftCore.so                    0x00007f1c51cbfbe0 _swift_stdlib_reportFatalError + 62
2    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
3    libswiftCore.so                    0x00007f1c51c18ead <unavailable> + 2625197
4    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
5    libswiftCore.so                    0x00007f1c51bd4060 specialized _fatalErrorMessage(StaticString, StaticString, file : StaticString, line : UInt, flags : UInt32) -> Never + 96
6    myProgram                          0x000000000045909e <unavailable> + 364702
7    myProgram                          0x0000000000423f37 <unavailable> + 147255
8    libdispatch.so                     0x00007f1c5276e177 <unavailable> + 278903
9    libdispatch.so                     0x00007f1c52779edd <unavailable> + 327389
10   libdispatch.so                     0x00007f1c5277a890 <unavailable> + 329872
11   libdispatch.so                     0x00007f1c5277c5f4 <unavailable> + 337396
12   libdispatch.so                     0x00007f1c5279aa18 <unavailable> + 461336
13   libpthread.so.0                    0x00007f1c50c6f6ba <unavailable> + 30394
14   libc.so.6                          0x00007f1c4f7b9370 clone + 109
Illegal instruction (core dumped)
</code>```

I simply cannot find any way to expand on this information, and although I could go looking through a map file.  I feel that we have moved very much beyond that territory now with modern tooling.

Does anyone have any pointers, or indeed knows how to produce a build with more information in it.

Ubuntu 16.04, Swift 3.1.1

答:
So, sadly this seems to be a bug in lldb, which uses local symbols in ELF executables, and dladdr cannot find them on linux platforms.

See the bug report here:
https://bugs.swift.org/browse/SR-755

ATTENTION:

Great news though, there is a bash script which does all the work for you.  Instruction's are slight, but this is what you need to do:

Download this script:
https://raw.githubusercontent.com/apple/swift/master/utils/symbolicate-linux-fatal

Exectute your crashing app.

```<code>$ myApp &> crash.log
</code>```

Then execute the script.

```<code>$ ./symbolicate-linux-fatal myApp crash.log
</code>```

It has helped me out no end.

Using LLDB

You can also use the swift debugger to help if still in the development stage.

Also if you execute lldb yourexecutable, then run.  You will pause and able to fully debug your application.

Body:
I have a crash which I am trying to locate, and even building the application as debug and executing it I don't seem to get any symbolic information.

The output I receive at the console is:

fatal error: unexpectedly found nil while unwrapping an Optional value
Current stack trace:
0    libswiftCore.so                    0x00007f1c51ca51c0 swift_reportError + 120
1    libswiftCore.so                    0x00007f1c51cbfbe0 _swift_stdlib_reportFatalError + 62
2    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
3    libswiftCore.so                    0x00007f1c51c18ead <unavailable> + 2625197
4    libswiftCore.so                    0x00007f1c51ab9be6 <unavailable> + 1186790
5    libswiftCore.so                    0x00007f1c51bd4060 specialized _fatalErrorMessage(StaticString, StaticString, file : StaticString, line : UInt, flags : UInt32) -> Never + 96
6    myProgram                          0x000000000045909e <unavailable> + 364702
7    myProgram                          0x0000000000423f37 <unavailable> + 147255
8    libdispatch.so                     0x00007f1c5276e177 <unavailable> + 278903
9    libdispatch.so                     0x00007f1c52779edd <unavailable> + 327389
10   libdispatch.so                     0x00007f1c5277a890 <unavailable> + 329872
11   libdispatch.so                     0x00007f1c5277c5f4 <unavailable> + 337396
12   libdispatch.so                     0x00007f1c5279aa18 <unavailable> + 461336
13   libpthread.so.0                    0x00007f1c50c6f6ba <unavailable> + 30394
14   libc.so.6                          0x00007f1c4f7b9370 clone + 109
Illegal instruction (core dumped)

I simply cannot find any way to expand on this information, and although I could go looking through a map file.  I feel that we have moved very much beyond that territory now with modern tooling.

Does anyone have any pointers, or indeed knows how to produce a build with more information in it.

Ubuntu 16.04, Swift 3.1.1

Body:
So, sadly this seems to be a bug in lldb, which uses local symbols in ELF executables, and dladdr cannot find them on linux platforms.

See the bug report here:
https://bugs.swift.org/browse/SR-755

ATTENTION:

Great news though, there is a bash script which does all the work for you.  Instruction's are slight, but this is what you need to do:

Download this script:
https://raw.githubusercontent.com/apple/swift/master/utils/symbolicate-linux-fatal

Exectute your crashing app.

$ myApp &> crash.log

Then execute the script.

$ ./symbolicate-linux-fatal myApp crash.log

It has helped me out no end.

Using LLDB

You can also use the swift debugger to help if still in the development stage.

Also if you execute lldb yourexecutable, then run.  You will pause and able to fully debug your application.

ContentLicense: CC BY-SA 4.0


问:
slideshow with page number in js
I created simple slideshow. If yu want to change image, you have to click on arrows button on keyboard. I want to add description e.g. "1 item from 7" etc.

Here is my source:

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    changeImage();
  } else if (e.keyCode == '39') {
    changeImage();
  }

}

document.onkeydown = checkKey;

function sliderText (){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>
</head>
<div id="slideshow_section">
  <img id="images" src="assets/1.jpg" />
</div>

<body>

</body>
<script src="script12.js"></script>

</html></code>```

Can you give me some hints how can I do that?

Thank you,
Megi

答:
Heres another working code(were iam going to explain, how to set image descr.):

```<code>          var images = [
          "http://www.helloworld.com/uploads/slider/1.jpg",
          "http://www.helloworld.com/uploads/slider/2.jpg",
          "http://www.helloworld.com/uploads/slider/3.jpg"
          ];
          var num = 0;
        function next() {
          var slider = document.getElementById("slider");
          num++;
          if(num >= images.length) {
            num = 0;
          }
          slider.src = images[num];
          setDescription();//calling function
          }

        function prev() {
          var slider = document.getElementById("slider");
          num--;
          if(num < 0) {
            num = images.length-1;
          }
          slider.src = images[num];
              setDescription();
//calling function - this can be included to your changeImage() function without any errors.
        }
    //To set the image description, i use following function:

            function setDescription(){
          var descr = document.getElementById("Description");
             var selectedimageindex = num + 1;/*beause Arrays start counting at 0
*/
        descr.innerHTML= "image "+ selectedimageindex +" of " + images.length;

        }
</code>```

Referring to your code it would look like this(Run it! ;) ):
  I needed to chage some Parts, like the image resources.

var img_index = 0;
var imgs = [
  "http://www.sololearn.com/uploads/slider/1.jpg",
  "http://www.sololearn.com/uploads/slider/2.jpg",
  "http://www.sololearn.com/uploads/slider/3.jpg"
];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 3;
  img.src = imgs[img_index];
  sliderText();
}

//needed to remove keychange functions because its not working on stackoverflow

function sliderText (){
  var Description = document.getElementById("description");
  var imagenumber = img_index + 1; //Arrays start counting at 0.
  Description.innerHTML = "image "+ imagenumber + " of "+imgs.length;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>
</head>
<div id="slideshow_section">
  <img id="images" src="http://www.sololearn.com/uploads/slider/1.jpg" />
  <span id="description">Image 1 of 3</span>
  <button id="nextbtn" onclick="changeImage()">Next</button>
</div>

<body>

</body>

</html></code>```

Feedback to this answer?please! Hope it was helpful!

Good Luck!

Title: slideshow with page number in js

Body:
I created simple slideshow. If yu want to change image, you have to click on arrows button on keyboard. I want to add description e.g. "1 item from 7" etc.

Here is my source:

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    changeImage();
  } else if (e.keyCode == '39') {
    changeImage();
  }

}

document.onkeydown = checkKey;

function sliderText (){

}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>

Can you give me some hints how can I do that?

Thank you,
Megi

Body:
Heres another working code(were iam going to explain, how to set image descr.):

          var images = [
          "http://www.helloworld.com/uploads/slider/1.jpg",
          "http://www.helloworld.com/uploads/slider/2.jpg",
          "http://www.helloworld.com/uploads/slider/3.jpg"
          ];
          var num = 0;
        function next() {
          var slider = document.getElementById("slider");
          num++;
          if(num >= images.length) {
            num = 0;
          }
          slider.src = images[num];
          setDescription();//calling function
          }

        function prev() {
          var slider = document.getElementById("slider");
          num--;
          if(num < 0) {
            num = images.length-1;
          }
          slider.src = images[num];
              setDescription();
//calling function - this can be included to your changeImage() function without any errors.
        }
    //To set the image description, i use following function:

            function setDescription(){
          var descr = document.getElementById("Description");
             var selectedimageindex = num + 1;/*beause Arrays start counting at 0
*/
        descr.innerHTML= "image "+ selectedimageindex +" of " + images.length;

        }

Referring to your code it would look like this(Run it! ;) ):
  I needed to chage some Parts, like the image resources.

var img_index = 0;
var imgs = [
  "http://www.sololearn.com/uploads/slider/1.jpg",
  "http://www.sololearn.com/uploads/slider/2.jpg",
  "http://www.sololearn.com/uploads/slider/3.jpg"
];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 3;
  img.src = imgs[img_index];
  sliderText();
}

//needed to remove keychange functions because its not working on stackoverflow

function sliderText (){
  var Description = document.getElementById("description");
  var imagenumber = img_index + 1; //Arrays start counting at 0.
  Description.innerHTML = "image "+ imagenumber + " of "+imgs.length;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>
</head>
<div id="slideshow_section">
  <img id="images" src="http://www.sololearn.com/uploads/slider/1.jpg" />
  <span id="description">Image 1 of 3</span>
  <button id="nextbtn" onclick="changeImage()">Next</button>
</div>

<body>

</body>

</html>

Feedback to this answer?please! Hope it was helpful!

Good Luck!


问:
cygwin: vagrant ssh, empty command prompt
If I vagrant ssh with windows cmd, I get a nice command prompt, like that:

```<code>vagrant@homestead:~$ echo foo
vagrant@homestead:~$ foo
</code>```

But with cygwin and mintty, I have no prompt at all:

```<code>echo foo
foo
</code>```

I see it has to do with "pseudo-tty allocation".

With cygwin and mintty, I can have my prompt with this :

```<code>vagrant ssh -- -t -t
</code>```

How can I change cygwin and mintty so that I don't have to tell the -t ?

About the ssh -t option :

"Force pseudo-tty allocation.  This can be used to execute arbi-
             trary screen-based programs on a remote machine, which can be
             very useful, e.g., when implementing menu services.  Multiple -t
             options force tty allocation, even if ssh has no local tty."

答:
Vagrant is a windows program managing Virtual machine

https://www.vagrantup.com/intro/index.html

as such it does not well interface with the pseudo tty
structure used by cygwin programs.
Read for reference on similar issues with a lot of other windows program

https://github.com/mintty/mintty/issues/56

Mintty is a Cygwin program. It expect interactive program running inside it to use the cygwin tty functionality for interactive behaviour.
Running Vagrant from Bash in Windows CMD, make CMD the terminal control so Vagrant has no problem in the interactive behaviour.

I do not see the need to run Vagrant inside Cygwin

Body:
If I vagrant ssh with windows cmd, I get a nice command prompt, like that:

vagrant@homestead:~$ echo foo
vagrant@homestead:~$ foo

But with cygwin and mintty, I have no prompt at all:

echo foo
foo

I see it has to do with "pseudo-tty allocation".

With cygwin and mintty, I can have my prompt with this :

vagrant ssh -- -t -t

How can I change cygwin and mintty so that I don't have to tell the -t ?

About the ssh -t option :

"Force pseudo-tty allocation.  This can be used to execute arbi-
             trary screen-based programs on a remote machine, which can be
             very useful, e.g., when implementing menu services.  Multiple -t
             options force tty allocation, even if ssh has no local tty."


问:
Is the code valid. If i want to display first element? if not then what will s.begin() return?
I am trying to display first element inserted into a vector.Can i use the begin() to access it?</p>

```<code> vector<int>s;
 s.push_back(5);
 cout<<s.begin();
</code>```

答:
In C++, the begin() member function returns a pointer (or iterator) to the front (a lot of the time, anyways).

You can access the first element with begin(), but you have to dereference it (like a pointer) first:

```<code>cout << *s.begin(); // 5
</code>```

Here is a demo: https://repl.it/JQiU/0

Body:
I am trying to display first element inserted into a vector.Can i use the begin() to access it?

 vector<int>s;
 s.push_back(5);
 cout<<s.begin();

Body:
In C++, the begin() member function returns a pointer (or iterator) to the front (a lot of the time, anyways).

You can access the first element with begin(), but you have to dereference it (like a pointer) first:

cout << *s.begin(); // 5

Here is a demo: https://repl.it/JQiU/0


问:
React native function return nothing
I'm trying to do something simple here - connect to a sqlite database and return the number of records.  In the code below I can output the len variable with console.log, but nothing gets returned.  Am I missing something obvious?  Thanks.</p>

```<code>const db = SQLite.openDatabase({ name: 'favorites.db' });
export default class PlayerScreen extends React.Component {

   fetch(){
      console.log('fetching data from database');
       var query = "SELECT * FROM items";
       var params = [];
         db.transaction((tx) => {
            tx.executeSql(query,params, (tx, results) => {
            var len = results.rows.length;
            return len;

          }, function(){
            console.log('Profile: Something went wrong');
          });
      });

}

render() {

   return  <Text>{this.fetch()}</Text>

}
 }
</code>```

答:
A lot of things are wrong here. Fetch is an asynchronous concept and React rendering is synchronous. You cannot use fetch or anything asynchronously inside the render method.

So, what should you do instead?

First, do the fetch in the componentDidMount of the component.
Also set an initial state in componentWillMount

```<code>componentWillMount() {
  this.state = { length: 0 };
}

componentDidMount() {
  // I use call here to make sure this.fetch gets the this context
  this.fetch.call(this);
}
</code>```

Secondly, attach the results to the innerState of the component in your fetch method

```<code>fetch() {
  var query = "SELECT * FROM items";
   var params = [];
     db.transaction((tx) => {
        tx.executeSql(query,params, (tx, results) => {
        var len = results.rows.length;

        // this.setState will trigger a re-render of the component
        this.setState({ length: len });

      }, function(){
        console.log('Profile: Something went wrong');
      });
  });
}
</code>```

Now, in the render method, you can use this.state.length to render the value.

```<code>render() {
  return  <Text>{this.state.length}</Text>
}
</code>```

Hope this helps you out

Title: React native function return nothing

Body:
I'm trying to do something simple here - connect to a sqlite database and return the number of records.  In the code below I can output the len variable with console.log, but nothing gets returned.  Am I missing something obvious?  Thanks.

const db = SQLite.openDatabase({ name: 'favorites.db' });
export default class PlayerScreen extends React.Component {

   fetch(){
      console.log('fetching data from database');
       var query = "SELECT * FROM items";
       var params = [];
         db.transaction((tx) => {
            tx.executeSql(query,params, (tx, results) => {
            var len = results.rows.length;
            return len;

          }, function(){
            console.log('Profile: Something went wrong');
          });
      });

}

render() {

   return  <Text>{this.fetch()}</Text>

}
 }

Body:
A lot of things are wrong here. Fetch is an asynchronous concept and React rendering is synchronous. You cannot use fetch or anything asynchronously inside the render method.

So, what should you do instead?

First, do the fetch in the componentDidMount of the component.
Also set an initial state in componentWillMount

componentWillMount() {
  this.state = { length: 0 };
}

componentDidMount() {
  // I use call here to make sure this.fetch gets the this context
  this.fetch.call(this);
}

Secondly, attach the results to the innerState of the component in your fetch method

fetch() {
  var query = "SELECT * FROM items";
   var params = [];
     db.transaction((tx) => {
        tx.executeSql(query,params, (tx, results) => {
        var len = results.rows.length;

        // this.setState will trigger a re-render of the component
        this.setState({ length: len });

      }, function(){
        console.log('Profile: Something went wrong');
      });
  });
}

Now, in the render method, you can use this.state.length to render the value.

render() {
  return  <Text>{this.state.length}</Text>
}

Hope this helps you out


问:
Saving data to a model with association hasMany does not work
I want to keep the information about posts to the user. Save turns. But at the output of the data on the posts no longer exists.

Why are not posts stored?

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/22mp

```<code>    Ext.define('Post', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'title',
            type: 'string'
        }]
    });

    Ext.define('User', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'name',
            type: 'string'
        }],

        hasMany: 'Post'
    });

    var user = Ext.create('User', {
        name: "user1"
    });

    user.posts().add({
        title: 'Post 10'
    });

    user.posts().sync();

    console.log(user.getData()); // There are no posts!
</code>```

答:
You have to use
user.getData({associated:true}); to get the associated data for more information please see the documentation.
https://docs.sencha.com/extjs/6.5.0/modern/Ext.data.Model.html#method-getData

Body:
I want to keep the information about posts to the user. Save turns. But at the output of the data on the posts no longer exists.

Why are not posts stored?

Fiddle: https://fiddle.sencha.com/#view/editor&fiddle/22mp

    Ext.define('Post', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'title',
            type: 'string'
        }]
    });

    Ext.define('User', {
        extend: 'Ext.data.Model',

        fields: [{
            name: 'name',
            type: 'string'
        }],

        hasMany: 'Post'
    });

    var user = Ext.create('User', {
        name: "user1"
    });

    user.posts().add({
        title: 'Post 10'
    });

    user.posts().sync();

    console.log(user.getData()); // There are no posts!


问:
Pass one queryset as parameter for exclude() in django
I have the following three models:

```<code>class Student(models.Model):
    name=models.CharField(max_length=10)

class Task(models.Model):
    name=models.CharField(max_length=10)

class StudentTask(models.Model):
     student=models.ForeignKey(Student)
     task=models.ForeignKey(Task)
</code>```

Now what I want is to show the list of tasks he is assigned to and the list of activities that he is not taking:

```<code>         my_tasks=StudentTask.objects.annotate(act_id=F('id'),act_name=F('task__name')).values('act_id','act_name').filter(student_id=id)

 tasks=Task.objects.exclude(id__in=my_tasks).values('id','name')
</code>```

Which gives the error "Cannot use multi-field values as a filter value.". I googled and realized annotate got something to do with the error (but i didnt yet try without it).

Is it even worth trying to use my_tasks given any given student cant have more than three tasks? The following query works fine:

```<code>  tasks=Task.objects.exclude(id__in=StudentTask.objects.filter(student_id=id).values('task_id')
</code>```

But it is querying the same thing twice. What is the proper way to do this, considering the first query will fail as it is?

答:
It seems that the problem is because in the first query, you are returning a dict which is populated by two attributes: act_id and act_name. And then you are using it in the exclude() filter in the second query. Try this:</p>

```<code>my_tasks=StudentTask.objects.annotate(act_id=F('id'),act_name=F('task__name')).values('act_id','act_name').filter(student_id=id)

my_task_ids = [d['act_id'] for d in my_tasks]

tasks=Task.objects.exclude(id__in=my_task_ids).values('id','name')
</code>```

Body:
I have the following three models:

class Student(models.Model):
    name=models.CharField(max_length=10)

class Task(models.Model):
    name=models.CharField(max_length=10)

class StudentTask(models.Model):
     student=models.ForeignKey(Student)
     task=models.ForeignKey(Task)

Now what I want is to show the list of tasks he is assigned to and the list of activities that he is not taking:

         my_tasks=StudentTask.objects.annotate(act_id=F('id'),act_name=F('task__name')).values('act_id','act_name').filter(student_id=id)

 tasks=Task.objects.exclude(id__in=my_tasks).values('id','name')

Which gives the error "Cannot use multi-field values as a filter value.". I googled and realized annotate got something to do with the error (but i didnt yet try without it).

Is it even worth trying to use my_tasks given any given student cant have more than three tasks? The following query works fine:

  tasks=Task.objects.exclude(id__in=StudentTask.objects.filter(student_id=id).values('task_id')

But it is querying the same thing twice. What is the proper way to do this, considering the first query will fail as it is?

Body:
It seems that the problem is because in the first query, you are returning a dict which is populated by two attributes: act_id and act_name. And then you are using it in the exclude() filter in the second query. Try this:

my_tasks=StudentTask.objects.annotate(act_id=F('id'),act_name=F('task__name')).values('act_id','act_name').filter(student_id=id)

my_task_ids = [d['act_id'] for d in my_tasks]

tasks=Task.objects.exclude(id__in=my_task_ids).values('id','name')


问:
How to put a tooltip on a user-defined function
In Excel 2007, how do I add a description and parameter hints to a user-defined function? When I start typing a function invocation for a built-in function, Excel shows a description and parameter list--a tooltip. I'd like to do the same for the functions I define.

Not just for the formula insert wizard, but in the formula box, so if I key "=myFun(", at the "(" the tooltip pops up just like it does for "=average("

There's no help in VBA Help, none on MSDN and none on any of the Excel and VBA dedicated forums I can find, so this is clearly a long shot.

答:
Also you can use, this Macro to assign Descriptions to arguments and the UDF:

```<code>Private Sub RegisterMyFunction()
Application.MacroOptions _
    Macro:="SampleFunction", _      '' Your UDF name
    Description:="calculates a result based on provided inputs", _
    Category:="My UDF Category", _  '' Or use numbers, a list in the link below
    ArgumentDescriptions:=Array( _  '' One by each argument
        "is the first argument.  tell the user what it does", _
        "is the second argument.  tell the user what it does")
End Sub
</code>```

Credits to Kendall and the original post here.
For the UDF Categories

Body:
Also you can use, this Macro to assign Descriptions to arguments and the UDF:

Private Sub RegisterMyFunction()
Application.MacroOptions _
    Macro:="SampleFunction", _      '' Your UDF name
    Description:="calculates a result based on provided inputs", _
    Category:="My UDF Category", _  '' Or use numbers, a list in the link below
    ArgumentDescriptions:=Array( _  '' One by each argument
        "is the first argument.  tell the user what it does", _
        "is the second argument.  tell the user what it does")
End Sub

Credits to Kendall and the original post here.
For the UDF Categories


问:
How to choose indexed assignment variable dynamically in SAS?
I am trying to build a custom transformation in SAS DI. This transformation will "act" on columns in an input data set, producing the desired output. For simplicity let's assume the transformation will use input_col1 to compute output_col1, input_col2 to compute output_col2, and so on up to some specified number of columns to act on (let's say 2).

In the Code Options section of the custom transformation users are able to specify (via prompts) the names of the columns to be acted on; for example, a user could specify that input_col1 should refer to the column named "order_datetime" in the input dataset, and either make a similar specification for input_col2 or else leave that prompt blank.

Here is the code I am using to generate the output for the custom transformation:

```<code>data cust_trans;
    set &_INPUT0;

    i=1;
    do while(i<3);
        call symputx('index',i);
        result = myfunc("&&input_col&index");
        output_col&index = result; /*what is proper syntax here?*/
        i = i+1;
    end;
run;
</code>```

Here myfunc refers to a custom function I made using proc fcmp which works fine.

The custom transformation works fine if I do not try to take into account the variable number of input columns to act on (i.e. if I use "&&input_col&i" instead of "&&input_col&index" and just use the column result on the output table).

However, I'm having two issues with trying to make the approach more dynamic:

I get the following warning on the line containing
result = myfunc("&&input_col&index"):

WARNING: Apparent symbolic reference INDEX not resolved.

I do not know how to have the assignment to the desired output column happen dynamically; i.e., depending on the iteration of the do loop I'd like to assign the output value to the corresponding output column.

I feel confident that the solution to this must be well known amongst experts, but I cannot find anything explaining how to do this.

Any help is greatly appreciated!

答:
You can't use macro variables that depend on data variables, in this manner.  Macro variables are resolved at compile time, not at run time.

So you either have to

```<code>%do i = 1 %to .. ;
</code>```

which is fine if you're in a macro (it won't work outside of an actual macro), or you need to use an array.

```<code>data cust_trans;
    set &_INPUT0;
    array in[2] &input_col1 &input_col2;  *or however you determine the input columns;
    array output_col[2]; *automatically names the results;
    do i = 1 to dim(in);
        result = myfunc(in[i]); *You quote the input - I cannot see what your function is doing, but it is probably wrong to do so;
        output_col[i] = result; /*what is proper syntax here?*/
    end;
run;
</code>```

That's the way you'd normally do that.  I don't know what myfunc does, and I also don't know why you quote "&&input_col&index." when you pass it to it, but that would be a strange way to operate unless you want the name of the input column as text (and don't want to know what data is in that variable).  If you do, then pass vname(in[i]) which passes the name of the variable as a character.

Body:
I am trying to build a custom transformation in SAS DI. This transformation will "act" on columns in an input data set, producing the desired output. For simplicity let's assume the transformation will use input_col1 to compute output_col1, input_col2 to compute output_col2, and so on up to some specified number of columns to act on (let's say 2).

In the Code Options section of the custom transformation users are able to specify (via prompts) the names of the columns to be acted on; for example, a user could specify that input_col1 should refer to the column named "order_datetime" in the input dataset, and either make a similar specification for input_col2 or else leave that prompt blank.

Here is the code I am using to generate the output for the custom transformation:

data cust_trans;
    set &_INPUT0;

    i=1;
    do while(i<3);
        call symputx('index',i);
        result = myfunc("&&input_col&index");
        output_col&index = result; /*what is proper syntax here?*/
        i = i+1;
    end;
run;

Here myfunc refers to a custom function I made using proc fcmp which works fine.

The custom transformation works fine if I do not try to take into account the variable number of input columns to act on (i.e. if I use "&&input_col&i" instead of "&&input_col&index" and just use the column result on the output table).

However, I'm having two issues with trying to make the approach more dynamic:

I get the following warning on the line containing
result = myfunc("&&input_col&index"):

WARNING: Apparent symbolic reference INDEX not resolved.

I do not know how to have the assignment to the desired output column happen dynamically; i.e., depending on the iteration of the do loop I'd like to assign the output value to the corresponding output column.

I feel confident that the solution to this must be well known amongst experts, but I cannot find anything explaining how to do this.

Any help is greatly appreciated!

Body:
You can't use macro variables that depend on data variables, in this manner.  Macro variables are resolved at compile time, not at run time.

So you either have to

%do i = 1 %to .. ;

which is fine if you're in a macro (it won't work outside of an actual macro), or you need to use an array.

data cust_trans;
    set &_INPUT0;
    array in[2] &input_col1 &input_col2;  *or however you determine the input columns;
    array output_col[2]; *automatically names the results;
    do i = 1 to dim(in);
        result = myfunc(in[i]); *You quote the input - I cannot see what your function is doing, but it is probably wrong to do so;
        output_col[i] = result; /*what is proper syntax here?*/
    end;
run;

That's the way you'd normally do that.  I don't know what myfunc does, and I also don't know why you quote "&&input_col&index." when you pass it to it, but that would be a strange way to operate unless you want the name of the input column as text (and don't want to know what data is in that variable).  If you do, then pass vname(in[i]) which passes the name of the variable as a character.


问:
C convert signed to unsigned maintaining exact bits
Edit: I updated the example to be C. I am concerned specifically with C and not C++ (sorry for the confusion, see situation below).

I am looking for a safe way to convert a signed integer to an unsigned integer while always maintaining the exact same bit pattern between conversions. As I understand it, simply casting has undefined or implementation dependent behavior so it is not safe to rely on (case A below). But what about bit-wise operators like OR (case B below)? Can bit-wise OR be used to safely convert signed to unsigned? What about the reverse?

Example:

```<code>#include <stdio.h>

int main() {
    // NOTE: assuming 32bit ints
    // example bit pattern: 11111111110001110001001111011010
    //   signed int value: -3730470
    // unsigned int value: 4291236826

    // example 1
    // signed -> unsigned
    int s1 = -3730470;
    unsigned int u1a = (unsigned int)s1;
    unsigned int u1b = (unsigned int)0 | s1;

    printf("%u\n%u\n", u1a, u1b);

    // example 2
    // unsigned -> signed
    unsigned int u2 = 4291236826;
    int s2a = (int)u2;
    int s2b = (int)0 | u2;

    printf("%i\n%i\n", s2a, s2b);
}
</code>```

Situation: I am writing a PostgreSQL C-Language function/extension to add popcount functionality (my first attempt code here). PostgreSQL does not support unsigned types (ref). All the efficient methods of calculating popcount I found require unsigned data types to work correctly. Therefore, I must be able to convert the signed data types to an unsigned data type without changing the bit pattern.

Off topic: I do realize that an alternate solution would be to use PostgreSQL bit string bit and varbit data types instead of the integer data types, but for my purposes the integer data types are much easier to use and manage.

答:
a safe way to convert a signed integer to an unsigned integer while always maintaining the exact same bit pattern between conversions

A union will work as below even if the int is a rare non-2's complement.  Only on very expectational platforms (ticking away in a silicon graveyard) where INT_MAX == UINT_MAX will this be a problem.

```<code>union {
  int i;
  unsigned u;
} x = { some_int };
printf("%d\n", some_int);
printf("%u\n", x.u);
</code>```

Yet if one can limit oneself to common 2's complement int, the below is sufficient.

```<code>unsigned u = (unsigned) some_int;
</code>```

But what about bit-wise operators like OR (case B below)?

  Can bit-wise OR be used to safely convert signed to unsigned?

The following | is like a hidden cast due to integer promotions:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int.  C11dr §6.3.1.1 3

```<code>int s1 = -3730470;
unsigned int u1b = (unsigned int)0 | s1;
// just like
                 = (unsigned int)0 | (unsigned int)s1;
                 =                   (unsigned int)s1;
</code>```

What about the reverse?

Converting a unsigned int to a signed int is well defined if the value is representable in both [0...INT_MAX].  Converting an out-of-int-range unsigned to int is ...

either the result is implementation-defined or an implementation-defined signal is raised. §6.3.1.3 3

Best to use unsigned types for bit manipulations.

The below code may often work as hoped, but should not be used for robust coding.

```<code>// NOTE: assuming 32bit ints, etc.
unsigned int u2 = 4291236826;
int s2a = (int)u2;  // avoid this
</code>```

Alternative

```<code>int s2a;
if (u2 > INT_MAX) {
  // Handle with some other code
} else {
  s2a = (int) u2; // OK
}
</code>```

BTW: better to append u to unsigned constants like 4291236826 to convey to the compiler that indeed an unsigned constant is intended and not a long long like 4291236826.

```<code>unsigned int u2 = 4291236826u;
</code>```

Body:
Edit: I updated the example to be C. I am concerned specifically with C and not C++ (sorry for the confusion, see situation below).

I am looking for a safe way to convert a signed integer to an unsigned integer while always maintaining the exact same bit pattern between conversions. As I understand it, simply casting has undefined or implementation dependent behavior so it is not safe to rely on (case A below). But what about bit-wise operators like OR (case B below)? Can bit-wise OR be used to safely convert signed to unsigned? What about the reverse?

Example:

#include <stdio.h>

int main() {
    // NOTE: assuming 32bit ints
    // example bit pattern: 11111111110001110001001111011010
    //   signed int value: -3730470
    // unsigned int value: 4291236826

    // example 1
    // signed -> unsigned
    int s1 = -3730470;
    unsigned int u1a = (unsigned int)s1;
    unsigned int u1b = (unsigned int)0 | s1;

    printf("%u\n%u\n", u1a, u1b);

    // example 2
    // unsigned -> signed
    unsigned int u2 = 4291236826;
    int s2a = (int)u2;
    int s2b = (int)0 | u2;

    printf("%i\n%i\n", s2a, s2b);
}

Situation: I am writing a PostgreSQL C-Language function/extension to add popcount functionality (my first attempt code here). PostgreSQL does not support unsigned types (ref). All the efficient methods of calculating popcount I found require unsigned data types to work correctly. Therefore, I must be able to convert the signed data types to an unsigned data type without changing the bit pattern.

Off topic: I do realize that an alternate solution would be to use PostgreSQL bit string bit and varbit data types instead of the integer data types, but for my purposes the integer data types are much easier to use and manage.

Body:
a safe way to convert a signed integer to an unsigned integer while always maintaining the exact same bit pattern between conversions

A union will work as below even if the int is a rare non-2's complement.  Only on very expectational platforms (ticking away in a silicon graveyard) where INT_MAX == UINT_MAX will this be a problem.

union {
  int i;
  unsigned u;
} x = { some_int };
printf("%d\n", some_int);
printf("%u\n", x.u);

Yet if one can limit oneself to common 2's complement int, the below is sufficient.

unsigned u = (unsigned) some_int;

But what about bit-wise operators like OR (case B below)?

  Can bit-wise OR be used to safely convert signed to unsigned?

The following | is like a hidden cast due to integer promotions:

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int.  C11dr §6.3.1.1 3

int s1 = -3730470;
unsigned int u1b = (unsigned int)0 | s1;
// just like
                 = (unsigned int)0 | (unsigned int)s1;
                 =                   (unsigned int)s1;

What about the reverse?

Converting a unsigned int to a signed int is well defined if the value is representable in both [0...INT_MAX].  Converting an out-of-int-range unsigned to int is ...

either the result is implementation-defined or an implementation-defined signal is raised. §6.3.1.3 3

Best to use unsigned types for bit manipulations.

The below code may often work as hoped, but should not be used for robust coding.

// NOTE: assuming 32bit ints, etc.
unsigned int u2 = 4291236826;
int s2a = (int)u2;  // avoid this

Alternative

int s2a;
if (u2 > INT_MAX) {
  // Handle with some other code
} else {
  s2a = (int) u2; // OK
}

BTW: better to append u to unsigned constants like 4291236826 to convey to the compiler that indeed an unsigned constant is intended and not a long long like 4291236826.

unsigned int u2 = 4291236826u;


问:
Better way to cast object to int
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is

```<code>int test = int.Parse(string.Format("{0}", myobject))
</code>```

Is there a cleaner way to do this? Thanks

答:
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?</p>

```<code>    // object to int
    // does not handle null
    // does not handle NAN ("102art54")
    // convert value to integar
    int intObj = (int)obj;

    // handles only null or number
    int? nullableIntObj = (int?)obj; // null
    Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null

   // best way for casting from object to nullable int
   // handles null
   // handles other datatypes gives null("sadfsdf") // result null
    int? nullableIntObj2 = obj as int?;

    // string to int
    // does not handle null( throws exception)
    // does not string NAN ("102art54") (throws exception)
    // converts string to int ("26236")
    // accepts string value
    int iVal3 = int.Parse("10120"); // throws exception value cannot be null;

    // handles null converts null to 0
    // does not handle NAN ("102art54") (throws exception)
    // converts obj to int ("26236")
    int val4 = Convert.ToInt32("10120");

    // handle null converts null to 0
    // handle NAN ("101art54") converts null to 0
    // convert string to int ("26236")
    int number;

    bool result = int.TryParse(value, out number);

    if (result)
    {
        // converted value
    }
    else
    {
        // number o/p = 0
    }
</code>```

Title: Better way to cast object to int

Body:
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is

int test = int.Parse(string.Format("{0}", myobject))

Is there a cleaner way to do this? Thanks

Body:
I am listing the difference in each of the casting ways. What a particular type of casting handles and it doesn't?

    // object to int
    // does not handle null
    // does not handle NAN ("102art54")
    // convert value to integar
    int intObj = (int)obj;

    // handles only null or number
    int? nullableIntObj = (int?)obj; // null
    Nullable<int> nullableIntObj1 = (Nullable<int>)obj; // null

   // best way for casting from object to nullable int
   // handles null
   // handles other datatypes gives null("sadfsdf") // result null
    int? nullableIntObj2 = obj as int?;

    // string to int
    // does not handle null( throws exception)
    // does not string NAN ("102art54") (throws exception)
    // converts string to int ("26236")
    // accepts string value
    int iVal3 = int.Parse("10120"); // throws exception value cannot be null;

    // handles null converts null to 0
    // does not handle NAN ("102art54") (throws exception)
    // converts obj to int ("26236")
    int val4 = Convert.ToInt32("10120");

    // handle null converts null to 0
    // handle NAN ("101art54") converts null to 0
    // convert string to int ("26236")
    int number;

    bool result = int.TryParse(value, out number);

    if (result)
    {
        // converted value
    }
    else
    {
        // number o/p = 0
    }


问:
Selenium Python Selector Returning Too Many Values
wondering if anyone can give me some advice for using Selenium with Python for webscraping.

I need to get the number of elements with a certain class on a page, and I have it working well with

```<code>driver=webdriver.PhantomJS()
driver.get('https://www.somerandomsite.com/1')
number_of_elements = len(driver.find_elements_by_class_name('some_class'))
</code>```

this gets the right number of elements every time.

But now I want to define a function so it can scrape multiple webpages - say https://www.somerandomsite.com/1 to https://www.somerandomsite.com/10

So I do

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

Theoretically, this should move onto the next page, and retrieve the number of classes that I want in that page. However, it works fine for the first page, but subsequent pages yield a number of elements that's either equal to the number of elements of the previous page plus that of the current page, or that sum minus 1. If I use an xpath instead of a class name selector I get the exact same results.

Also, if I try to access any elements that are in that longer list, it throws an error since only the values on that page actually exist. So I have no idea how it's getting that longer list if the elements on it don't even exist. (For example, if there are 8 elements on page one and 5 elements on page two, when it gets to page two it'll say there are 12 or 13 elements. If I access elements 1-5 they all return values, but trying to call the sixth element or higher will cause a NoSuchElementException.)

Anyone know why this might be happening?

EDIT: I've narrowed it down a bit more, hopefully this helps. Sorry I was off in the initial question.

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        driver.get('https://www.somerandomsite.com/otherpage')
        start += 1

my_func(1,2)
</code>```

So let's say https://www.somerandomsite.com/1 has 8 elements of class 'some_class', https://www.somerandomsite.com/otherpage has 7 elements of class 'some_class', and https://www.somerandomsite.com/2 has 10 elements of class 'some_class'.

When I run the above code, it'll print 8, then 17. If I don't navigate to the other page, and run

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

```<code>driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        start += 1

my_func(1,2)
</code>```

it'll print 8 then 10, as I want it to. I'm not sure why it's counting elements on two pages at once, and only if I get that other page beforehand.

EDIT2: So I've gotten it working by navigating to a page on a different server and then returning to the page I want. Weird, but I'll use it. If anyone has any ideas on why it doesn't work if I don't though I'd still love to understand the problem better.

答:
Take a look at

```<code>number_of_elements = len(driver.find_elements_by_class_name('some_class'))
</code>```

You asign len of elements on each iteration, but instead you need to sum them, so your code should look like:

```<code>driver=webdriver.PhantomJS()
def my_func(start,end):
    count = 0
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        count += len(driver.find_elements_by_class_name('some_class'))
        start += 1
</code>```

Body:
wondering if anyone can give me some advice for using Selenium with Python for webscraping.

I need to get the number of elements with a certain class on a page, and I have it working well with

driver=webdriver.PhantomJS()
driver.get('https://www.somerandomsite.com/1')
number_of_elements = len(driver.find_elements_by_class_name('some_class'))

this gets the right number of elements every time.

But now I want to define a function so it can scrape multiple webpages - say https://www.somerandomsite.com/1 to https://www.somerandomsite.com/10

So I do

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

Theoretically, this should move onto the next page, and retrieve the number of classes that I want in that page. However, it works fine for the first page, but subsequent pages yield a number of elements that's either equal to the number of elements of the previous page plus that of the current page, or that sum minus 1. If I use an xpath instead of a class name selector I get the exact same results.

Also, if I try to access any elements that are in that longer list, it throws an error since only the values on that page actually exist. So I have no idea how it's getting that longer list if the elements on it don't even exist. (For example, if there are 8 elements on page one and 5 elements on page two, when it gets to page two it'll say there are 12 or 13 elements. If I access elements 1-5 they all return values, but trying to call the sixth element or higher will cause a NoSuchElementException.)

Anyone know why this might be happening?

EDIT: I've narrowed it down a bit more, hopefully this helps. Sorry I was off in the initial question.

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        driver.get('https://www.somerandomsite.com/otherpage')
        start += 1

my_func(1,2)

So let's say https://www.somerandomsite.com/1 has 8 elements of class 'some_class', https://www.somerandomsite.com/otherpage has 7 elements of class 'some_class', and https://www.somerandomsite.com/2 has 10 elements of class 'some_class'.

When I run the above code, it'll print 8, then 17. If I don't navigate to the other page, and run

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        start += 1

So the above code actually works. However, when I then navigate to another page that also has elements of 'some_class', and then continue looping, it adds the number of elements from the previous page to the current page.

So my code's like this:

driver=webdriver.PhantomJS()
def my_func(start,end)
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        number_of_elements = len(driver.find_elements_by_class_name('some_class'))
        print(number_of_elements)
        start += 1

my_func(1,2)

it'll print 8 then 10, as I want it to. I'm not sure why it's counting elements on two pages at once, and only if I get that other page beforehand.

EDIT2: So I've gotten it working by navigating to a page on a different server and then returning to the page I want. Weird, but I'll use it. If anyone has any ideas on why it doesn't work if I don't though I'd still love to understand the problem better.

Body:
Take a look at

number_of_elements = len(driver.find_elements_by_class_name('some_class'))

You asign len of elements on each iteration, but instead you need to sum them, so your code should look like:

driver=webdriver.PhantomJS()
def my_func(start,end):
    count = 0
    while start <= end:
        driver.get('https://www.somerandomsite.com/'+str(start))
        count += len(driver.find_elements_by_class_name('some_class'))
        start += 1


问:
Difficulty with Angular controller usage from old tutorial
I'm going through a basic book for Angular, and it uses a controller to set up a field. However, I don't get the expected output. Searching here and elsewhere, it looks like I'm invoking it correctly, but something's not working. Anything obviously wrong? Anything else to try? Details below. Thanks.

Document html:

```<code><html lang="en" ng-app ng-controller="AppCtrl">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <title></title>
  <script src="js/angular.min.js"></script>
  <script type="text/javascript" src="js/controller.js"></script>
</head>
<body>
  <h1>Hello, {{name || 'World'}}</h1>
  <input type="text" ng-model="name">
</body>
</code>```

controller.js:

```<code>function AppCtrl($scope) {
 $scope.name = "World";
</code>```

(function closing brace lost by code formatting)

Expected output is "Hello, World", but I get "Hello, {{name || 'World'}}"

答:
You are missing the ng-app and the module in controller.

```<code> var app = angular.module('myApp', []);
</code>```

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
 $scope.name = "World";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
  <h1>Hello, {{name || 'World'}}</h1>
  <input type="text" ng-model="name">
  </div>
</body>

</html></code>```

Body:
I'm going through a basic book for Angular, and it uses a controller to set up a field. However, I don't get the expected output. Searching here and elsewhere, it looks like I'm invoking it correctly, but something's not working. Anything obviously wrong? Anything else to try? Details below. Thanks.

Document html:

  <meta charset="utf-8">
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <title></title>

Hello, {{name || 'World'}}

  <input type="text" ng-model="name">

controller.js:

function AppCtrl($scope) {
 $scope.name = "World";

(function closing brace lost by code formatting)

Expected output is "Hello, World", but I get "Hello, {{name || 'World'}}"

Body:
You are missing the ng-app and the module in controller.

 var app = angular.module('myApp', []);

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope, $http) {
 $scope.name = "World";
});

<!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
  <h1>Hello, {{name || 'World'}}</h1>
  <input type="text" ng-model="name">
  </div>
</body>

</html>