问:
touchesbegan, touchesmoved, touchesended issue
For various reasons, I've moved these methods from a UIView subclass to my viewcontroller. And I finally got it working, except for one thing. Not only am I able to drag the UIImageviews I've programmatically created, but the actual view controllers view is draggable too. Creating this much undesired effect. I guess it's the fact that it's touches anyobject, and the background itself is an object. I'm just not sure how exclude the background. I would think that it would need the "UserInteraction enabled", but I guess not? I only want it to make UIImageViews draggable. Please forgive my noobness. I'm still learning.

I have all the imageviews i'd want "touchable" in an NSMutableDictionary called "letterDictionary". Would it be possible to only have touch apply to what's in the dictionary?

http://imgur.com/W08dI

```<code>- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [touches anyObject];
    touchPoint = [touch locationInView:self.view];

    movingLetter = [touch view];

    CGPoint pointInside = [touch locationInView:[touch view]];
    if ([movingLetter pointInside:pointInside withEvent:event]) touchedInside = YES;

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (touchedInside) {
        UITouch *touch = [touches anyObject];
        CGPoint newPoint = [touch locationInView:self.view];  // get the new touch location
        movingLetter.center = CGPointMake(movingLetter.center.x + newPoint.x - touchPoint.x, movingLetter.center.y + newPoint.y - touchPoint.y);
        touchPoint = newPoint;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (touchedInside) {
        UITouch *touch = [touches anyObject];
        CGPoint newPoint = [touch locationInView:self.view];

        movingLetter.center = CGPointMake(movingLetter.center.x + newPoint.x - touchPoint.x, movingLetter.center.y + newPoint.y - touchPoint.y);

        if (CGRectIntersectsRect([movingLetter frame], [placeHolder frame]))
            {
                movingLetter.center = placeHolder.center;
            }

    }
    touchedInside = NO;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    touchedInside = NO;
}
</code>```

答:
In this touchesBegen Method :

```<code>-(void)touchesBegan:(NSSet* )touches withEvent:(UIEvent *)event
 {
     [self.view endEditing:YES];

     UITouch *touch = [touches anyObject];
    _previousPoint1 = [touch      previousLocationInView:self.main_uiview];
    _previousPoint2 = [touch previousLocationInView:self.main_uiview];
    _currentPoint = [touch locationInView:self.main_uiview];

    [self touchesMoved:touches withEvent:event];

    self.bezierPath = [UIBezierPath bezierPath];
    [self.bezierPath moveToPoint:_currentPoint];
     }
</code>```

TouchesMove Method

```<code>  -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent* )event
   {

    UITouch *touch = [touches anyObject];

    _previousPoint2 = _previousPoint1;
    _previousPoint1 = [touch previousLocationInView:self.main_uiview];
    _currentPoint = [touch locationInView:self.main_uiview];

    lastPoint = _currentPoint;

    [_bezierPath addLineToPoint:lastPoint];

    // calculate mid point
    CGPoint mid1 = midPoint4(_previousPoint1, _previousPoint2);
    CGPoint mid2 = midPoint4(_currentPoint, _previousPoint1);

    UIGraphicsBeginImageContextWithOptions(self.bg_imageview.frame.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context,brush);

    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context,kCGLineJoinRound);

    [self.bg_imageview.image drawInRect:CGRectMake(0, 0, self.bg_imageview.frame.size.width, self.bg_imageview.frame.size.height)];

    CGContextMoveToPoint(context, mid1.x, mid1.y);

    // Use QuadCurve is the key
    CGContextAddQuadCurveToPoint(context, _previousPoint1.x, _previousPoint1.y, mid2.x, mid2.y);

    CGContextSetLineCap(context, kCGLineCapRound);

    CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);

    CGContextSetLineWidth(context, 3.0);

    CGContextStrokePath(context);

    self.bg_imageview.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();}
</code>```

Body:
For various reasons, I've moved these methods from a UIView subclass to my viewcontroller. And I finally got it working, except for one thing. Not only am I able to drag the UIImageviews I've programmatically created, but the actual view controllers view is draggable too. Creating this much undesired effect. I guess it's the fact that it's touches anyobject, and the background itself is an object. I'm just not sure how exclude the background. I would think that it would need the "UserInteraction enabled", but I guess not? I only want it to make UIImageViews draggable. Please forgive my noobness. I'm still learning.

I have all the imageviews i'd want "touchable" in an NSMutableDictionary called "letterDictionary". Would it be possible to only have touch apply to what's in the dictionary?

http://imgur.com/W08dI

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch *touch = [touches anyObject];
    touchPoint = [touch locationInView:self.view];

    movingLetter = [touch view];

    CGPoint pointInside = [touch locationInView:[touch view]];
    if ([movingLetter pointInside:pointInside withEvent:event]) touchedInside = YES;

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (touchedInside) {
        UITouch *touch = [touches anyObject];
        CGPoint newPoint = [touch locationInView:self.view];  // get the new touch location
        movingLetter.center = CGPointMake(movingLetter.center.x + newPoint.x - touchPoint.x, movingLetter.center.y + newPoint.y - touchPoint.y);
        touchPoint = newPoint;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (touchedInside) {
        UITouch *touch = [touches anyObject];
        CGPoint newPoint = [touch locationInView:self.view];

        movingLetter.center = CGPointMake(movingLetter.center.x + newPoint.x - touchPoint.x, movingLetter.center.y + newPoint.y - touchPoint.y);

        if (CGRectIntersectsRect([movingLetter frame], [placeHolder frame]))
            {
                movingLetter.center = placeHolder.center;
            }

    }
    touchedInside = NO;
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    touchedInside = NO;
}

Body:
In this touchesBegen Method :

-(void)touchesBegan:(NSSet* )touches withEvent:(UIEvent *)event
 {
     [self.view endEditing:YES];

     UITouch *touch = [touches anyObject];
    _previousPoint1 = [touch      previousLocationInView:self.main_uiview];
    _previousPoint2 = [touch previousLocationInView:self.main_uiview];
    _currentPoint = [touch locationInView:self.main_uiview];

    [self touchesMoved:touches withEvent:event];

    self.bezierPath = [UIBezierPath bezierPath];
    [self.bezierPath moveToPoint:_currentPoint];
     }

TouchesMove Method

  -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent* )event
   {

    UITouch *touch = [touches anyObject];

    _previousPoint2 = _previousPoint1;
    _previousPoint1 = [touch previousLocationInView:self.main_uiview];
    _currentPoint = [touch locationInView:self.main_uiview];

    lastPoint = _currentPoint;

    [_bezierPath addLineToPoint:lastPoint];

    // calculate mid point
    CGPoint mid1 = midPoint4(_previousPoint1, _previousPoint2);
    CGPoint mid2 = midPoint4(_currentPoint, _previousPoint1);

    UIGraphicsBeginImageContextWithOptions(self.bg_imageview.frame.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context,brush);

    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineJoin(context,kCGLineJoinRound);

    [self.bg_imageview.image drawInRect:CGRectMake(0, 0, self.bg_imageview.frame.size.width, self.bg_imageview.frame.size.height)];

    CGContextMoveToPoint(context, mid1.x, mid1.y);

    // Use QuadCurve is the key
    CGContextAddQuadCurveToPoint(context, _previousPoint1.x, _previousPoint1.y, mid2.x, mid2.y);

    CGContextSetLineCap(context, kCGLineCapRound);

    CGContextSetStrokeColorWithColor(context,[UIColor blackColor].CGColor);

    CGContextSetLineWidth(context, 3.0);

    CGContextStrokePath(context);

    self.bg_imageview.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();}


来源: stackexchange

问:
Find all matches in workbook using Excel VBA
I am trying to write a VBA routine that will take a string, search a given Excel workbook, and return to me all possible matches.

I currently have an implementation that works, but it is extremely slow as it is a double for loop. Of course the built in Excel Find function is "optimized" to find a single match, but I would like it to return an array of initial matches that I can then apply further methods to.

I will post some pseudocode of what I have already

```<code>For all sheets in workbook
    For all used rows in worksheet
        If cell matches search string
            do some stuff
        end
    end
end
</code>```

As previously stated, this double for loop makes things run very slowly, so I am looking to get rid of this if possible. Any suggestions?

UPDATE

While the below answers would have improved my method, I ended up going with something slightly different as I needed to do multiple queries over and over.

I instead decided to loop through all rows in my document and create a dictionary containing a key for each unique row. The value this points to will then be a list of possible matches, so that when I query later, I can simply just check if it exists, and if so, just get a quick list of matches.

Basically just doing one initial sweep to store everything in a manageable structure, and then query that structure which can be done in O(1) time

答:
Based on the idea of B Hart's answer, here's my version of a function that searches for a value in a range, and returns all found ranges (cells):

```<code>Function FindAll(ByVal rng As Range, ByVal searchTxt As String) As Range
    Dim foundCell As Range
    Dim firstAddress
    Dim rResult As Range
    With rng
        Set foundCell = .Find(What:=searchTxt, _
                              After:=.Cells(.Cells.Count), _
                              LookIn:=xlValues, _
                              LookAt:=xlWhole, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlNext, _
                              MatchCase:=False)
        If Not foundCell Is Nothing Then
            firstAddress = foundCell.Address
            Do
                If rResult Is Nothing Then
                    Set rResult = foundCell
                Else
                    Set rResult = Union(rResult, foundCell)
                End If
                Set foundCell = .FindNext(foundCell)
            Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress
        End If
    End With

    Set FindAll = rResult
End Function
</code>```

To search for a value in the whole workbook:

```<code>Dim wSh As Worksheet
Dim foundCells As Range
For Each wSh In ThisWorkbook.Worksheets
    Set foundCells = FindAll(wSh.UsedRange, "YourSearchString")
    If Not foundCells Is Nothing Then
        Debug.Print ("Results in sheet '" & wSh.Name & "':")
        Dim cell As Range
        For Each cell In foundCells
            Debug.Print ("The value has been found in cell: " & cell.Address)
        Next
    End If
Next
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write a VBA routine that will take a string, search a given Excel workbook, and return to me all possible matches.

I currently have an implementation that works, but it is extremely slow as it is a double for loop. Of course the built in Excel Find function is "optimized" to find a single match, but I would like it to return an array of initial matches that I can then apply further methods to.

I will post some pseudocode of what I have already

For all sheets in workbook
    For all used rows in worksheet
        If cell matches search string
            do some stuff
        end
    end
end

As previously stated, this double for loop makes things run very slowly, so I am looking to get rid of this if possible. Any suggestions?

UPDATE

While the below answers would have improved my method, I ended up going with something slightly different as I needed to do multiple queries over and over.

I instead decided to loop through all rows in my document and create a dictionary containing a key for each unique row. The value this points to will then be a list of possible matches, so that when I query later, I can simply just check if it exists, and if so, just get a quick list of matches.

Basically just doing one initial sweep to store everything in a manageable structure, and then query that structure which can be done in O(1) time

Body:
Based on the idea of B Hart's answer, here's my version of a function that searches for a value in a range, and returns all found ranges (cells):

Function FindAll(ByVal rng As Range, ByVal searchTxt As String) As Range
    Dim foundCell As Range
    Dim firstAddress
    Dim rResult As Range
    With rng
        Set foundCell = .Find(What:=searchTxt, _
                              After:=.Cells(.Cells.Count), _
                              LookIn:=xlValues, _
                              LookAt:=xlWhole, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlNext, _
                              MatchCase:=False)
        If Not foundCell Is Nothing Then
            firstAddress = foundCell.Address
            Do
                If rResult Is Nothing Then
                    Set rResult = foundCell
                Else
                    Set rResult = Union(rResult, foundCell)
                End If
                Set foundCell = .FindNext(foundCell)
            Loop While Not foundCell Is Nothing And foundCell.Address <> firstAddress
        End If
    End With

    Set FindAll = rResult
End Function

To search for a value in the whole workbook:

Dim wSh As Worksheet
Dim foundCells As Range
For Each wSh In ThisWorkbook.Worksheets
    Set foundCells = FindAll(wSh.UsedRange, "YourSearchString")
    If Not foundCells Is Nothing Then
        Debug.Print ("Results in sheet '" & wSh.Name & "':")
        Dim cell As Range
        For Each cell In foundCells
            Debug.Print ("The value has been found in cell: " & cell.Address)
        Next
    End If
Next


问:
String is null or empty
Ok, here are some easy points. PyBinding came with this script:

```<code>def IsNotNull(value):
    return value is not None
</code>```

It is close, but what I want is this.

```<code>bool IsNotNullOrEmpty(string value) {
    return (value != null) && (value.Length > 0 );
}
</code>```

答:
If it's IronPython, then why not use the default implementation of IsNullOrEmpty from System.String?</p>

```<code>import clr
clr.AddReference('System')
import System
System.String.IsNullOrEmpty('') # returns True
System.String.IsNullOrEmpty(None) # returns True
System.String.IsNullOrEmpty('something') # returns False
</code>```

Title: String is null or empty

Body:
Ok, here are some easy points. PyBinding came with this script:

def IsNotNull(value):
    return value is not None

It is close, but what I want is this.

bool IsNotNullOrEmpty(string value) {
    return (value != null) && (value.Length > 0 );
}

Body:
If it's IronPython, then why not use the default implementation of IsNullOrEmpty from System.String?

import clr
clr.AddReference('System')
import System
System.String.IsNullOrEmpty('') # returns True
System.String.IsNullOrEmpty(None) # returns True
System.String.IsNullOrEmpty('something') # returns False

ContentLicense: CC BY-SA 2.5


问:
Is it possible and rational to deploy .ova file on the cloud?
Is it possible and rational to deploy .ova file on the cloud? Does anybody have a similar experience?</p>

答:
you can use Ravello to deploy ESXI on the cloud and then you can deploy OVA on top of that ,

see :
https://www.ravellosystems.com/solutions/esxi-cloud/install-esxi-on-aws


问:
How to check whether hash key contain JSON in perl?
I am sending a request to the endpoint url ,from there i am getting the response in case of success in form of JSON,but if it fails it return certain text .

Sending request:

```<code>$data->{response} = $self->{_http}->send($myData);
</code>```

So before doing this:

```<code>$resp = from_json($data->{response});
</code>```

i want to check whether the reponse is in json format or not .How we can handle this in Perl kindly help in this

答:
You could use a try/catch block using Try::Tiny</p>

```<code>use Try::Tiny;
try {
    $resp = from_json($data->{response});
} catch {
    # Do something if it does not parse
    warn 'Could not parse json'
};
</code>```

Body:
I am sending a request to the endpoint url ,from there i am getting the response in case of success in form of JSON,but if it fails it return certain text .

Sending request:

$data->{response} = $self->{_http}->send($myData);

So before doing this:

$resp = from_json($data->{response});

i want to check whether the reponse is in json format or not .How we can handle this in Perl kindly help in this

Body:
You could use a try/catch block using Try::Tiny

use Try::Tiny;
try {
    $resp = from_json($data->{response});
} catch {
    # Do something if it does not parse
    warn 'Could not parse json'
};


问:
BWA can't find the local index file
I'm currently trying to import a .fasta file into bwa to use a reference genome to map my reads to. However, i currently am getting this error:

```<code>[E::bwa_idx_load_from_disk] fail to locate the index files
</code>```

Any help? Here is my code:

```<code>#!/bin/bash

source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load pear/0.9.10
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
module load bwa/0.7.12
module load samtools/1.2
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load trimmomatic/0.35

r=20
####mapping
#Indexing reference library for BWA mapping:
bwa index -a is ~/gz_files/sample_things/fungiref.fa fungiref

bwa mem fungiref sample${r}_clipped_paired.assembled.fastq > sample${r}.sam

#sort and convert to bam
samtools view -bS sample${r}.sam | samtools sort - sample{r}_sorted

#counts and stats
samtools index sample${r}_sorted.bam
samtools idxstats sample${r}_sorted.bam > ${r}_counts.txt
</code>```

答:
The usage for bwa index is

```<code>bwa index [-p prefix] [-a algoType] <in.db.fasta>
</code>```

Your usage doesn’t match this; it’s a shame that bwa silently accepts this instead of immediately throwing an error. Annoyingly, there is also simply no way to specify a path prefix for the index. You’re stuck with the location of your reference.

At any rate, the index filename is derived from the FASTA reference file. As a consequence you need to adjust your index filename in the subsequent command:

```<code>bwa mem ~/gz_files/sample_things/fungiref.fa sample${r}_clipped_paired.assembled.fastq > sample${r}.sam
</code>```

Title: BWA can't find the local index file

Body:
I'm currently trying to import a .fasta file into bwa to use a reference genome to map my reads to. However, i currently am getting this error:

[E::bwa_idx_load_from_disk] fail to locate the index files

Any help? Here is my code:

#!/bin/bash

source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load pear/0.9.10
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load fastqc/0.10.1
module load fastx/0.0.13
module load bwa/0.7.12
module load samtools/1.2
source /opt/asn/etc/asn-bash-profiles-special/modules.sh
module load trimmomatic/0.35

r=20
####mapping
#Indexing reference library for BWA mapping:
bwa index -a is ~/gz_files/sample_things/fungiref.fa fungiref

bwa mem fungiref sample${r}_clipped_paired.assembled.fastq > sample${r}.sam

#sort and convert to bam
samtools view -bS sample${r}.sam | samtools sort - sample{r}_sorted

#counts and stats
samtools index sample${r}_sorted.bam
samtools idxstats sample${r}_sorted.bam > ${r}_counts.txt

Body:
The usage for bwa index is

bwa index [-p prefix] [-a algoType] <in.db.fasta>

Your usage doesn’t match this; it’s a shame that bwa silently accepts this instead of immediately throwing an error. Annoyingly, there is also simply no way to specify a path prefix for the index. You’re stuck with the location of your reference.

At any rate, the index filename is derived from the FASTA reference file. As a consequence you need to adjust your index filename in the subsequent command:

bwa mem ~/gz_files/sample_things/fungiref.fa sample${r}_clipped_paired.assembled.fastq > sample${r}.sam


问:
Overlay over WebBrowser control
I have a TabControl (using InfragisticTabControl) where each TabItem contains a WebBrowser control where I can display a URL like www.google.com or any xbap UI.

Below is the TabItem Code:

```<code><Grid>
    <WebBrowser x:Name="myBrowser"
            webHelper:WebBrowserHelper.BrowserSource="{Binding XBAP_URI}"
            Height="Auto"/>

    <Grid Name="MyOverlayGrid" Background="LightGray" Opacity="0.5"
          Visibility="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisible2}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type igDock:ContentPane}}}">
        <TextBlock Text="User does not have permissions for this application" FontSize="24"/>
    </Grid>
</Grid>
</code>```

I verified using snoop that Visibility binding is correctly getting populated, but I don't see MyOverlayGrid on myBrowser control. I even tried updating Panel.ZIndex for MyOverlayGrid, no help.

Only thing that worked is to set myBrowser visibility to hidden (i used snoop) and then i could see MyOverlayGrid.

Can anyone tell me if I am doing something incorrect or missing something obvious? This works fine for a contentcontrol, may be its not possible for a WebBrowser control since the its starts new applictaion (InternetExplorer.exe or PresentationHost.exe) in the tab control?

Thanks,

RDV

答:
Can anyone tell me if I am doing something incorrect or missing something obvious?

The latter am I afraid. The WebBrowser control is hosted in a separate HWND that is always drawn on top of the WPF elements as stated in the documentation on MSDN: https://msdn.microsoft.com/en-us/library/ms744952(v=vs.110).aspx.

There is nothing much you can do about this besides applying a workaround like for example putting your Grid in a Popup.

You may want to consider using some other third-party WebBrowser control such as for example Chromium.

Title: Overlay over WebBrowser control

Body:
I have a TabControl (using InfragisticTabControl) where each TabItem contains a WebBrowser control where I can display a URL like www.google.com or any xbap UI.

Below is the TabItem Code:

<Grid>
    <WebBrowser x:Name="myBrowser"
            webHelper:WebBrowserHelper.BrowserSource="{Binding XBAP_URI}"
            Height="Auto"/>

    <Grid Name="MyOverlayGrid" Background="LightGray" Opacity="0.5"
          Visibility="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisible2}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type igDock:ContentPane}}}">
        <TextBlock Text="User does not have permissions for this application" FontSize="24"/>
    </Grid>
</Grid>

I verified using snoop that Visibility binding is correctly getting populated, but I don't see MyOverlayGrid on myBrowser control. I even tried updating Panel.ZIndex for MyOverlayGrid, no help.

Only thing that worked is to set myBrowser visibility to hidden (i used snoop) and then i could see MyOverlayGrid.

Can anyone tell me if I am doing something incorrect or missing something obvious? This works fine for a contentcontrol, may be its not possible for a WebBrowser control since the its starts new applictaion (InternetExplorer.exe or PresentationHost.exe) in the tab control?

Thanks,

RDV


问:
Adding to an array of characters in Fortran
I'm trying to write a class procedure that adds a new character to an array of characters, but keep stumbling across "different character length in array constructor" errors (compiling with GFortran), even when the characters lengths are, as far as I can see, the same.

Here's my function:

```<code>subroutine addToArray(this, newElement)
  class(MyClass), intent(inout) :: this
  character(len=*), intent(in) :: newElement
  character(len=256) :: tempElement
  character(len=256), dimension(:), allocatable :: temp

  tempElement = newElement               ! Needed otherwise newElement is of the wrong size
  allocate(temp(size(this%charArray)+1)  ! Make the char array bigger by 1
  temp = [this%charArray, tempElement]
  call move_alloc(from=temp, to=this%charArray)
end subroutine
</code>```

This results in the error Fortran runtime error: Different CHARACTER lengths (538976288/256) in array constructor. However, if I print len(this%charArray) or len(tempElement), they are both 256 characters long. So where is the 538976288 coming from?

I'm typically calling this procedure using something like myObject%addToArray('hello'). this%charArray is declared in the type definition as character(len=256), dimension(:), allocatable :: charArray, and allocated using allocate(this%charArray(0)).

答:
It appears it is an error which I reported to GCC more than a year ago https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70231

The workaround is to compile with optimizations at least -O1.

If it is not the same error, an exact reproduction case is needed including the compilation flags and all relevant details.

Body:
I'm trying to write a class procedure that adds a new character to an array of characters, but keep stumbling across "different character length in array constructor" errors (compiling with GFortran), even when the characters lengths are, as far as I can see, the same.

Here's my function:

subroutine addToArray(this, newElement)
  class(MyClass), intent(inout) :: this
  character(len=*), intent(in) :: newElement
  character(len=256) :: tempElement
  character(len=256), dimension(:), allocatable :: temp

  tempElement = newElement               ! Needed otherwise newElement is of the wrong size
  allocate(temp(size(this%charArray)+1)  ! Make the char array bigger by 1
  temp = [this%charArray, tempElement]
  call move_alloc(from=temp, to=this%charArray)
end subroutine

This results in the error Fortran runtime error: Different CHARACTER lengths (538976288/256) in array constructor. However, if I print len(this%charArray) or len(tempElement), they are both 256 characters long. So where is the 538976288 coming from?

I'm typically calling this procedure using something like myObject%addToArray('hello'). this%charArray is declared in the type definition as character(len=256), dimension(:), allocatable :: charArray, and allocated using allocate(this%charArray(0)).


问:
How to integrate admob with google play services?
Can anyone please tell me how to integrate admob plugin with google play services plug in unity.I am struggle since long time to solve this problem .But, I am not able to solve it.</p>

答:
I am using Unity Ads and I have been more than satisfied with it. Unity provides ads so if you use their service, ads showen will be provided by Unity. It is very simple to implement. Really good explained in this video Ads tutorial unity.
You can show ad just with Advertisement.Show() which will show default ad which can be set here.


问:
Simple Encryption/Decryption method for encrypting an image file
My requirement is that I need simple encryption/decryption methods in C# to encrypt and
decrypt an image (maybe gif/jpeg).Simple cause I have to store it in the database in a BLOB field andsome other developers in some other programming language(like java) may need to extract and display this image.I don't need much security cause its just a matter of "security by obscuring"(life).

Gulp..can someone help...

答:
Look at the System.Security.Cryptography namespace.

Here is an article about encrypting data.

Your question is very general - the linked article gives you examples of encryption using the built in functions.


问:
iOS - How to set image to ImageView according to a specific value
I have several images, and I would like to set the image of my ImageView according to a specific value I get from web service.

For example if I got value "dog" I have to set image of a dog.

All the images are in my xcassets repertory.

Should I make a Switch for that ? Or is there a better way to do it ?

答:
lets say you are getting "dog" value from the web service, and you have "dog" image saved in .xcassests folder, then you can simply use the same name to specify the image name. Ideally create the same image name coming from the server in .xcassets folder to correctly map the image.

assuming you have Model as Data struct and imageName property stores the image name

```<code>struct Data {
  let imageName: String
}

let imageName = data.imageName //"dog"
imageView.image = UIImage(named: imageName)
</code>```

Body:
lets say you are getting "dog" value from the web service, and you have "dog" image saved in .xcassests folder, then you can simply use the same name to specify the image name. Ideally create the same image name coming from the server in .xcassets folder to correctly map the image.

assuming you have Model as Data struct and imageName property stores the image name

struct Data {
  let imageName: String
}

let imageName = data.imageName //"dog"
imageView.image = UIImage(named: imageName)


问:
Sort of the table datatables jquery
I use the DataTables plugin to display the data but I change the data of the table with PHP and AJAX:

```<code>$aColumns = array(
  'entity_id',
  'entity_immatriculation',
  'entity_designation',
  'categorieentity_label',
  'emplacemententity_label',
  'familleentity_label',
  'entity_date_destruction',
  'entity_prix',
  'id_entity_etat'
);

Model::factory('entity')->_ajax_entity($aColumns,$this->_controller);
</code>```

Module :

```<code>foreach($rResult as $aRow)
{
  $row = array();
  for ($i = 0; $i < count($aColumns); $i++)
  {
    if ($i == 6)
    {
      $row[] = $compteur;
    }
  }
}
</code>```

The display is OK but the sort of the table is always by the old value entity_date_destruction Please help please.

答:
you can use syntax below to change default sorting.

```<code>var table = $('#example').DataTable();

var data = table
.column( 0 )
.data()
.sort();
</code>```

It will sort w.r.t first (0) column.

Title: Sort of the table datatables jquery

Body:
I use the DataTables plugin to display the data but I change the data of the table with PHP and AJAX:

$aColumns = array(
  'entity_id',
  'entity_immatriculation',
  'entity_designation',
  'categorieentity_label',
  'emplacemententity_label',
  'familleentity_label',
  'entity_date_destruction',
  'entity_prix',
  'id_entity_etat'
);

Model::factory('entity')->_ajax_entity($aColumns,$this->_controller);

Module :

foreach($rResult as $aRow)
{
  $row = array();
  for ($i = 0; $i < count($aColumns); $i++)
  {
    if ($i == 6)
    {
      $row[] = $compteur;
    }
  }
}

The display is OK but the sort of the table is always by the old value entity_date_destruction Please help please.

Body:
you can use syntax below to change default sorting.

var table = $('#example').DataTable();

var data = table
.column( 0 )
.data()
.sort();

It will sort w.r.t first (0) column.


问:
Transform SQL Table
We have a table that has the following format

```<code>RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40
</code>```

We would like to present this as:

```<code>John   30
Alice  40
</code>```

Anyone have a good solution for this?

答:
Why didn't anybody use pivot?</p>

```<code>declare @a TABLE(RecordId int, FieldName varchar(20), FieldValue varchar(20))

insert into @a select 1, 'Name', 'John'
insert into @a select 1, 'Age', '30'
insert into @a select 2, 'Name', 'Alice'
insert into @a select 2, 'Age', '40'

select *
from @a a pivot (max(FieldValue) for FieldName in (Name,Age)) p
</code>```

Title: Transform SQL Table

Body:
We have a table that has the following format

RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40

We would like to present this as:

John   30
Alice  40

Anyone have a good solution for this?

Body:
Why didn't anybody use pivot?

declare @a TABLE(RecordId int, FieldName varchar(20), FieldValue varchar(20))

insert into @a select 1, 'Name', 'John'
insert into @a select 1, 'Age', '30'
insert into @a select 2, 'Name', 'Alice'
insert into @a select 2, 'Age', '40'

select *
from @a a pivot (max(FieldValue) for FieldName in (Name,Age)) p


问:
open new activity with button
here is the code of my xml.

```<code><Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>
</code>```

and here is my code of java.

```<code> public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}
</code>```

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

答:
You have two ways:

Either

1) Set an onClick listener on the button

Or

2) Set an onClick attribute on the button and create a method

Method 1

Xml file

```<code><Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:layout_gravity="center_horizontal"
        android:text="Make New Account"
        android:textColor="#E74C3C"
        android:textStyle="bold"
        android:paddingTop="20dp"/>
</code>```

Java File

```<code>public Button btn2;
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
    }
});
</code>```

Method 2

Xml file

```<code><Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn2"
    android:layout_gravity="center_horizontal"
    android:onclick="newAccount"
    android:text="Make New Account"
    android:textColor="#E74C3C"
    android:textStyle="bold"
    android:paddingTop="20dp"/>
</code>```

Java file

```<code>public Button btn2;
btn2=(Button)findViewById(R.id.btn2);
public void newAccount(View v) {
        Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
    }
</code>```

Title: open new activity with button

Body:
here is the code of my xml.

<Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/btn2"
            android:layout_gravity="center_horizontal"
            android:text="Make New Account"
            android:onClick="new"
            android:textColor="#E74C3C"
            android:textStyle="bold"
            android:paddingTop="20dp"/>

and here is my code of java.

 public Button btn2;
public void onClick(){
    btn2=(Button)findViewById(R.id.btn2);
    btn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,submit.class);
            startActivity(intent);
        }
    });

}

my button is not working yet, even an message will appear after clicking on button that unfortunately application has stopped... what is the reason??

Body:
You have two ways:

Either

1) Set an onClick listener on the button

Or

2) Set an onClick attribute on the button and create a method

Method 1

Xml file

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn2"
        android:layout_gravity="center_horizontal"
        android:text="Make New Account"
        android:textColor="#E74C3C"
        android:textStyle="bold"
        android:paddingTop="20dp"/>

Java File

public Button btn2;
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
    }
});

Method 2

Xml file

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn2"
    android:layout_gravity="center_horizontal"
    android:onclick="newAccount"
    android:text="Make New Account"
    android:textColor="#E74C3C"
    android:textStyle="bold"
    android:paddingTop="20dp"/>

Java file

public Button btn2;
btn2=(Button)findViewById(R.id.btn2);
public void newAccount(View v) {
        Intent intent = new Intent(MainActivity.this,submit.class);
        startActivity(intent);
    }


问:
CSS column element inside bug
I used column-count, but it looks like I found a bug when an element has an absolute position and overflowed from the parent.

```<code>#master {
    column-count: 2;
}

.Books {
    display: table;
    column-break-inside: avoid;
    -webkit-column-break-inside: avoid;
}
</code>```

JSFiddle

There are two issues. One, the two red elements are not balanced (see the purple line) and second, the red element dropped on the bottom.

答:
This is the way column-count works. Add margin-top: 10px; to your .Books class and the issue will be fixed. Like this: https://jsfiddle.net/x6ms3nxr/5/

Red element dropped to the bottom is actually a part of bookmark from second column that is cut and gone to the first column.

Some additional details regarding columns support in browsers can be found here:
http://zomigi.com/blog/deal-breaker-problems-with-css3-multi-columns/

Title: CSS column element inside bug

Body:
I used column-count, but it looks like I found a bug when an element has an absolute position and overflowed from the parent.

#master {
    column-count: 2;
}

.Books {
    display: table;
    column-break-inside: avoid;
    -webkit-column-break-inside: avoid;
}

JSFiddle

There are two issues. One, the two red elements are not balanced (see the purple line) and second, the red element dropped on the bottom.


问:
Error while creating calculated field in Tableau
I have a Baseball Player Data file. I want to create a calculated column called "Quadrant" which will categorise the types of players into 4 categories.
My code is:

```<code>CASE

WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Banjo Hitter"
WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Patient Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Solid Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Top Performer"
END
</code>```

here OBP and BB/K are calculated fields. The 50th percentile is the median.
I am getting an error that says "Syntax error: maybe you are missing an identifier".
Can anyone help me figure out what my mistake is? I am new to tableau and practicing examples.

答:
The percentile expression can be as per below image:

The below calculation is valid.

```<code>IF [OBP]<= { FIXED : PERCENTILE([OBP],0.50) }AND [BB/K]<= { FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Banjo Hitter"

    ELSEIF  [OBP]<= { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Patient Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]<={ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Solid Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Top Performer"

    END
</code>```

Also for reference Click Here

Body:
I have a Baseball Player Data file. I want to create a calculated column called "Quadrant" which will categorise the types of players into 4 categories.
My code is:

CASE

WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Banjo Hitter"
WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Patient Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Solid Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Top Performer"
END

here OBP and BB/K are calculated fields. The 50th percentile is the median.
I am getting an error that says "Syntax error: maybe you are missing an identifier".
Can anyone help me figure out what my mistake is? I am new to tableau and practicing examples.

Body:
The percentile expression can be as per below image:

The below calculation is valid.

IF [OBP]<= { FIXED : PERCENTILE([OBP],0.50) }AND [BB/K]<= { FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Banjo Hitter"

    ELSEIF  [OBP]<= { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Patient Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]<={ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Solid Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Top Performer"

    END

Also for reference Click Here


问:
Passing pointer to ndarray in a struct within a struct (ctypes)
I have a ctypes function that has a struct, containing another struct, as one of its arguments.
I have created the structs as follows;

```<code>class ChannelDataBuffers(Structure):
_pack_ = PACK
_fields_ = [
            ("bufferMax",  c_void_p),
            ("bufferMin", c_void_p),
            ("dataType", c_int32)
            ]

class DataBuffers(Structure):
_pack_ = PACK
_fields_ =  [
                ("channel",               c_int32),
                ("waveform",              c_uint64),
                ("downSampleRatioMode",   c_int32),
                ("read",                  c_int32),
                ("buffers",               ChannelDataBuffers),
                ("nbuffers",              c_uint32),
                ("nDistributionPoints",   c_uint32)
            ]
def __init__(self, channel, waveform, ratiomode, read, ref_buffermax, ref_buffermin, datatype, nbuffers, nDistributionPoints):

    self.channel = c_int32(channel)
    self.waveform = c_uint64(waveform)
    self.downSampleRatioMode = c_int32(ratiomode)
    self.read = c_int32(read)
    self.buffers.bufferMax = (ref_buffermax)
    self.buffers.bufferMin = (ref_buffermin)
    self.buffers.datatype = c_int32(datatype)
    self.nbuffers = c_uint32(nbuffers)
    self.nDistributionPoints = c_uint32(nDistributionPoints)
</code>```

The bufferMax and bufferMin are both numpy arrays, passed using the .ctypes argument - ie defined as follows:

```<code>bufMax = self._buffers[bufIndex].data.ctypes
</code>```

This results in an object being passed into the DataBuffers init function of

```<code>numpy.core._internal._ctypes object at 0x08D99D90
</code>```

Which seems sensible.
However I then hit an exception of

```<code> cannot be converted to pointer <type 'exceptions.TypeError'>
</code>```

at the line

```<code>self.buffers.bufferMax = (ref_buffermax)
</code>```

Anyone know what I can do to fix this??

答:
Possibly you need to use ctypes.cast:

```<code>self.buffers.bufferMax = ctypes.cast(ref_buffermax, c_void_p)
</code>```

Body:
I have a ctypes function that has a struct, containing another struct, as one of its arguments.
I have created the structs as follows;

class ChannelDataBuffers(Structure):
_pack_ = PACK
_fields_ = [
            ("bufferMax",  c_void_p),
            ("bufferMin", c_void_p),
            ("dataType", c_int32)
            ]

class DataBuffers(Structure):
_pack_ = PACK
_fields_ =  [
                ("channel",               c_int32),
                ("waveform",              c_uint64),
                ("downSampleRatioMode",   c_int32),
                ("read",                  c_int32),
                ("buffers",               ChannelDataBuffers),
                ("nbuffers",              c_uint32),
                ("nDistributionPoints",   c_uint32)
            ]
def __init__(self, channel, waveform, ratiomode, read, ref_buffermax, ref_buffermin, datatype, nbuffers, nDistributionPoints):

    self.channel = c_int32(channel)
    self.waveform = c_uint64(waveform)
    self.downSampleRatioMode = c_int32(ratiomode)
    self.read = c_int32(read)
    self.buffers.bufferMax = (ref_buffermax)
    self.buffers.bufferMin = (ref_buffermin)
    self.buffers.datatype = c_int32(datatype)
    self.nbuffers = c_uint32(nbuffers)
    self.nDistributionPoints = c_uint32(nDistributionPoints)

The bufferMax and bufferMin are both numpy arrays, passed using the .ctypes argument - ie defined as follows:

bufMax = self._buffers[bufIndex].data.ctypes

This results in an object being passed into the DataBuffers init function of

numpy.core._internal._ctypes object at 0x08D99D90

Which seems sensible.
However I then hit an exception of

 cannot be converted to pointer <type 'exceptions.TypeError'>

at the line

self.buffers.bufferMax = (ref_buffermax)

Anyone know what I can do to fix this??

Body:
Possibly you need to use ctypes.cast:

self.buffers.bufferMax = ctypes.cast(ref_buffermax, c_void_p)


问:
What is a viable local database for Windows Phone 7 right now?
I was wondering what is a viable database solution for local storage on Windows Phone 7 right now. Using search I stumbled upon these 2 threads but they are over a few months old. I was wondering if there are some new development in databases for WP7. And I didn't found any reviews about the databases mentioned in the links below.

windows phone 7 database

Local Sql database support for Windows phone 7

My requirements are:

It should be free for commercial use

Saving/updating a record should only save the actual record and not the entire database (unlike WinPhone7 DB)

Able to fast query on a table with ~1000 records using LINQ.

Should also work in simulator

EDIT:

Just tried Sterling using a simple test app: It looks good, but I have 2 issues.

Creating 1000 records takes 30 seconds using db.Save(myPerson). Person is a simple class with 5 properties.

Then I discovered there is a db.SaveAsync<Person>(IList) method. This is fine because it doesn't block the current thread anymore.

BUT my question is: Is it save to call db.Flush() immediately and do a query on the currently saving IList? (because it takes up to 30 seconds to save the records in synchronous mode). Or do I have to wait until the BackgroundWorker has finished saving?

Query these 1000 records with LINQ and a where clause the first time takes up to 14 sec to load into memory.

Is there a way to speed this up?

Here are some benchmark results: (Unit tests was executed on a HTC Trophy)

```
-----------------------------
purging: 7,59 sec
creating 1000 records: 0,006 sec
saving 1000 records: 32,374 sec
flushing 1000 records: 0,07 sec
-----------------------------
//async
creating 1000 records: 0,04 sec
saving 1000 records: 0,004 sec
flushing 1000 records: 0 sec
-----------------------------
//get all keys
persons list count = 1000 (0,007)
-----------------------------
//get all persons with a where clause
persons list with query count = 26 (14,241)
-----------------------------
//update 1 property of 1 record + save
persons list with query count = 26 (0,003s)
db saved (0,072s)
```

答:
You might want to take a look at Sterling - it should address most of your concerns and is very flexible.

http://sterling.codeplex.com/

(Full disclosure: my project)

Body:
I was wondering what is a viable database solution for local storage on Windows Phone 7 right now. Using search I stumbled upon these 2 threads but they are over a few months old. I was wondering if there are some new development in databases for WP7. And I didn't found any reviews about the databases mentioned in the links below.

windows phone 7 database

Local Sql database support for Windows phone 7

My requirements are:

It should be free for commercial use

Saving/updating a record should only save the actual record and not the entire database (unlike WinPhone7 DB)

Able to fast query on a table with ~1000 records using LINQ.

Should also work in simulator

EDIT:

Just tried Sterling using a simple test app: It looks good, but I have 2 issues.

Creating 1000 records takes 30 seconds using db.Save(myPerson). Person is a simple class with 5 properties.

Then I discovered there is a db.SaveAsync<Person>(IList) method. This is fine because it doesn't block the current thread anymore.

BUT my question is: Is it save to call db.Flush() immediately and do a query on the currently saving IList? (because it takes up to 30 seconds to save the records in synchronous mode). Or do I have to wait until the BackgroundWorker has finished saving?

Query these 1000 records with LINQ and a where clause the first time takes up to 14 sec to load into memory.

Is there a way to speed this up?

Here are some benchmark results: (Unit tests was executed on a HTC Trophy)

-----------------------------
purging: 7,59 sec
creating 1000 records: 0,006 sec
saving 1000 records: 32,374 sec
flushing 1000 records: 0,07 sec
-----------------------------
//async
creating 1000 records: 0,04 sec
saving 1000 records: 0,004 sec
flushing 1000 records: 0 sec
-----------------------------
//get all keys
persons list count = 1000 (0,007)
-----------------------------
//get all persons with a where clause
persons list with query count = 26 (14,241)
-----------------------------
//update 1 property of 1 record + save
persons list with query count = 26 (0,003s)
db saved (0,072s)


问:
How to execute success method in Firebase?
I'm developing an Android+Firebase app but since I'm new to both techlogies I'm having a problem regarding async calls and I haven't found the solution yet so hope you can help me.

I have the following snippet in my Activity's onCreate method:

```<code>final ArrayList<AssetLocation> assetsLocations = new ArrayList<>();
        DatabaseReference assetsLocationReference = database.getReference(FirebaseReferences.ASSETSLOCATION_REFERENCE);
        assetsLocationReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                ArrayList<String> assetsLocationSpinner = new ArrayList<String>();
                // Create an ArrayAdapter using the string array and a default spinner layout
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    //Getting the data from snapshot
                    AssetLocation assetsLocation = postSnapshot.getValue(AssetLocation.class);
                    assetsLocations.add(AssetLocation);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });
</code>```

I also have a pretty similar call but instead of getting Locations, I'm getting Types.

After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

How can I execute setScreenInfo once the calls are made? I tried with .once()/.on() but it's not being recognised by Android Studio as a function.

Thanks for your help!

答:
After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

You aren't allowed to modify the UI from a background thread.  Normally I would make a call to runOnUIThread, passing a new Runnable() and a final copy of the data I want to pass.

```<code>        final String myData = "updateData";

        ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // use myData to update UI
            }
        });
</code>```

However, it seems like there's a migration to AsyncTask : Converting runOnUiThread to AsyncTask

I personally still use runOnUIThread.  It's more explicit.

Body:
I'm developing an Android+Firebase app but since I'm new to both techlogies I'm having a problem regarding async calls and I haven't found the solution yet so hope you can help me.

I have the following snippet in my Activity's onCreate method:

final ArrayList<AssetLocation> assetsLocations = new ArrayList<>();
        DatabaseReference assetsLocationReference = database.getReference(FirebaseReferences.ASSETSLOCATION_REFERENCE);
        assetsLocationReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                ArrayList<String> assetsLocationSpinner = new ArrayList<String>();
                // Create an ArrayAdapter using the string array and a default spinner layout
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    //Getting the data from snapshot
                    AssetLocation assetsLocation = postSnapshot.getValue(AssetLocation.class);
                    assetsLocations.add(AssetLocation);
                }
            }

            @Override
            public void onCancelled(DatabaseError firebaseError) {
                System.out.println("The read failed: " + firebaseError.getMessage());
            }
        });

I also have a pretty similar call but instead of getting Locations, I'm getting Types.

After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

How can I execute setScreenInfo once the calls are made? I tried with .once()/.on() but it's not being recognised by Android Studio as a function.

Thanks for your help!

Body:
After this code (inside the onCreate method as well), I'm calling setScreenInfo which is a function to fill both spinners (and do more stuff) with said data but since it is an async call, the spinners are blank when I execute it.

You aren't allowed to modify the UI from a background thread.  Normally I would make a call to runOnUIThread, passing a new Runnable() and a final copy of the data I want to pass.

        final String myData = "updateData";

        ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // use myData to update UI
            }
        });

However, it seems like there's a migration to AsyncTask : Converting runOnUiThread to AsyncTask

I personally still use runOnUIThread.  It's more explicit.


问:
MySQL LOAD_FILE() loads null values
I'm attempting to load a directory of xml files into a database table as blobs.  Each row would contain a corresponding blob file.  When loading files via a python script into the table, values are inserted as null.  This is also the case when running an equivalent command in the mysql command line.

At one point I was able to insert values after changing some folder permissions to mysql, but due to needed scripting privileges I had to modify ownership of the directory /var/lib/mysql/foo, thus values are being reinserted as null effectively breaking the script I wrote.  I cannot remember the necessary change of directory permissions to do so.

The following are discussions of the topic:

http://bugs.mysql.com/bug.php?id=38403

along with

MySQL LOAD_FILE returning NULL

答:
I have lost some time with this problem. In my case, the problem had to do with secure_file_priv variable defined in "my.ini".

From MySQL documentation:

If the secure_file_priv system variable is set to a nonempty
  directory name, the file to be loaded must be located in that
  directory

So, there are two ways:

1)remove this option
2) use the default folder for uploading files ("C:\ProgramData\MySQL\MySQL Server 5.7\Uploads"). I also had to use double slash in Windows.

Title: MySQL LOAD_FILE() loads null values


问:
how to get get_theme_mod value into array in wordpress?
I want to make an array by theme_mod value in wp theme customizer.

for example in this code:

```<code>$arr = array(com, net, org);
foreach ($arr as &$value) {
    echo "<div id='domain-$value'></div>";
}
</code>```

I have an array like above with some tlds and want to set it dynamically by wp mcomstomizer.

I had a try by put "get_theme_mod( 'tlds' );" (like below) in array but no success and it put all the value in just one array key.

```<code>$arr = array(get_theme_mod( 'tlds' ););
foreach ($arr as &$value) {
    echo "<div id='domain-$value'></div>";
}
</code>```

How to put values into array and separate every array by comma,?

答:
get_them_mods() should return an array that you can loop over.

https://codex.wordpress.org/Function_Reference/get_theme_mods

You can use array_values()

Example:

```<code>$arr = get_them_mods();
$temp = array_values($arr);
foreach ($temp as $value) {
    echo "<div id='domain-$value'></div>";
}
</code>```

Body:
I want to make an array by theme_mod value in wp theme customizer.

for example in this code:

$arr = array(com, net, org);
foreach ($arr as &$value) {
    echo "

";
}

I have an array like above with some tlds and want to set it dynamically by wp mcomstomizer.

I had a try by put "get_theme_mod( 'tlds' );" (like below) in array but no success and it put all the value in just one array key.

$arr = array(get_theme_mod( 'tlds' ););
foreach ($arr as &$value) {
    echo "

";
}

How to put values into array and separate every array by comma,?

Body:
get_them_mods() should return an array that you can loop over.

https://codex.wordpress.org/Function_Reference/get_theme_mods

You can use array_values()

Example:

$arr = get_them_mods();
$temp = array_values($arr);
foreach ($temp as $value) {
    echo "<div id='domain-$value'></div>";
}


问:
Using collection size in for loop comparison
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

```<code>for(int i=0;i<list.size();i++)
      ...some operation.....
</code>```

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

```<code>final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....
</code>```

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.

答: Calling the size() method of a collection is just returning an integer value that is already kept track of. There isnt much of a time difference because size() isnt actually counting the number of items but instead the number of items are kept track of when you add or remove them.</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there a compiler optimization for the size() methods of Collections in Java?

Consider the following code:

for(int i=0;i<list.size();i++)
      ...some operation.....

There is a call to the size() methods for every i. Won't it be better to find out the size and reuse it? (Method calls have overheads).

final int len = list.size()
for(int i=0;i<len;i++)
      ...some operation.....

However, when I timed both these code pieces there was no significant time difference, even for i as high as 10000000.
Am I missing something here?

Update1: I understand that the size is not computed again unless the collection changes. But there has to be some overhead associated with a method call. Is it the case that the compiler always inlines these (See Esko's answer)?

Update 2: My curiosity has been fueled further. From the answers given, I see that good JIT compilers will often inline this function call. But they will still have to determine whether the collection was modified or not. I am not accepting an answer in the hope that someone will give me pointers regarding how this is handled by compilers.


问:
ERROR 1046:No database selected
I would  like  to create a SQL database  but this error occurs I do not know why. Can somebody  help  me?

My SQL statement:

```<code>CREATE TABLE 'users'(
    'user_id' int (11) NOT NULL AUTO_INCREMENT,
    'username' varchar (255) DEFAULT NULL,
    'password' varchar (255) DEFAULT NULL,
    PRIMARY KEY ('user_id')
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
</code>```

Can somebody help me?

答:
Select the database first using:
USE database_name

If you haven't created database, create it by using :

```<code>CREATE DATABASE database_name
</code>```

and select database using :

```<code>USE database_name
</code>```

Now, you can create table as follows :

```<code>CREATE TABLE users(
user_id int (11) NOT NULL AUTO_INCREMENT,
username varchar (255) DEFAULT NULL,
password varchar (255) DEFAULT NULL,
PRIMARY KEY (user_id)
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
</code>```

Primary key should be user_id instead of id in your case.
I hope, this will help you.

Title: ERROR 1046:No database selected

Body:
I would  like  to create a SQL database  but this error occurs I do not know why. Can somebody  help  me?

My SQL statement:

CREATE TABLE 'users'(
    'user_id' int (11) NOT NULL AUTO_INCREMENT,
    'username' varchar (255) DEFAULT NULL,
    'password' varchar (255) DEFAULT NULL,
    PRIMARY KEY ('user_id')
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

Can somebody help me?

Body:
Select the database first using:
USE database_name

If you haven't created database, create it by using :

CREATE DATABASE database_name

and select database using :

USE database_name

Now, you can create table as follows :

CREATE TABLE users(
user_id int (11) NOT NULL AUTO_INCREMENT,
username varchar (255) DEFAULT NULL,
password varchar (255) DEFAULT NULL,
PRIMARY KEY (user_id)
)ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

Primary key should be user_id instead of id in your case.
I hope, this will help you.


问:
How to use consul to manage different type of servers
I want to register servers of different project on one consul server.
Do we have a method to filter consul members on basis of their "type" or "project"? How do I segregate or filter the result?

答:
You should setup you consul servers: at least change default ports.

For cli commands you can specify -http-addr. So, for example, with default settings consul members is the same as consul members -http-addr=http://127.0.0.1:8500.


问:
How to determine in Windows whether file exists, does not exist or this can't be known (using c)
I have to clean up from a list of files the ones that do not exist any more. The ones whose status is indeterminable should be given a warning about but left on the list. Sounds simple enough. However, the c functions I tried to solve this with don't seem to give a reliable answer between whether the file really does not exist or it e.g. resides on a network share that is at the moment inaccessible (e.g. due to network problems).

stat function sets errno to ENOENT if the file can't be reached, so that is indistinguishable from the file not actually existing.

FindFirstFile in some cases sets last error (obtainable with GetLastError()) to ERROR_PATH_NOT_FOUND when the network share can't be reached.
Yes, I know FindFirstFile is for reading directories, but I thought I could deduce what I need to know by the error code it sets.

Also GetFileAttributes seems to in some cases set last error to ERROR_PATH_NOT_FOUND in case the network drive is unreachable.

答: CreateFile does set LastError to 0x35 (network path not found) if network share is not availiable and to 0x2 (system cannot find the path specified) if share is availiable, but file does not exist


问:
How to get past "N" seconds data while processing current batch in Dstream
I am new to the spark world.
Having a weather  streaming applications receiving time based dstream (in form of tuples) of below type:

```<code>{
  timestamp,
  { v1, v2, v3}
}
</code>```

where v1=temp, v2=humidity, v3=windrate

Example: { 01/05/2016 08:01:00,  { 25,4.2,10}}

Now my requirement is to check temperature for every incoming record and if it crosses 35 then stop processing and dump last 10 mins data to hdfs for further investigation.

答:
If the goal is to save all data received the last 10 minutes when you get a temp higher than 35 you have to follow these steps:

Create a dstream with a window value of 10 minutes and a slide duration of 1 seconds for instance: dstream.window(Minutes(10),Seconds(1)).

You will check the temperature received every seconds and if temp > 30, store the dstream on HDFS (containing all data received from batch_time - 10 minutes to batch_time).

Body:
I am new to the spark world.
Having a weather  streaming applications receiving time based dstream (in form of tuples) of below type:

{
  timestamp,
  { v1, v2, v3}
}

where v1=temp, v2=humidity, v3=windrate

Example: { 01/05/2016 08:01:00,  { 25,4.2,10}}

Now my requirement is to check temperature for every incoming record and if it crosses 35 then stop processing and dump last 10 mins data to hdfs for further investigation.


问:
Why CSS and Bootstrap elements disappear with node express server?
I firstly made a basic node server like this:

```<code>  var connect = require('connect');

  var serveStatic = require('serve-static');
  connect().use(serveStatic(__dirname)).listen(8080, function() {
    console.log('Server running on 8080...');
  });
</code>```

Then I replaced it with an express server like this:

```<code>   var express = require("express");
   var app     = express();
   var path    = require("path");

   app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));

   });

   app.use(express.static("public"));

   app.listen(8080);

   console.log("Running at Port 8080");
</code>```

With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?

答:
You are not serving static files.

```<code>app.use(express.static("public"))
</code>```

This would serve all files from /public directly on the root of your server /. If you want to serve them at /static you need to modify the code a bit.

```<code>app.use("/static", express.static("public"))
</code>```

Example

File Structure

```<code>├── node_modules
├── package.json
├── public
| └ style.css
|
└── server.js
</code>```

server.js

```<code>var express = require("express")
var app = express()

app.use(express.static("public"))

app.listen(3333)
</code>```

After running server.js you should be able to access http://localhost:3333/style.css (and every other file in the /public directory)

Body:
I firstly made a basic node server like this:

  var connect = require('connect');

  var serveStatic = require('serve-static');
  connect().use(serveStatic(__dirname)).listen(8080, function() {
    console.log('Server running on 8080...');
  });

Then I replaced it with an express server like this:

   var express = require("express");
   var app     = express();
   var path    = require("path");

   app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));

   });

   app.use(express.static("public"));

   app.listen(8080);

   console.log("Running at Port 8080");

With the first one, everything worked fine. CSS, JQuery, images etc..., but with the second one, some of my style elements totally disappeared and it can't reach the pictures on the site. What did I miss? How can I solve it?

Body:
You are not serving static files.

app.use(express.static("public"))

This would serve all files from /public directly on the root of your server /. If you want to serve them at /static you need to modify the code a bit.

app.use("/static", express.static("public"))

Example

File Structure

├── node_modules
├── package.json
├── public
| └ style.css
|
└── server.js

server.js

var express = require("express")
var app = express()

app.use(express.static("public"))

app.listen(3333)

After running server.js you should be able to access http://localhost:3333/style.css (and every other file in the /public directory)


问:
QListWidget item index selected by default
I have a QListWidget which has some item, and I have "Remove" button on my form which actually removes item from list(array object) and from QlistWidget.

"Add" button for add item into array obj and show it to QlistWidget and the problem is when i press remove without selecting any item from list, it takes the item at the lats index by default and remove it, and the QlistWidget didn't refresh when i press remove button.

i confused how to explain it, need to try the code first

this is my code:

```<code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from netmiko import ConnectHandler
from paramiko import SSHException
import jtextfsm as textfsm
import ipaddress
import time

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.device_list = [] #object array
        self.setWindowTitle("Network Automation")
        ############################# Input IP

        # Device Type
        lb_device_list = QLabel(self)
        lb_device_list.setText('Device Type')
        self.cb_device_list = QComboBox(self)
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        # Ip Device
        lb_ip = QLabel(self)
        lb_ip.setText('IP Address')
        self.le_ip = QLineEdit(self)
        self.le_ip.setText('')
        self.le_ip.setPlaceholderText('Input Device IP')
        self.le_ip.setFixedWidth(150)

        # username
        lb_username = QLabel(self)
        self.le_username = QLineEdit(self)
        lb_username.setText('Username')
        self.le_username.setText('')
        self.le_username.setPlaceholderText('Input Username')
        self.le_username.setFixedWidth(150)

        # password
        lb_password = QLabel(self)
        self.le_password = QLineEdit(self)
        lb_password.setText('Password')
        self.le_password.setText('')
        self.le_password.setPlaceholderText('Input Password')
        self.le_password.setFixedWidth(150)

        # Privilage Password
        lb_enable = QLabel(self)
        lb_enable.setText('Privilege Mode Password')
        self.le_enable = QLineEdit(self)
        self.le_enable.setText('')
        self.le_enable.setPlaceholderText('Input Enable Password')
        self.le_enable.setFixedWidth(150)

        #button generate and add
        btgenerate = QPushButton(self)
        btgenerate.setText('Generate')
        btgenerate.setFixedWidth(70)
        btadd = QPushButton(self)
        btadd.setText('Add')

        #button delete
        btdel = QPushButton(self)
        btdel.setFixedWidth(70)
        btdel.setText('Remove')

        # line
        line = QFrame(self)
        line.setFrameShape(QFrame.VLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setLineWidth(3)

        ########################### Layout Ip Device List

        lb3 = QLabel(self)
        lb3.setText('IP Device List')
        self.ip_device_list = QListWidget(self)
        self.ip_device_list.setFixedWidth(150)
        #self.combobox_ip_list = QComboBox(self)
        #self.combobox_ip_list.setFixedWidth(170)

        ############################## SubLayout and Layout
        hblayout = QHBoxLayout()
        hblayout.addWidget(btgenerate)
        hblayout.addWidget(btadd)

        sublayout = QVBoxLayout()
        sublayout.addWidget(lb_device_list)
        sublayout.addWidget(self.cb_device_list)
        sublayout.addWidget(lb_ip)
        sublayout.addWidget(self.le_ip)
        sublayout.addWidget(lb_username)
        sublayout.addWidget(self.le_username)
        sublayout.addWidget(lb_password)
        sublayout.addWidget(self.le_password)
        sublayout.addWidget(lb_enable)
        sublayout.addWidget(self.le_enable)
        sublayout.addLayout(hblayout)

        sublayout2 = QVBoxLayout()
        sublayout2.addWidget(lb3)
        sublayout2.addWidget(self.ip_device_list)
        #sublayout2.addWidget(self.combobox_ip_list)
        sublayout2.addWidget(btdel)
        sublayout2.addStretch(1)

        layout = QGridLayout(self)
        layout.addLayout(sublayout,0,0)
        layout.addWidget(line,0,1)
        layout.addLayout(sublayout2,0,2)

        btadd.clicked.connect(self.addDevice)

        btdel.clicked.connect(self.remove)

    ####################----------- AddDevice
    def addDevice(self):
        try:
            ip = self.le_ip.text()
            ipaddress.ip_address(ip)
            device_type = str(self.cb_device_list.currentText())
            username = self.le_username.text()
            password = self.le_password.text()
            secret = self.le_enable.text()
            command = 'show tech'
            self.device_list.append(MyClass(device_type, ip, username, password, secret, command))

            # self.combobox_ip_list.addItem(ip)# Add Ip to ComboBox
            self.ip_device_list.addItem(ip)

            self.le_ip.clear()
            self.le_username.clear()
            self.le_password.clear()
            self.le_enable.clear()
            #self.ip_device_list.clear()
            for list in self.device_list:
                print(list.ip,list.device_type)
        except ValueError:
            print("insert you're ip correctly")

    def remove(self):
        index = self.ip_device_list.currentRow()
        self.ip_device_list.takeItem(index)
        del self.device_list[index] #dremove data from list/array

class MyClass(object):
    def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None):
        self.device_type = device_type
        self.ip = ip
        self.username = username
        self.password = password
        self.secret = secret
        self.command = command

##################################
app = QApplication(sys.argv)
QApplication.processEvents()
app.setStyle('cleanlooks')
window = Widget()
window.show()
sys.exit(app.exec_())
</code>```

答:
The reason is that the currentRow method will return -1 if no selection is made. -1 has a very specific meaning in Python indexing. It means last element (-2 would mean element prior to last). So to solve your problem just add the following to your code:

```<code>def remove(self):
    index = self.ip_device_list.currentRow()
    if index != -1:
        self.ip_device_list.takeItem(index)
        del self.device_list[index]
</code>```

Body:
I have a QListWidget which has some item, and I have "Remove" button on my form which actually removes item from list(array object) and from QlistWidget.

"Add" button for add item into array obj and show it to QlistWidget and the problem is when i press remove without selecting any item from list, it takes the item at the lats index by default and remove it, and the QlistWidget didn't refresh when i press remove button.

i confused how to explain it, need to try the code first

this is my code:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from netmiko import ConnectHandler
from paramiko import SSHException
import jtextfsm as textfsm
import ipaddress
import time

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent=parent)
        self.device_list = [] #object array
        self.setWindowTitle("Network Automation")
        ############################# Input IP

        # Device Type
        lb_device_list = QLabel(self)
        lb_device_list.setText('Device Type')
        self.cb_device_list = QComboBox(self)
        self.cb_device_list.addItem('cisco_ios')
        self.cb_device_list.addItem('cisco_s300')

        # Ip Device
        lb_ip = QLabel(self)
        lb_ip.setText('IP Address')
        self.le_ip = QLineEdit(self)
        self.le_ip.setText('')
        self.le_ip.setPlaceholderText('Input Device IP')
        self.le_ip.setFixedWidth(150)

        # username
        lb_username = QLabel(self)
        self.le_username = QLineEdit(self)
        lb_username.setText('Username')
        self.le_username.setText('')
        self.le_username.setPlaceholderText('Input Username')
        self.le_username.setFixedWidth(150)

        # password
        lb_password = QLabel(self)
        self.le_password = QLineEdit(self)
        lb_password.setText('Password')
        self.le_password.setText('')
        self.le_password.setPlaceholderText('Input Password')
        self.le_password.setFixedWidth(150)

        # Privilage Password
        lb_enable = QLabel(self)
        lb_enable.setText('Privilege Mode Password')
        self.le_enable = QLineEdit(self)
        self.le_enable.setText('')
        self.le_enable.setPlaceholderText('Input Enable Password')
        self.le_enable.setFixedWidth(150)

        #button generate and add
        btgenerate = QPushButton(self)
        btgenerate.setText('Generate')
        btgenerate.setFixedWidth(70)
        btadd = QPushButton(self)
        btadd.setText('Add')

        #button delete
        btdel = QPushButton(self)
        btdel.setFixedWidth(70)
        btdel.setText('Remove')

        # line
        line = QFrame(self)
        line.setFrameShape(QFrame.VLine)
        line.setFrameShadow(QFrame.Sunken)
        line.setLineWidth(3)

        ########################### Layout Ip Device List

        lb3 = QLabel(self)
        lb3.setText('IP Device List')
        self.ip_device_list = QListWidget(self)
        self.ip_device_list.setFixedWidth(150)
        #self.combobox_ip_list = QComboBox(self)
        #self.combobox_ip_list.setFixedWidth(170)

        ############################## SubLayout and Layout
        hblayout = QHBoxLayout()
        hblayout.addWidget(btgenerate)
        hblayout.addWidget(btadd)

        sublayout = QVBoxLayout()
        sublayout.addWidget(lb_device_list)
        sublayout.addWidget(self.cb_device_list)
        sublayout.addWidget(lb_ip)
        sublayout.addWidget(self.le_ip)
        sublayout.addWidget(lb_username)
        sublayout.addWidget(self.le_username)
        sublayout.addWidget(lb_password)
        sublayout.addWidget(self.le_password)
        sublayout.addWidget(lb_enable)
        sublayout.addWidget(self.le_enable)
        sublayout.addLayout(hblayout)

        sublayout2 = QVBoxLayout()
        sublayout2.addWidget(lb3)
        sublayout2.addWidget(self.ip_device_list)
        #sublayout2.addWidget(self.combobox_ip_list)
        sublayout2.addWidget(btdel)
        sublayout2.addStretch(1)

        layout = QGridLayout(self)
        layout.addLayout(sublayout,0,0)
        layout.addWidget(line,0,1)
        layout.addLayout(sublayout2,0,2)

        btadd.clicked.connect(self.addDevice)

        btdel.clicked.connect(self.remove)

    ####################----------- AddDevice
    def addDevice(self):
        try:
            ip = self.le_ip.text()
            ipaddress.ip_address(ip)
            device_type = str(self.cb_device_list.currentText())
            username = self.le_username.text()
            password = self.le_password.text()
            secret = self.le_enable.text()
            command = 'show tech'
            self.device_list.append(MyClass(device_type, ip, username, password, secret, command))

            # self.combobox_ip_list.addItem(ip)# Add Ip to ComboBox
            self.ip_device_list.addItem(ip)

            self.le_ip.clear()
            self.le_username.clear()
            self.le_password.clear()
            self.le_enable.clear()
            #self.ip_device_list.clear()
            for list in self.device_list:
                print(list.ip,list.device_type)
        except ValueError:
            print("insert you're ip correctly")

    def remove(self):
        index = self.ip_device_list.currentRow()
        self.ip_device_list.takeItem(index)
        del self.device_list[index] #dremove data from list/array

class MyClass(object):
    def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None):
        self.device_type = device_type
        self.ip = ip
        self.username = username
        self.password = password
        self.secret = secret
        self.command = command

##################################
app = QApplication(sys.argv)
QApplication.processEvents()
app.setStyle('cleanlooks')
window = Widget()
window.show()
sys.exit(app.exec_())

Body:
The reason is that the currentRow method will return -1 if no selection is made. -1 has a very specific meaning in Python indexing. It means last element (-2 would mean element prior to last). So to solve your problem just add the following to your code:

def remove(self):
    index = self.ip_device_list.currentRow()
    if index != -1:
        self.ip_device_list.takeItem(index)
        del self.device_list[index]


问:
Bearing and location
Got some strange thing here while doing task of map rotation around user current location marker. So what i am trying to do is like google maps application on second "Current location" tap. Marker must keep its position at map center while map is moving.

As i understood need to use bearing value to update camera position object on GoogleMap v2.

```<code>CameraUpdate cameraUpdatePos;
            CameraPosition.Builder currentPlaceBuilder = new CameraPosition.Builder().target(loc);
            if (location.hasBearing())
                currentPlaceBuilder.bearing(location.getBearing());
            cameraUpdatePos = CameraUpdateFactory.newCameraPosition(currentPlaceBuilder.build());
            map.animateCamera(cameraUpdatePos);
</code>```

The bug is about every location returns every time false hasBearing() call result and bearing 0.0 with my app. But google maps app shows me my direction at this time properly.

I am using service

```<code>LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        googleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(gmsCallbacks)
                .addOnConnectionFailedListener(gmsCallbacks)
                .addApi(LocationServices.API)
                .build();

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(25 * 1000)
                .setFastestInterval(5 * 1000)
                .setSmallestDisplacement(1);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .setAlwaysShow(true);`
</code>```

and method onconnected

```<code>`@Override
        public void onConnected(@Nullable Bundle bundle) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                return;
            Log.i(TAG, "Connected");
            location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, gmsCallbacks);
            if (locationChangeCallback != null)
                locationChangeCallback.onLocationChanged(location);
        }`
</code>```

Does anybody knows how google map made their bearing calculation for auto orientation map mode ?
Maybe someone has such situation and could help me with advice. Thanks.

答:
May this helps you

```<code>public class GoogleApiActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener , {
SupportMapFragment fragment;
GoogleMap googleMap;
GoogleApiClient googleApiClient;
Marker marker;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google_api);
    mapLoading();
    googleClientApi();

}

private void mapLoading(){
    FragmentManager manager = getSupportFragmentManager();
    fragment = (SupportMapFragment) manager.findFragmentById(R.id.map_space);
    if (fragment == null)
    {
        fragment = SupportMapFragment.newInstance();
        manager.beginTransaction().replace(R.id.map_space, fragment).commit();
    }
}

@Override
protected void onResume(){
    super.onResume();
    if (googleMap == null){
        fragment.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap){
    this.googleMap = googleMap;
    Toast.makeText(this, "Map Ready CallBack", Toast.LENGTH_SHORT).show();

    this.googleMap.setTrafficEnabled(true);
    this.googleMap.setIndoorEnabled(true);
    this.googleMap.setBuildingsEnabled(true);
    this.googleMap.getUiSettings().setZoomControlsEnabled(true);
    this.googleMap.setOnCameraChangeListener(this);
}

private void googleClientApi(){
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(@Nullable Bundle bundle){
    LocationRequest locationRequest = createLocationRequest();
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, createLocationRequest(),GoogleApiActivity.this);
}

@Override
public void onConnectionSuspended(int i){

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult){

}

public LocationRequest createLocationRequest()
{
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(0);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setSmallestDisplacement(0);
    return locationRequest;
}

@Override
protected void onStart()
{
    super.onStart();
    if (googleApiClient != null)
    {
        googleApiClient.connect();
    }
}

@Override
protected void onStop()
{
    super.onStop();
    if (googleApiClient != null)
    {
        googleApiClient.disconnect();
    }
}

@Override
public void onLocationChanged(Location location){
    Toast.makeText(this, "Inside onLocationChanged  "+location.getAccuracy(), Toast.LENGTH_SHORT).show();
    if (location != null)
    {
        if (marker == null){
            marker = googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(location.getLatitude(), location.getLongitude()))
                    .title("My Location"));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 18));
        }else{
            marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
            updateCameraBearing(googleMap, location.getBearing(),location);
        }
    }    }

private void updateCameraBearing(GoogleMap googleMap, float bearing, Location location) {
    if ( googleMap == null) return;
    CameraPosition camPos = CameraPosition
            .builder(
                    googleMap.getCameraPosition() // current Camera
            ).target(new LatLng(location.getLatitude(),location.getLongitude()))
            .bearing(bearing)
            .build();
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
}
</code>```

}

Title: Bearing and location

Body:
Got some strange thing here while doing task of map rotation around user current location marker. So what i am trying to do is like google maps application on second "Current location" tap. Marker must keep its position at map center while map is moving.

As i understood need to use bearing value to update camera position object on GoogleMap v2.

CameraUpdate cameraUpdatePos;
            CameraPosition.Builder currentPlaceBuilder = new CameraPosition.Builder().target(loc);
            if (location.hasBearing())
                currentPlaceBuilder.bearing(location.getBearing());
            cameraUpdatePos = CameraUpdateFactory.newCameraPosition(currentPlaceBuilder.build());
            map.animateCamera(cameraUpdatePos);

The bug is about every location returns every time false hasBearing() call result and bearing 0.0 with my app. But google maps app shows me my direction at this time properly.

I am using service

LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        googleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(gmsCallbacks)
                .addOnConnectionFailedListener(gmsCallbacks)
                .addApi(LocationServices.API)
                .build();

        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(25 * 1000)
                .setFastestInterval(5 * 1000)
                .setSmallestDisplacement(1);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest)
                .setAlwaysShow(true);`

and method onconnected

`@Override
        public void onConnected(@Nullable Bundle bundle) {
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                return;
            Log.i(TAG, "Connected");
            location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, gmsCallbacks);
            if (locationChangeCallback != null)
                locationChangeCallback.onLocationChanged(location);
        }`

Does anybody knows how google map made their bearing calculation for auto orientation map mode ?
Maybe someone has such situation and could help me with advice. Thanks.

Body:
May this helps you

public class GoogleApiActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener , {
SupportMapFragment fragment;
GoogleMap googleMap;
GoogleApiClient googleApiClient;
Marker marker;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_google_api);
    mapLoading();
    googleClientApi();

}

private void mapLoading(){
    FragmentManager manager = getSupportFragmentManager();
    fragment = (SupportMapFragment) manager.findFragmentById(R.id.map_space);
    if (fragment == null)
    {
        fragment = SupportMapFragment.newInstance();
        manager.beginTransaction().replace(R.id.map_space, fragment).commit();
    }
}

@Override
protected void onResume(){
    super.onResume();
    if (googleMap == null){
        fragment.getMapAsync(this);
    }
}

@Override
public void onMapReady(GoogleMap googleMap){
    this.googleMap = googleMap;
    Toast.makeText(this, "Map Ready CallBack", Toast.LENGTH_SHORT).show();

    this.googleMap.setTrafficEnabled(true);
    this.googleMap.setIndoorEnabled(true);
    this.googleMap.setBuildingsEnabled(true);
    this.googleMap.getUiSettings().setZoomControlsEnabled(true);
    this.googleMap.setOnCameraChangeListener(this);
}

private void googleClientApi(){
    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

@Override
public void onConnected(@Nullable Bundle bundle){
    LocationRequest locationRequest = createLocationRequest();
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, createLocationRequest(),GoogleApiActivity.this);
}

@Override
public void onConnectionSuspended(int i){

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult){

}

public LocationRequest createLocationRequest()
{
    LocationRequest locationRequest = new LocationRequest();
    locationRequest.setInterval(0);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setSmallestDisplacement(0);
    return locationRequest;
}

@Override
protected void onStart()
{
    super.onStart();
    if (googleApiClient != null)
    {
        googleApiClient.connect();
    }
}

@Override
protected void onStop()
{
    super.onStop();
    if (googleApiClient != null)
    {
        googleApiClient.disconnect();
    }
}

@Override
public void onLocationChanged(Location location){
    Toast.makeText(this, "Inside onLocationChanged  "+location.getAccuracy(), Toast.LENGTH_SHORT).show();
    if (location != null)
    {
        if (marker == null){
            marker = googleMap.addMarker(new MarkerOptions()
                    .position(new LatLng(location.getLatitude(), location.getLongitude()))
                    .title("My Location"));
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 18));
        }else{
            marker.setPosition(new LatLng(location.getLatitude(),location.getLongitude()));
            updateCameraBearing(googleMap, location.getBearing(),location);
        }
    }    }

private void updateCameraBearing(GoogleMap googleMap, float bearing, Location location) {
    if ( googleMap == null) return;
    CameraPosition camPos = CameraPosition
            .builder(
                    googleMap.getCameraPosition() // current Camera
            ).target(new LatLng(location.getLatitude(),location.getLongitude()))
            .bearing(bearing)
            .build();
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
}

}