问:
C# DataGridView how to illuminate current List<Action>
I would like to highlight the method that is being implemented  on datagridview right now.

This is List :

```<code>  public List<Action> functions = new List<Action>();
</code>```

And inside i have a methods.  by adding for example.

```<code>functions.Add(waypoint1);
</code>```

My datagridview after add method look like :

And i just want hightlight current waypoint.

to start list I use:

```<code>foreach (Action func in functions)
{
    func();
}
</code>```

For example when func() number 2 is currenly  activated just highlight 2nd row.
When func() number 3 is currenly  activated just highlight 3rd row. I searched forum but don't find solution.Please be patient for newbie. Thank you.

EDIT 1 :
Added code of foreach loop in backgroundworker as you want.

```<code>private void DoWork_backgroundworker(object sender, DoWorkEventArgs e)
{
    while (true)
    {
        foreach (Action func in functions)
        {
            func();
        }
    }
}
</code>```

And button to start :

```<code>private void metroButton7_Click(object sender, EventArgs e)
{
    DoWork_backgroundworker.RunWorkerAsync();
}
</code>```

答:
If it is ok for you that you use the Selected property for the highlighting you can use a normal for-loop (which will give you an indexer) and index the rows that belong to the items. Set simply the Selected property of that Row to true:

```<code>for (int i = 0; i < functions.Count; i++)
{
    //select the row before action is started
    dataGridView1.Rows[i].Selected = true;

    // execute your action
    functions[i]();

    //unselect the row when job is finished
    dataGridView1.Rows[i].Selected = false;

}
</code>```

EDIT:

If you want to change the selection/highlight colour use the dataGridView1.RowsDefaultCellStyle.SelectionBackColor property. Put this line before the for-loop:

```<code>dataGridView1.RowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Black;
</code>```

Body:
I would like to highlight the method that is being implemented  on datagridview right now.

This is List :

  public List<Action> functions = new List<Action>();

And inside i have a methods.  by adding for example.

functions.Add(waypoint1);

My datagridview after add method look like :

And i just want hightlight current waypoint.

to start list I use:

foreach (Action func in functions)
{
    func();
}

For example when func() number 2 is currenly  activated just highlight 2nd row.
When func() number 3 is currenly  activated just highlight 3rd row. I searched forum but don't find solution.Please be patient for newbie. Thank you.

EDIT 1 :
Added code of foreach loop in backgroundworker as you want.

private void DoWork_backgroundworker(object sender, DoWorkEventArgs e)
{
    while (true)
    {
        foreach (Action func in functions)
        {
            func();
        }
    }
}

And button to start :

private void metroButton7_Click(object sender, EventArgs e)
{
    DoWork_backgroundworker.RunWorkerAsync();
}

Body:
If it is ok for you that you use the Selected property for the highlighting you can use a normal for-loop (which will give you an indexer) and index the rows that belong to the items. Set simply the Selected property of that Row to true:

for (int i = 0; i < functions.Count; i++)
{
    //select the row before action is started
    dataGridView1.Rows[i].Selected = true;

    // execute your action
    functions[i]();

    //unselect the row when job is finished
    dataGridView1.Rows[i].Selected = false;

}

EDIT:

If you want to change the selection/highlight colour use the dataGridView1.RowsDefaultCellStyle.SelectionBackColor property. Put this line before the for-loop:

dataGridView1.RowsDefaultCellStyle.SelectionBackColor = System.Drawing.Color.Black;


来源: stackexchange

问:
Load data in a Global Temporary Table
I have two different Oracle sessions ("session A" and "session B") on the same Oracle user.

A Global Temporary Table is populated, in "session A", with about 320,000 records.

How can I quickly insert the same 320,000 records in the global temporary table of the "session B"?

Thank you in advance for your kind suggestions!

EDIT: I have forgotten to specify that I am allowed to create ONLY GLOBAL TEMPORARY TABLES.

EDIT: I have forgotten to specify that I am not allowed to create database links

答:
DBMS_PIPE is the 'classic' mechanism for pushing information from one session to another. Session A would have to push data into the pipe and session B would have to pull it.

But generally the idea of databases is that sessions are independent and any commonality is in the preserved data. Going against this suggests you are using the wrong tool.

ContentLicense: CC BY-SA 2.5

Title: Load data in a Global Temporary Table


问:
CollectionView as a Subview in Swift
CollectionView as a Subview in Swift

I am try to insert a very simple collectionView as a Subview but cannot get a right frame. What am I doing wrong? Could you help me please?

Here is my code:

```<code>import UIKit

class ViewController: UIViewController {

var collectionView: UICollectionView!

@IBOutlet weak var testView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidLayoutSubviews() {

    setupCollectionView()

}

func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: testView.frame, collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)

}
</code>```

}

答:
```<code>func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, testView.frame.size.width, height: testView.frame.size.height), collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)
    testView.clipsToBounds=true

    }
</code>```

<p>Problem is "testView.frame" that. testview frame x and y point not 0 </p>

ContentLicense: CC BY-SA 3.0

Title: CollectionView as a Subview in Swift

Body:
CollectionView as a Subview in Swift

I am try to insert a very simple collectionView as a Subview but cannot get a right frame. What am I doing wrong? Could you help me please?

Here is my code:

import UIKit

class ViewController: UIViewController {

var collectionView: UICollectionView!

@IBOutlet weak var testView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidLayoutSubviews() {

    setupCollectionView()

}

func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: testView.frame, collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)

}

}

Body:
func setupCollectionView() {

    let layout = UICollectionViewFlowLayout()
    collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, testView.frame.size.width, height: testView.frame.size.height), collectionViewLayout: layout)
    collectionView.backgroundColor = UIColor.green
    testView.addSubview(collectionView)
    testView.clipsToBounds=true

    }

Problem is "testView.frame" that. testview frame x and y point not 0


问:
Add chart using chart.js in codeigniter
I am trying to display a simple chart on my view (Codeigniter), however it is not appearing.

Can someone tell me what am I missing?

Appreciate your help with this.

```<code><div class="container">
  <h2>This is a sample — Line Chart</h2>
  <div>
      <canvas id="myChart"></canvas>
  </div>
 </div>

 <script type="text/javascript" src="http://www.chartjs.org/assets/Chart.js">
var ctx = document.getElementById("myChart").getContext("2d");

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3]
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
</code>```

答:
I have fixed my problem. I just changes the source on my script tag.
See the updated code below.</p>

```<code><div class="container">
    <h2>This is a sample — Line Chart</h2>
    <div>
        <canvas id="myChart"></canvas>
    </div>
</div>

 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
    var ctx = document.getElementById("myChart").getContext("2d");

    var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                  labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                  datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3]
                             }]
                  },
            options: {
            scales: {
                  yAxes: [{
                        ticks: {
                             beginAtZero:true
                               }
                          }]
                    }
           }
       });
  </script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Add chart using chart.js in codeigniter

Body:
I am trying to display a simple chart on my view (Codeigniter), however it is not appearing.

Can someone tell me what am I missing?

Appreciate your help with this.

This is a sample — Line Chart

      <canvas id="myChart"></canvas>

Body:
I have fixed my problem. I just changes the source on my script tag.
See the updated code below.

<div class="container">
    <h2>This is a sample — Line Chart</h2>
    <div>
        <canvas id="myChart"></canvas>
    </div>
</div>

 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js">
    var ctx = document.getElementById("myChart").getContext("2d");

    var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                  labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                  datasets: [{
                        label: '# of Votes',
                        data: [12, 19, 3, 5, 2, 3]
                             }]
                  },
            options: {
            scales: {
                  yAxes: [{
                        ticks: {
                             beginAtZero:true
                               }
                          }]
                    }
           }
       });
  </script>


问:
How do you update float data type in SQL column to hold numbers with upto 20 scale
I have a SQL table with a column having float data type with default precision.
I want this column to hold data with upto 20 digits after the decimal point.

How do I update existing column to do this?

答:
SQL Server: The literal answer here would be "you cannot". If you look at the documentation, you'll see that the float type only supports two precisions - either 7 or 15 digits.

Answers provided so far all seem to be advocating a switch to a different datatype (decimal) but don't highlight that this comes with its own drawbacks - notably that the decimal type supports a far smaller range. float can support a range from - 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to 1.79E+308 whereas decimal only supports a range of ~ -10^38 to 10^38 (and that, only if you are using a 0 scale). If using a scale of 20 then the range is limited to ~ -10^18 to 10^18.


问:
Angular - how to concat var name
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

```<code><div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc(1)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe1 = false;
    $scope.myFunc = function(x) {
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope.nametocng = !$scope.nametocng;
    }
});
</script>
</code>```

答:
If you have a dynamic variable name, you need to access via [] syntax. It will evaluate the variable's value and use that value as a property name.

<button ng-click="myFunc(1)">Click Me!</button>

Menu:

Pizza

Pasta

Pesce

```

Title: Angular - how to concat var name

Body:
I just started to learn Angular, and I tried to make concat var name so I can control it dynamically.

This is what I tried -

<button ng-click="myFunc(1)">Click Me!</button>

Menu:

Pizza

Pasta

Pesce

Body:
If you have a dynamic variable name, you need to access via [] syntax. It will evaluate the variable's value and use that value as a property name.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="myFunc(1)">Click Me!</button>

<div ng-show="showMe1">
    <h1>Menu:</h1>
    <div>Pizza</div>
    <div>Pasta</div>
    <div>Pesce</div>
</div>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showMe1 = false;
    $scope.myFunc = function(x) {
        var nametocng = 'showMe'+x;
        //var nametocng = $parse("showMe"+x);  // - I tried this also
        $scope[nametocng] = !$scope[nametocng];
    }
});
</script>


问:
How to prevent uncheck (unselect) gridview item in windows Universal app
In Windows Universal app, I have a pivot table which every tab content have gridview, gridview items are multi select mode,

What I want that if any one item once checked (selected), then it unable to unselect(uncheck)

```<code><Grid DataContext="{Binding Path=Value}">
                            <GridView x:Name="categoryItemsGV"
                                Margin="5,5,0,0"
                                SizeChanged="categoryItemsGV_SizeChanged"
                                IsItemClickEnabled="True"
                                ItemClick="categoryItemsGV_ItemClick"
                                SelectionMode="Single"
                                ItemsSource="{Binding}">
                                <GridView.ItemContainerStyle>
                                    <Style TargetType="GridViewItem">
                                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                                        <!--<Setter Property="VerticalContentAlignment" Value="Center"/>-->
                                    </Style>
                                </GridView.ItemContainerStyle>
                                <GridView.ItemTemplate>
                                    <DataTemplate>
                                        <Grid Width="195" Height="43" Margin="3">
                                            <StackPanel Width="193" Height="40"  Background="Gray" Opacity="0.5" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
                                            <StackPanel Orientation="Horizontal" Width="193" Height="40" Padding="7,7,0,0" Background="#FDFCC2"  HorizontalAlignment="Left" VerticalAlignment="Top">
                                                <TextBlock  Text="{Binding ProductOptionLineName}" FontSize="18" MaxLines="1" TextTrimming="CharacterEllipsis"   Visibility="{Binding Converter={StaticResource langToVisibilityConverter}, ConverterParameter='CH', Mode=OneWay}">
                                                </TextBlock>
                                                <TextBlock  Text="{Binding ProductOptionLineNameEn}" FontSize="18" MaxLines="1" TextTrimming="CharacterEllipsis"  Visibility="{Binding Converter={StaticResource langToVisibilityConverter}, ConverterParameter='EN', Mode=OneWay}"/>
                                                <TextBlock Text="{Binding ExtraPriceString}" FontSize="18" Margin="2,0,0,0"></TextBlock>
                                            </StackPanel>
                                        </Grid>
                                    </DataTemplate>
                                </GridView.ItemTemplate>
                            </GridView>
                        </Grid>

  private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
       }
</code>```

答:
If we want to keep item selected as it was already selected, use below approach.

```<code> private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
                        GridView gv = sender as GridView;
                        gv.SelectedItems.Remove(item);
       }
</code>```

and if we want to keep item deselect on click (prevent deselected) for validation purpose. used below approach.

```<code>private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
                            await   _viewModel.DialogService("FirstRequireMinOption", "", true);
                            GridView gv = sender as GridView;
                            gv.SelectedItems.Add(item);
       }
</code>```

Body:
In Windows Universal app, I have a pivot table which every tab content have gridview, gridview items are multi select mode,

What I want that if any one item once checked (selected), then it unable to unselect(uncheck)

<Grid DataContext="{Binding Path=Value}">
                            <GridView x:Name="categoryItemsGV"
                                Margin="5,5,0,0"
                                SizeChanged="categoryItemsGV_SizeChanged"
                                IsItemClickEnabled="True"
                                ItemClick="categoryItemsGV_ItemClick"
                                SelectionMode="Single"
                                ItemsSource="{Binding}">
                                <GridView.ItemContainerStyle>

                                </GridView.ItemContainerStyle>
                                <GridView.ItemTemplate>
                                    <DataTemplate>
                                        <Grid Width="195" Height="43" Margin="3">
                                            <StackPanel Width="193" Height="40"  Background="Gray" Opacity="0.5" HorizontalAlignment="Right" VerticalAlignment="Bottom" />
                                            <StackPanel Orientation="Horizontal" Width="193" Height="40" Padding="7,7,0,0" Background="#FDFCC2"  HorizontalAlignment="Left" VerticalAlignment="Top">
                                                <TextBlock  Text="{Binding ProductOptionLineName}" FontSize="18" MaxLines="1" TextTrimming="CharacterEllipsis"   Visibility="{Binding Converter={StaticResource langToVisibilityConverter}, ConverterParameter='CH', Mode=OneWay}">
                                                </TextBlock>
                                                <TextBlock  Text="{Binding ProductOptionLineNameEn}" FontSize="18" MaxLines="1" TextTrimming="CharacterEllipsis"  Visibility="{Binding Converter={StaticResource langToVisibilityConverter}, ConverterParameter='EN', Mode=OneWay}"/>
                                                <TextBlock Text="{Binding ExtraPriceString}" FontSize="18" Margin="2,0,0,0"></TextBlock>
                                            </StackPanel>
                                        </Grid>
                                    </DataTemplate>
                                </GridView.ItemTemplate>
                            </GridView>
                        </Grid>

  private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
       }

Body:
If we want to keep item selected as it was already selected, use below approach.

 private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
                        GridView gv = sender as GridView;
                        gv.SelectedItems.Remove(item);
       }

and if we want to keep item deselect on click (prevent deselected) for validation purpose. used below approach.

private async void categoryItemsGV_ItemClick(object sender, ItemClickEventArgs e)
        {

                var item = e.ClickedItem as ProductOptionLineModel;
                            await   _viewModel.DialogService("FirstRequireMinOption", "", true);
                            GridView gv = sender as GridView;
                            gv.SelectedItems.Add(item);
       }


问:
Difference in time between records
I have a table that has (among others) a timestamp column (named timestamp; it's a standard Oracle DATE datatype).  The records are about 4-11 minutes apart, about 7 or 8 records every hour, and I'm trying to determine if there is any pattern to them.

Is there an easy way to see each record, and the number of minutes that record occurred after the previous record?

Thanks,
AndyDan

答:
If the records have sequential id's you could do a self join like this:

```<code>SELECT t2.*, t2.timestamp - t1.timestamp AS timediff
FROM foo t1 inner join foo.t2 on t1.id = t2.id-1
</code>```

You'd probably need to tweak this to handle the first and last records, but that's the basics.

Title: Difference in time between records

Body:
If the records have sequential id's you could do a self join like this:

SELECT t2.*, t2.timestamp - t1.timestamp AS timediff
FROM foo t1 inner join foo.t2 on t1.id = t2.id-1

You'd probably need to tweak this to handle the first and last records, but that's the basics.


问:
How to encrypt data using server's public key txt file on iOS
I'm working on an iOS application with a java server. I need to encrypt some data using RSA. The RSA public key is a txt file. I want to connvert it into a SecKeyRef. The server is developed by the previous guy. I don't have the access to do anything with the server.

```<code>NSData *keyBytes = [[NSData alloc] initWithBase64EncodedString:SERVER_PUBLIC_KEY options:0];

SecCertificateRef mycertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) keyBytes);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;

if (mycertificate != NULL){
OSStatus status = SecTrustCreateWithCertificates(mycertificate, myPolicy, &myTrust);
SecTrustResultType trustResult;
if(status == noErr) {
    status = SecTrustEvaluate(myTrust, &trustResult);
}
CFRelease(mycertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
} else {
    NSLog(@"Hell no!");
}
return SecTrustCopyPublicKey(myTrust);
</code>```

The problem is SecCertificateRef is always null. The application crashes when I run the code above!

答:
You need to convert your certificate to the binary format DER from the text format PEM (Privacy Enhanced Mail, a text format for cryptographic objects). Basically PEM is a header, footer, some options (not used for certificates) and base 64 encoded DER in the middle.

As I didn't find any direct sample that performs this operation in iOS it is probably easiest to convert the certificate yourself from .txt to .bin, .der or .cer. You can do this for instance using openssl:

```<code>openssl x509 -in cert.txt -outform der -out cert.der
</code>```

and then try to read it in using the code in the question.

Body:
I'm working on an iOS application with a java server. I need to encrypt some data using RSA. The RSA public key is a txt file. I want to connvert it into a SecKeyRef. The server is developed by the previous guy. I don't have the access to do anything with the server.

NSData *keyBytes = [[NSData alloc] initWithBase64EncodedString:SERVER_PUBLIC_KEY options:0];

SecCertificateRef mycertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) keyBytes);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;

if (mycertificate != NULL){
OSStatus status = SecTrustCreateWithCertificates(mycertificate, myPolicy, &myTrust);
SecTrustResultType trustResult;
if(status == noErr) {
    status = SecTrustEvaluate(myTrust, &trustResult);
}
CFRelease(mycertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
} else {
    NSLog(@"Hell no!");
}
return SecTrustCopyPublicKey(myTrust);

The problem is SecCertificateRef is always null. The application crashes when I run the code above!

Body:
You need to convert your certificate to the binary format DER from the text format PEM (Privacy Enhanced Mail, a text format for cryptographic objects). Basically PEM is a header, footer, some options (not used for certificates) and base 64 encoded DER in the middle.

As I didn't find any direct sample that performs this operation in iOS it is probably easiest to convert the certificate yourself from .txt to .bin, .der or .cer. You can do this for instance using openssl:

openssl x509 -in cert.txt -outform der -out cert.der

and then try to read it in using the code in the question.


问:
Start Activity from within ArrayAdapter
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

```<code>import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

    @Override
    public int getCount()
    {
        return this.email.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}
</code>```

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

```<code>--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Update your code:

```<code>public Context c;

// Contractor
public TrackAdapter(Context mcontext, int resource)
{
    super(mcontext, R.layout.track_item, resource);
    this.c= mcontext;
    this.resource = resource;
}
</code>```

Call the setOnClickListener after setText label or before return.

```<code>holder.EMAIL.setText(EM);
  holder.EMAIL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(c.getApplicationContext(), NEXT_ACTIVITY.class);
                c.startActivity(intent);
            }
        });
</code>```

Title: Start Activity from within ArrayAdapter

Body:
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

    @Override
    public int getCount()
    {
        return this.email.size();
    }

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Update your code:

public Context c;

// Contractor
public TrackAdapter(Context mcontext, int resource)
{
    super(mcontext, R.layout.track_item, resource);
    this.c= mcontext;
    this.resource = resource;
}

Call the setOnClickListener after setText label or before return.

holder.EMAIL.setText(EM);
  holder.EMAIL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(c.getApplicationContext(), NEXT_ACTIVITY.class);
                c.startActivity(intent);
            }
        });


问:
SQL Trigger after insert not working
I tried to write a trigger that updates the data after an insert.

I'm using the SQL Server 2016 Import Export Data tool to transfer my data from Excel into the database.

After the import I need to run a few update statements.

I can save my trigger, but it's not updating any data. Where is my fault?

Trigger:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TRG_InsertMappinng]
   ON  [dbo].[T_CCG_MBR2017_Across]
   AFTER  INSERT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE  [DB_CC_FC_Database_SQL].[dbo].[T_CCG_MBR2017_Across]
    SET [Colum1] = 'Text1'
    Where [Colum1] IS NULL
    AND [Colum2] = 'Text2'
    AND [Colum3] = 'Text3'
    AND [Colum4] = 'Text4'

END
</code>```

答:
If your code is working outside the trigger, but not within the trigger, it could just be that the trigger is disabled. Try enabling it, and run it again to test.</p>

```<code>ENABLE TRIGGER [dbo].[TRG_InsertMappinng]
    ON [dbo].[T_CCG_MBR2017_Across];
</code>```

Title: SQL Trigger after insert not working

Body:
I tried to write a trigger that updates the data after an insert.

I'm using the SQL Server 2016 Import Export Data tool to transfer my data from Excel into the database.

After the import I need to run a few update statements.

I can save my trigger, but it's not updating any data. Where is my fault?

Trigger:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [dbo].[TRG_InsertMappinng]
   ON  [dbo].[T_CCG_MBR2017_Across]
   AFTER  INSERT
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE  [DB_CC_FC_Database_SQL].[dbo].[T_CCG_MBR2017_Across]
    SET [Colum1] = 'Text1'
    Where [Colum1] IS NULL
    AND [Colum2] = 'Text2'
    AND [Colum3] = 'Text3'
    AND [Colum4] = 'Text4'

END

Body:
If your code is working outside the trigger, but not within the trigger, it could just be that the trigger is disabled. Try enabling it, and run it again to test.

ENABLE TRIGGER [dbo].[TRG_InsertMappinng]
    ON [dbo].[T_CCG_MBR2017_Across];


问:
Why is the output of this program 312213444 and not 3122134?
In the code given, the output that I can think of is 3122134 because the the last printf statement gets executed only once when n=1. so condition become 1>1 which is definitely not true and the loop exits and the last printf statement is executed. but the original output is 312213444. Why is it so ? Where am I going wrong ? kindly explain every concept and instance of it ? </p>

```<code> #include <stdio.h>
 void count (int n)
 {
 static int d=1;

 printf("%d", n);
 printf("%d", d);
 d++ ;
 if(n>1)
 count(n-1);
 printf("%d", d);
 }

 void main ()
 {
 count(3);
 }
</code>```

答:
As you are recursively calling the function

count()

you are putting each call of count() on the stack of your application. After the last call of count is finished you return to the last call of count, which also prints the static variable d (which is only initialized once) again and so on, until the stack is finally on top and it goes back to the main method. This is why you are getting the last two '4' in your output.

Body:
In the code given, the output that I can think of is 3122134 because the the last printf statement gets executed only once when n=1. so condition become 1>1 which is definitely not true and the loop exits and the last printf statement is executed. but the original output is 312213444. Why is it so ? Where am I going wrong ? kindly explain every concept and instance of it ?

 #include <stdio.h>
 void count (int n)
 {
 static int d=1;

 printf("%d", n);
 printf("%d", d);
 d++ ;
 if(n>1)
 count(n-1);
 printf("%d", d);
 }

 void main ()
 {
 count(3);
 }


问:
Sql query using count(*) , groupby and fetching a column value simultaneously
I am been developing application in java and not much insight into sql.
Meanwhile , I have got to fetch count and username in the same query. My query goes like this :

```<code>SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  );
</code>```

This throws me an exception "not a single-group group function"
I want the count and C_user_name of the top most row (latest one).
Can somebody please help.

答:
If you use count(*) in the main query you also need a group by there:

```<code>SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  )
Group by   c_user_name
</code>```

Body:
I am been developing application in java and not much insight into sql.
Meanwhile , I have got to fetch count and username in the same query. My query goes like this :

SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  );

This throws me an exception "not a single-group group function"
I want the count and C_user_name of the top most row (latest one).
Can somebody please help.

Body:
If you use count(*) in the main query you also need a group by there:

SELECT count(*),c_user_name
FROM tra_shipment_status
WHERE i_tra_shipment_status_id IN
  (SELECT MAX(i_tra_shipment_status_id)
  FROM tra_shipment_status
  WHERE i_status_code = '4072'
  AND c_reference    IN ('FILEIO0023','MIASTOFIL003')
  Group By C_Reference
  )
Group by   c_user_name


问:
AMQP C Library for Small Embedded Devices
I am looking for a AMQP library, preferably written in C, that will work on a small embedded device. i.e. no OS and limited RAM and code size space (256k between both RAM and code).

I have seen the following post and number of others, I have looked into Qpid and RabbitMQ, but none seem suited to a small device.

Is there a AMQP implementation that has stable C++ Client library

Can anyone suggest a AMQP library that will work on a microcontroller? All functionality is not essential, even just support for telemetry would be good.

答:
This seems to be an old question, but maybe this still helps.

Disclaimer: I am one of the authors of uamqp-c.

There are 2 choices I know of:

-Qpic Proton C: https://github.com/apache/qpid-proton

-uamqp-c: https://github.com/Azure/azure-uamqp-c

Cheers,
/Dan


问:
Every time I start/restart Eclipse it changes the Text File Encoding to Other: UTF-8 instead of the Default (Cp1252)
so I have been reading and trying all the options I have found online with no success. The Problem: Every time I start/restart my Eclipse (Neon 4.6.2) the encoding is set back to Other: UTF-8 (I want it to be the Default Cp1252).
Screenshot.

I have set the encoding in eclipse.ini to -Dfile.encoding=Cp1252. Also tried the -Dclient.encoding.override=Cp1252 option.
No help. Also set all other possible encodings in eclipse->Window->Preferences to Cp1252. No success. Info: OS Windows 10, Java JDK1.8.0_112

Anyone have any ideas? I read that the encoding can be influenced by my JVM-encoding? I am really clueless here.

答: I fixed it by enabling the option "Skip automatic task execution at startup time" in the Ooomp -> Setup Tasks Preference Page.</p>


问:
SQL Server 2008 result String replacement - multi-identifier
I am currently stuck with running the following SQL query:

```<code>SELECT
    c.[DeviceName],
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'CFRM-Server%' FOR XML PATH('')),1,3,'') AS 'CFRM',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Communication Module%' FOR XML PATH('')),1,3,'') AS 'Communication Module',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons-Java%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons Java',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons_JBOSS%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons JBOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Mobile Store%' FOR XML PATH('')),1,3,'') AS 'Mobile Store',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'NEWPOSS-Store-Server%' FOR XML PATH('')),1,3,'') AS 'NEWPOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store Portal - Complete%' FOR XML PATH('')),1,3,'') AS 'Store Portal',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store S&R Services%' FOR XML PATH('')),1,3,'') AS 'SSR'
FROM
    [dbo].[Computer] as c WITH (NOLOCK)
WHERE
    c.[DeviceName] LIKE '%STL01'
ORDER BY
    c.[DeviceName] ASC;
</code>```

Output is fine, but it seems that one product (for 'SSR') in the database has a "&" character which leads to an corrupt output ('Store S&R Services' instead of 'S&R Services xx.xx.xx').

Any chance to perform an string replacement in the output?

Reason for the 'For XML' is because of double entries per DeviceName in the Database which leads to an empty result.

Any help is appreciated :)

答:
have a look at this:

```<code>DECLARE @teststring VARCHAR(100)='This is for test & show';

SELECT(SELECT ' + ' + @teststring FOR XML PATH(''));

SELECT((SELECT ' + ' + @teststring FOR XML PATH(''),TYPE).value('.','nvarchar(max)'));
</code>```

The two results are:

```<code>+ This is for test & show
+ This is for test & show
</code>```

Using FOR XML with forbidden characters (in most cases '<, > and &') will lead to escape entities. XML just cannot use these characters as they have meta semantics.

There are more characters which can lead to troubles like a line break or many foreign characters...

The easy solution: Wrap your SELECT ... FOR XML ... as shown in the second line and read the internal value via value()method. This will implicitly re-code the entities to the former characters.

Body:
I am currently stuck with running the following SQL query:

SELECT
    c.[DeviceName],
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'CFRM-Server%' FOR XML PATH('')),1,3,'') AS 'CFRM',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Communication Module%' FOR XML PATH('')),1,3,'') AS 'Communication Module',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons-Java%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons Java',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'GEBIT-Commons_JBOSS%' FOR XML PATH('')),1,3,'') AS 'Gebit Commons JBOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Mobile Store%' FOR XML PATH('')),1,3,'') AS 'Mobile Store',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'NEWPOSS-Store-Server%' FOR XML PATH('')),1,3,'') AS 'NEWPOSS',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store Portal - Complete%' FOR XML PATH('')),1,3,'') AS 'Store Portal',
    STUFF((SELECT ' + ' +  sw.[SuiteName] FROM [dbo].[AppSoftwareSuites] as sw where sw.[Computer_Idn] = c.[Computer_Idn] AND sw.[SuiteName] like 'Store S&R Services%' FOR XML PATH('')),1,3,'') AS 'SSR'
FROM
    [dbo].[Computer] as c WITH (NOLOCK)
WHERE
    c.[DeviceName] LIKE '%STL01'
ORDER BY
    c.[DeviceName] ASC;

Output is fine, but it seems that one product (for 'SSR') in the database has a "&" character which leads to an corrupt output ('Store S&R Services' instead of 'S&R Services xx.xx.xx').

Any chance to perform an string replacement in the output?

Reason for the 'For XML' is because of double entries per DeviceName in the Database which leads to an empty result.

Any help is appreciated :)

Body:
have a look at this:

DECLARE @teststring VARCHAR(100)='This is for test & show';

SELECT(SELECT ' + ' + @teststring FOR XML PATH(''));

SELECT((SELECT ' + ' + @teststring FOR XML PATH(''),TYPE).value('.','nvarchar(max)'));

The two results are:

+ This is for test &amp; show
+ This is for test & show

Using FOR XML with forbidden characters (in most cases '<, > and &') will lead to escape entities. XML just cannot use these characters as they have meta semantics.

There are more characters which can lead to troubles like a line break or many foreign characters...

The easy solution: Wrap your SELECT ... FOR XML ... as shown in the second line and read the internal value via value()method. This will implicitly re-code the entities to the former characters.


问:
Site working fine in Preview but when accessing the index.html file, the background images are missing
I have encountered an issue and I really don't know what is causing it. I am working in brackets and the site works perfectly in preview.

However, when I click on  the actual index.html file my background images from my scss are missing.

Uploaded images via src are working

Rest of my sass is working

Js is working

Only the images for my backgrounds ( using url ) are not working anymore, so I presume it has something to do with the url.

An example of the scss:

```<code>.jumbfirst {
    background: url('/imagini/images/background6.jpg');
    background-size: cover;
    width: $fullwidth;
    min-height: 600px;
}
</code>```

Any ideas? Thank you!

答:
It's because path relativity to your image file. When it comes to domain image shows because the path is set to current directory. But with index.html image path will be converted to something like this http://www.example.com/index.html/imagini/images/background6.jpg. Since the browser try to find image in that path image wont be found. Check your console in developer tools of chrome browser. You may get more details from there.

This might be fixed by removing starting / from your image url or creating a .htaccess with proper parameters.

Body:
I have encountered an issue and I really don't know what is causing it. I am working in brackets and the site works perfectly in preview.

However, when I click on  the actual index.html file my background images from my scss are missing.

Uploaded images via src are working

Rest of my sass is working

Js is working

Only the images for my backgrounds ( using url ) are not working anymore, so I presume it has something to do with the url.

An example of the scss:

.jumbfirst {
    background: url('/imagini/images/background6.jpg');
    background-size: cover;
    width: $fullwidth;
    min-height: 600px;
}

Any ideas? Thank you!


问:
Using GPU to train model
I have a little knowledge of using GPU to train model.
I am using K-means from scikit-learn to train my model.
Since my data is very large, is it possible to train this model using GPU to reduce computation time?
or could you please suggest any methods to use GPU power?

The other question is if I use TensorFlow to build the K-means as shown in this blog.

https://blog.altoros.com/using-k-means-clustering-in-tensorflow.html

It will use GPU or not?

Thank you in advance.

答:
To check if your GPU supports CUDA: https://developer.nvidia.com/cuda-gpus

Scikit-learn hasn't supported CUDA so far. You may want to use TensorFlow: https://www.tensorflow.org/install/install_linux

I hope this helps.

Title: Using GPU to train model


问:
improving my ghostscript eps compressive script
I would like to have some help to improve the compression of an .eps file with ghostscript.

So far I use the fonction eps2write:

```<code>-sDEVICE=eps2write -r72 -dLanguageLevel=1 -sOutputFile="%HOMEDRIVE%%HOMEPATH%\Desktop\cleaned.eps" -dNOPAUSE -dEPSCrop %1 -c quit pause
</code>```

If I use a 18Mo file that I get from Matlab it compresses it to 13Mo. Unfortunately it is still too big to be opened in Illustrator.
Any tips would be very welcomed.

答:
OK first off you aren't 'compressing' your EPS program, you are creating a brand new EPS program which should be visually the same. Its a subtle distinction, but its important. This is documented here.

Without seeing your EPS program its impossible to know why its so large, the likelihood is that it contains a large bitmap image, but there may be other reasons. Without knowing why the file is large, and what compromises in quality you are prepared to accept, its impossible to make recommendations for reducing it.

Your command line does nothing which I would expect to result in a reduced file size.

Setting LanguageLevel=1 does nothing, because you are using eps2write which always writes level 2 output. If it did do anything it would likely make the file bigger because of all the language level 2 constructs that would have to be rewritten using level 2 operators.

Setting the resolution to 72 does nothing in general, because eps2write (and the related family of devices) strive hard to retain the device and resolution-independent nature of the input. The onl;y time the resolution is used is when the input uses some primitive which cannot be reproduced in the output, and the primitive is rendered to an image. If that was happening I think you would be horrified by the extremely low resolution result.

If you want to produce a new file, which trades quality for file size, then you need to look at the various options described in the documentation.

There are a few things which might reduce the file size, at the expense of quality, in particular the image downsampling parameters. Its up to you to decide just how much quality you are prepared to trade for file size, so you will have to decide what level to set these parameters to.

Its also entirely possible that the program is simply very complex (lots of long paths for example) and cannot be significantly reduced. PostScript is not intended as an editable container format and Illustrator is not intended as a graphical PostScript editor, if you want to modify the content, go back to Matlab, modify the document and recreate the EPS file.

Body:
I would like to have some help to improve the compression of an .eps file with ghostscript.

So far I use the fonction eps2write:

-sDEVICE=eps2write -r72 -dLanguageLevel=1 -sOutputFile="%HOMEDRIVE%%HOMEPATH%\Desktop\cleaned.eps" -dNOPAUSE -dEPSCrop %1 -c quit pause

If I use a 18Mo file that I get from Matlab it compresses it to 13Mo. Unfortunately it is still too big to be opened in Illustrator.
Any tips would be very welcomed.


问:
Print the hash name of a hash of hashes of hashes etc
So I have a massive hash of hashes.

```<code>$VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };
</code>```

There's an example I found on the web.

What I want to print is 'Peti Bar' and 'Foo Bar', but it's not quite that simple. Imagine Mathematics being it's own hash within that hash, etc. So I'd wanta to print 'Peti Bar' -> 'Mathematics' -> 'AnotherHash'
'Foo Bar' -> 'Literature' -> 'Anotherhash'

I guess maybe what I'm asking is print the hash of hashes without key/value of each respective hash.

答:
Similar to Dave S

```<code>use strict;

my $VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };

sub printHash($$) {
    my $hashRef = shift;
    my $indent = shift;
    for (keys %$hashRef) {
        if (ref($hashRef->{$_}) eq 'HASH') {
            print "$indent$_ \n";
            printHash($hashRef->{$_},"\t$indent");
        }
        else {
            print "$indent$_  $hashRef->{$_}\n";
        }
    }
}

printHash($VAR1,undef);
</code>```

Output is :

```<code>Foo Bar
        Mathematics  97
        Literature  67
Peti Bar
        Literature  88
        Mathematics  82
        Art  99
</code>```

Body:
So I have a massive hash of hashes.

$VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };

There's an example I found on the web.

What I want to print is 'Peti Bar' and 'Foo Bar', but it's not quite that simple. Imagine Mathematics being it's own hash within that hash, etc. So I'd wanta to print 'Peti Bar' -> 'Mathematics' -> 'AnotherHash'
'Foo Bar' -> 'Literature' -> 'Anotherhash'

I guess maybe what I'm asking is print the hash of hashes without key/value of each respective hash.

Body:
Similar to Dave S

use strict;

my $VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };

sub printHash($$) {
    my $hashRef = shift;
    my $indent = shift;
    for (keys %$hashRef) {
        if (ref($hashRef->{$_}) eq 'HASH') {
            print "$indent$_ \n";
            printHash($hashRef->{$_},"\t$indent");
        }
        else {
            print "$indent$_  $hashRef->{$_}\n";
        }
    }
}

printHash($VAR1,undef);

Output is :

Foo Bar
        Mathematics  97
        Literature  67
Peti Bar
        Literature  88
        Mathematics  82
        Art  99


问:
Appropriate Data structure of java to find unique word from file
I have a requirement to parse a file which contains 1000 of sentences in the file.
where I have to find a unique word in a file means that has not come more than one time in the file.
which data structure of should I use.(need to perform this operation using DS of java only)and why and how

2nd Question is

```<code>map.put("abc","hello");
map.put.("ABC","hi");
</code>```

when we are inserting in map object as given above code what will happen.

答:
You can fill your words in a map witch has a key the word and the value the number of occurrence.

When you finish filling your data in your Map loop again again check the value if great then on or equal one, if it is great then one, remove it from your map.
And you can return the size of this map in the end, to know the number of unique words

If you dont want to use just abc or ABC, you ca use LowerCase or UpperCase when you insert in your Map.

Here a simple example you can go throw :

```<code>public static void main(String[] args) {
    //i consider you know how to learn from a file, i use a simple array just to explain
    String[] listWords = {"hello", "word", "hello", "stack", "HELLO", "WORD", "123", "what?"};

    //fill your words in your map
    Map<String, Integer> map = new HashMap<>();
    for (String word : listWords) {
        if (!map.containsKey(word.toLowerCase())) {
            map.put(word.toLowerCase(), 1);
        } else {
            map.put(word.toLowerCase(), map.get(word.toLowerCase()) + 1);
        }
    }

    //print your map
    map.entrySet().forEach((entry) -> {
        System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue());
    });
    System.out.println("**************************************************");
    //loop throw your map and remove the words which occurrence > 1
    for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, Integer> entry = it.next();
        if (entry.getValue() > 1) {
            it.remove();
        }
    }

    //print your map again
    map.entrySet().forEach((entry) -> {
        System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue());
    });

    //size of your end map
    System.out.println("Size of map = " + map.size());
}
</code>```

Some good references you can base one to play with maps:

How to update a value, given a key in a java hashmap?

iterating over and removing from a map

Hope this can gives you an idea.

Body:
I have a requirement to parse a file which contains 1000 of sentences in the file.
where I have to find a unique word in a file means that has not come more than one time in the file.
which data structure of should I use.(need to perform this operation using DS of java only)and why and how

2nd Question is

map.put("abc","hello");
map.put.("ABC","hi");

when we are inserting in map object as given above code what will happen.

Body:
You can fill your words in a map witch has a key the word and the value the number of occurrence.

When you finish filling your data in your Map loop again again check the value if great then on or equal one, if it is great then one, remove it from your map.
And you can return the size of this map in the end, to know the number of unique words

If you dont want to use just abc or ABC, you ca use LowerCase or UpperCase when you insert in your Map.

Here a simple example you can go throw :

public static void main(String[] args) {
    //i consider you know how to learn from a file, i use a simple array just to explain
    String[] listWords = {"hello", "word", "hello", "stack", "HELLO", "WORD", "123", "what?"};

    //fill your words in your map
    Map<String, Integer> map = new HashMap<>();
    for (String word : listWords) {
        if (!map.containsKey(word.toLowerCase())) {
            map.put(word.toLowerCase(), 1);
        } else {
            map.put(word.toLowerCase(), map.get(word.toLowerCase()) + 1);
        }
    }

    //print your map
    map.entrySet().forEach((entry) -> {
        System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue());
    });
    System.out.println("**************************************************");
    //loop throw your map and remove the words which occurrence > 1
    for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, Integer> entry = it.next();
        if (entry.getValue() > 1) {
            it.remove();
        }
    }

    //print your map again
    map.entrySet().forEach((entry) -> {
        System.out.println("word : " + entry.getKey() + " occurence : " + entry.getValue());
    });

    //size of your end map
    System.out.println("Size of map = " + map.size());
}

Some good references you can base one to play with maps:

How to update a value, given a key in a java hashmap?

iterating over and removing from a map

Hope this can gives you an idea.


问:
How to put an image over the content of a div?
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

```<code>.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}
</code>```

and the HTML is not special but I put it:

```<code><template name="machine">
    <li class="liMachine switch">
        <div id="nameMachine">
            <h3>{{nameMachine}}</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">{{stateMachine}}</span>
        </div>
        {{#if isLocked}}
        <div>
          <img class="imgCadenas">
        </div>
        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}<i class="fa fa-spinner fa-spin"></i>
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}<i class="fa fa-spinner fa-spin"></i>
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}<i class="fa fa-spinner fa-spin"></i>{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}
    </li>
</template>
</code>```

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

答:
I would edit the position of the div as follows and make sure the parent div has also a set position e.g. position:relative;</p>

```<code>.imgCadenas{
   position: absolute;
   top: 4px;
   right: 4px;
 }
</code>```

Body:
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}

and the HTML is not special but I put it:

<template name="machine">

{{nameMachine}}

            State:{{stateMachine}}

        {{#if isLocked}}

        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}

</template>

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

Body:
I would edit the position of the div as follows and make sure the parent div has also a set position e.g. position:relative;

.imgCadenas{
   position: absolute;
   top: 4px;
   right: 4px;
 }


答:
Define position if li as relative

```<code>.liMachine{
  list-style:none;
  position:relative;
}
</code>```

and for image

```<code>.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
/* Add following css */
position:absolute;
  top:0px;
  right:0px;
}
</code>```

Title: How to put an image over the content of a div?

Body:
Define position if li as relative

.liMachine{
  list-style:none;
  position:relative;
}

and for image

.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
/* Add following css */
position:absolute;
  top:0px;
  right:0px;
}


问:
Mono Pkg-Config.exe Keeps Crashing?
I'm new to Mono - thought I'd give cross platform a try - my main IDE is Visual Studio and so the process of building applications through the command prompt is a bit foreign to me.

I was following the Mono Basics tutorial, and have gotten to the point where it says Winforms Hello World. I copied the code provided and saved it to a .cs file (on the Desktop).

I then opened up a command prompt and pointed it towards the Desktop directory. I ran the command:

```<code>mcs hello.cs -pkg:dotnet
</code>```

And the result was:

The console told me that it was a CS8027 error but nothing else.

I have 3 environment variables that I added, with no fix:

PATH -> path to mono\bin

PATH -> path to mono\lib\pkgconfig

PKG_CONFIG_PATH -> path to mono\lib\pkgconfig

This happens whenever I try to use pkg-config.exe (tried to use pkg-config.exe --list-all but the same problem arose).

I've checked other answers/questions about the CS8027 error but the solutions did not help - it still crashes every time!

答:
pkg-config is built with a different version of MSVC to Mono itself. You need the 32-bit VC++12 runtime installed for it to work. That ought to be included with mono.msi, as per https://github.com/mono/release/commit/8394dcc254510977c3e654abf916a48c6c6894fb

If you check the Windows event log, under Applications, you might get more information on what didn't work.

Title: Mono Pkg-Config.exe Keeps Crashing?

Body:
I'm new to Mono - thought I'd give cross platform a try - my main IDE is Visual Studio and so the process of building applications through the command prompt is a bit foreign to me.

I was following the Mono Basics tutorial, and have gotten to the point where it says Winforms Hello World. I copied the code provided and saved it to a .cs file (on the Desktop).

I then opened up a command prompt and pointed it towards the Desktop directory. I ran the command:

mcs hello.cs -pkg:dotnet

And the result was:

The console told me that it was a CS8027 error but nothing else.

I have 3 environment variables that I added, with no fix:

PATH -> path to mono\bin

PATH -> path to mono\lib\pkgconfig

PKG_CONFIG_PATH -> path to mono\lib\pkgconfig

This happens whenever I try to use pkg-config.exe (tried to use pkg-config.exe --list-all but the same problem arose).

I've checked other answers/questions about the CS8027 error but the solutions did not help - it still crashes every time!


问:
How to automatically insert a blank row after a group of data
I have created a sample table below that is similar-enough to my table in excel that it should serve to illustrate the question. I want to simply add a row after each distinct datum in column1 (simplest way, using excel, thanks).

_

CURRENT TABLE:

```<code>column1   |   column2   |  column3
----------------------------------
  A       |     small   |  blue
  A       |     small   |  orange
  A       |     small   |  yellow
  B       |     med     |  yellow
  B       |     med     |  blue
  C       |     large   |  green
  D       |     large   |  green
  D       |     small   |  pink
</code>```

_

DESIRED TABLE

Note: the blank row after each distinct column1

```<code>column1   |   column2   |  column3
----------------------------------
  A       |     small   |  blue
  A       |     small   |  orange
  A       |     small   |  yellow

  B       |     med     |  yellow
  B       |     med     |  blue

  C       |     large   |  green

  D       |     large   |  green
  D       |     small   |  pink
</code>```

答:
Insert a column at the left of the table 'Control'

Number the data as 1 to 1000 (assuming there are 1000 rows)

Copy the key field to another sheet and remove duplicates

Copy the unique row items to the main sheet, after 1000th record

In the 'Control' column, add number 1001 to all unique records

Sort the data (including the added records), first on key field and then on 'Control'

A blank line (with data in key field and 'Control') is added

Body:
I have created a sample table below that is similar-enough to my table in excel that it should serve to illustrate the question. I want to simply add a row after each distinct datum in column1 (simplest way, using excel, thanks).

_

CURRENT TABLE:

column1   |   column2   |  column3
----------------------------------
  A       |     small   |  blue
  A       |     small   |  orange
  A       |     small   |  yellow
  B       |     med     |  yellow
  B       |     med     |  blue
  C       |     large   |  green
  D       |     large   |  green
  D       |     small   |  pink

_

DESIRED TABLE

Note: the blank row after each distinct column1

column1   |   column2   |  column3
----------------------------------
  A       |     small   |  blue
  A       |     small   |  orange
  A       |     small   |  yellow

  B       |     med     |  yellow
  B       |     med     |  blue

  C       |     large   |  green

  D       |     large   |  green
  D       |     small   |  pink


问:
Creating a web service to connect with my chatbot
I was going through the tutorial at https://api.ai/slack/ to create a chatbot and I'm not sure what a web hook and web service is. I know simple java programming and created test classes in a netbeans project to simulate the input from the chatbot.

How do I connect my locally-hosted application to api.ai through a web hook to create a slack chatbot?

答:
Webhook is a HTTP callback URL that you are suppose to provide api.ai. It is a connector between api.ai and web service. Now when slack sends a message to api.ai, it would send an event notification to your web application service.
To generate a temporary callback URL you could use the following link : https://ngrok.com/

Steps :  1) If you do not have a callback URL, follow the steps in the ngrok website for installation

2) Run your application on port 8080

3) Now execute the ngrok.exe file from command prompt with the following command [ngrok.exe http 8080].  This would give you the webhook URL which you could give api.ai


问:
convert method to generic with multiple data types
I Try to convert my method in java into a generic method, but it does not work. My problem is, that i have two data types as Parameter.

My method is:

```<code>public static int whichInt(int[] a, char[] b) { ...
</code>```

My solution was something like this:

```<code>public static <T,S extends Comparable<T,S>> int whichint(T[]a, S[] b){ ...
</code>```

Does somebody know how to write this method correctly?
Best regards,

答:
You have to change the parameters from Array to List or Set or Collection..

```<code>public static <T,S> int whichInt(Collection<T> a,Collection<S> b)
</code>```

Java does not support Generics in Array..
Reference : https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html

Body:
I Try to convert my method in java into a generic method, but it does not work. My problem is, that i have two data types as Parameter.

My method is:

public static int whichInt(int[] a, char[] b) { ...

My solution was something like this:

public static <T,S extends Comparable<T,S>> int whichint(T[]a, S[] b){ ...

Does somebody know how to write this method correctly?
Best regards,

Body:
You have to change the parameters from Array to List or Set or Collection..

public static <T,S> int whichInt(Collection<T> a,Collection<S> b)

Java does not support Generics in Array..
Reference : https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html


问:
How to access old entity value in ASP.NET Entity Framework
I have a small ASP.Net mvc3 application and I am on the edit part. I have the default template:

```<code>public ActionResult Edit(int id)
{
    User user = db.Users.Find(id);
    return View(user);
}

public ActionResult Edit(User user)
{
    //(Here access to old user name for example)
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}
</code>```

If i do user.name I have the new value but I want to access the db value before the save.

Thanks !

答:
If you want to get old value and new value separate :

```<code> //user.UserName = "oldtest"
 user.UserName = "Test"
 var originalValues = db.Entry(user).OriginalValues.Clone();
 var originalval = originalValues.GetValue<string>("UserName");
 var currentvalue = db.Entry(user).CurrentValues.Clone();
 var curretval = currentvalue.GetValue<string>("UserName");
</code>```

This will return originalval  as old value before set new UserName as "oldtest" and curretval return new UserName as "Test"

Body:
I have a small ASP.Net mvc3 application and I am on the edit part. I have the default template:

public ActionResult Edit(int id)
{
    User user = db.Users.Find(id);
    return View(user);
}

public ActionResult Edit(User user)
{
    //(Here access to old user name for example)
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

If i do user.name I have the new value but I want to access the db value before the save.

Thanks !

Body:
If you want to get old value and new value separate :

 //user.UserName = "oldtest"
 user.UserName = "Test"
 var originalValues = db.Entry(user).OriginalValues.Clone();
 var originalval = originalValues.GetValue<string>("UserName");
 var currentvalue = db.Entry(user).CurrentValues.Clone();
 var curretval = currentvalue.GetValue<string>("UserName");

This will return originalval  as old value before set new UserName as "oldtest" and curretval return new UserName as "Test"


问:
Hover button that shows text html/css
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

```<code><title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
    /*TEST HERE*/
    .w3-button {width:800px;}
    .w3-button {height:800px;} `
</style>
<div class="w3-container">
    <h2>TITULO AQUI</h2>
    <p>
        <button class="w3-button w3-light-blue">Hover in here</button>
    </p>
</div>
/*<div id="button1"></div>*/
</code>```

答:
The title attribute is of course the most obvious.

Another attribute based solution is using a custom one and show it with a pseudo, where you could style it some more.

button[data-title] {
  position: relative;
  transition: opacity 1s;
}
button[data-title]::after {
  content: attr(data-title);
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%,-150%);
  background: gray;
  color: lightgreen;
  padding: 10px;
  opacity: 0;
  transition: opacity 0.5s;
}
button[data-title]:hover::after {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
    /*TEST HERE*/
    .w3-button {width:200px;}
    .w3-button {height:150px;} `
</style>
<div class="w3-container">
    <h2>TITULO AQUI</h2>
    <p>
        <button class="w3-button w3-light-blue" data-title="I'm being hovered">Hover in here</button>
    </p>
</div></code>```

Title: Hover button that shows text html/css

Body:
I'm learning HTML & CSS. Now I am trying to make a hover button that shows some text just like the tooltip feature makes. How can I make that happen from here:

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=2">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

TITULO AQUI

        <button class="w3-button w3-light-blue">Hover in here</button>

/*

*/

Body:
The title attribute is of course the most obvious.

Another attribute based solution is using a custom one and show it with a pseudo, where you could style it some more.

button[data-title] {
  position: relative;
  transition: opacity 1s;
}
button[data-title]::after {
  content: attr(data-title);
  position: absolute;
  left: 50%; top: 50%;
  transform: translate(-50%,-150%);
  background: gray;
  color: lightgreen;
  padding: 10px;
  opacity: 0;
  transition: opacity 0.5s;
}
button[data-title]:hover::after {
  opacity: 1;
}

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<style>
    /*TEST HERE*/
    .w3-button {width:200px;}
    .w3-button {height:150px;} `
</style>
<div class="w3-container">
    <h2>TITULO AQUI</h2>
    <p>
        <button class="w3-button w3-light-blue" data-title="I'm being hovered">Hover in here</button>
    </p>
</div>


问:
Intermittent bugs - sometimes this code works and sometimes it doesn't!
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

```<code>int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}
</code>```

The code for compute_3d_transform is:

```<code>void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}
</code>```

Structure for the results:

```<code>typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};
</code>```

The code is part of an open source project of mine so it's okay to post a lot of code here.

答:
When I used to program C, I would use a divide and conquer debugging technique for this kind of problem to try to isolate the offending operation (paying attention to whether the symptoms change as debugging code is added, which is indicative of dangling pointer type bugs).

Essentially, start with the first line where the value is known to be good (and prove that it is consistently good at that line).  Then identify where is it known to be bad.  Then approx. halfway between the two points insert a test to see if it's bad.  If not, then insert a test halfway between the mid-point and the known bad location, if it is bad then insert a test halfway between the mid-point and the known good location, and so on.

If the line identified is itself a function call, this process can be repeated in that called function, and so on.

When using this kind of approach, it's important to minimize the amount of added code and the artificial "noise", which can create timing changes.

Use this if you don't have (or can't use) an interactive debugger, or if the problem does not manifest when using one.

Body:
This code intermittently works. It's running on a small microcontroller. It will work fine even after restarting the processor, but if I change some part of the code, it breaks. This makes me think that it's some kind of pointer bug or memory corruption. What's happening is the coordinate, p_res.pos.x is sometimes read as 0 (the incorrect value) and 96 (the correct value) when it is passed to write_circle_outlined. y seems to be correct most of the time. If anyone can spot anything obviously wrong please point it out!

int demo_game()
{
    long int d;
    int x, y;
    struct WorldCamera p_viewer;
    struct Point3D_LLA p_subj;
    struct Point2D_CalcRes p_res;
    p_viewer.hfov = 27;
    p_viewer.vfov = 32;
    p_viewer.width = 192;
    p_viewer.height = 128;
    p_viewer.p.lat = 51.26f;
    p_viewer.p.lon = -1.0862f;
    p_viewer.p.alt = 100.0f;
    p_subj.lat = 51.20f;
    p_subj.lon = -1.0862f;
    p_subj.alt = 100.0f;
    while(1)
    {
        fill_buffer(draw_buffer_mask, 0x0000);
        fill_buffer(draw_buffer_level, 0xffff);
        compute_3d_transform(&p_viewer, &p_subj, &p_res, 10000.0f);
        x = p_res.pos.x;
        y = p_res.pos.y;
        write_circle_outlined(x, y, 1.0f / p_res.est_dist, 0, 0, 0, 1);
        p_viewer.p.lat -= 0.0001f;
        //p_viewer.p.alt -= 0.00001f;
        d = 20000;
        while(d--);
    }
    return 1;
}

The code for compute_3d_transform is:

void compute_3d_transform(struct WorldCamera *p_viewer, struct Point3D_LLA *p_subj, struct Point2D_CalcRes *res, float cliph)
{
    // Estimate the distance to the waypoint. This isn't intended to replace
    // proper lat/lon distance algorithms, but provides a general indication
    // of how far away our subject is from the camera. It works accurately for
    // short distances of less than 1km, but doesn't give distances in any
    // meaningful unit (lat/lon distance?)
    res->est_dist = hypot2(p_viewer->p.lat - p_subj->lat, p_viewer->p.lon - p_subj->lon);
    // Save precious cycles if outside of visible world.
    if(res->est_dist > cliph)
        goto quick_exit;
    // Compute the horizontal angle to the point.
    // atan2(y,x) so atan2(lon,lat) and not atan2(lat,lon)!
    res->h_angle = RAD2DEG(angle_dist(atan2(p_viewer->p.lon - p_subj->lon, p_viewer->p.lat - p_subj->lat), p_viewer->yaw));
    res->small_dist = res->est_dist * 0.0025f; // by trial and error this works well.
    // Using the estimated distance and altitude delta we can calculate
    // the vertical angle.
    res->v_angle = RAD2DEG(atan2(p_viewer->p.alt - p_subj->alt, res->est_dist));
    // Normalize the results to fit in the field of view of the camera if
    // the point is visible. If they are outside of (0,hfov] or (0,vfov]
    // then the point is not visible.
    res->h_angle += p_viewer->hfov / 2;
    res->v_angle += p_viewer->vfov / 2;
    // Set flags.
    if(res->h_angle < 0 || res->h_angle > p_viewer->hfov)
        res->flags |= X_OVER;
    if(res->v_angle < 0 || res->v_angle > p_viewer->vfov)
        res->flags |= Y_OVER;
    res->pos.x = (res->h_angle / p_viewer->hfov) * p_viewer->width;
    res->pos.y = (res->v_angle / p_viewer->vfov) * p_viewer->height;
    return;
quick_exit:
    res->flags |= X_OVER | Y_OVER;
    return;
}

Structure for the results:

typedef struct Point2D_Pixel { unsigned int x, y; };

// Structure for storing calculated results (from camera transforms.)
typedef struct Point2D_CalcRes
{
    struct Point2D_Pixel pos;
    float h_angle, v_angle, est_dist, small_dist;
    int flags;
};

The code is part of an open source project of mine so it's okay to post a lot of code here.


问:
Azure AD "Description" field missing when sync'd using Azure AD Connect
We're using Azure AD Connect to sync our on-premises Active Directory to Azure AD. We have the free version that comes with the Office 365 business plans.

Azure AD Connect shows the Description field as being synchronized to Azure AD, yet, the field does not appear anywhere.

We're using a third-party service to read data from our user profiles to generate email signatures, but the service cannot read the data as it doesn't "exist" in Azure.

I even tried going into our Azure AD Connect configuration, enabled Directory extension attribute sync and added the Description field for user accounts...but it created a new "description" field with a weird name instead.

Is there something I'm missing ? Do we perhaps need to have Azure AD Premium ?

Thanks for your help people!

答:
Based on the official documentation, the attribute for Description has been synced to Azure AD. You can verify it by open Synchronization Service Manager, and check the properties for the specific user by Metaverse Search.

However, if you need to retrieve the attribute values for specific user, you must use Azure AD Graph API. For your scenario, the third-party service may leverage  Azure AD Graph API for retrieving user properties.

Then, if you check the Graph API reference, you can find that Description is not included in the list, which means you can't retrieve the Description attribute from Azure AD.

As a workaround, you can use Directory extension, but the attributes are prefixed with extension_{AppClientId}_. The AppClientId has the same value for all attributes in your Azure AD tenant.

Also, you can submit your requirements to the following website, which collects feedbacks for Azure AD from users.

https://feedback.azure.com/forums/169401-azure-active-directory?query=attribute


问:
How do I use CSS transitions when adding elements in Elm?
Simple scenario is I have a button that fetches some data from an API and adds the data to a list.

I would like to apply a CSS transition of the opacity property for the newly added item so it fades in as its added to the list.

Usually this is done by having a default CSS class with opacity: 0; and a transition rule. Then after the element is added you apply another CSS class to it with opacity: 1; and you get a fade in effect.

How do you do this with Elm?

This is how list items are added to the view right now,

ul [ class "list" ] (List.map (\item -> li [] [ text item ]) model.items)

答:
You need to use an animation to achieve this like below

var para = document.createElement("P");                       // Create a
 element
var t = document.createTextNode("Element added with Javascript");       // Create a text node
para.appendChild(t);                                          // Append the text to

para.className = 'animation-enter'                            // Add animation enter
document.body.appendChild(para);                              // Append
 to ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.animation-enter{
  animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}</code>```

On page Load
```

Body:
You need to use an animation to achieve this like below

var para = document.createElement("P");                       // Create a <p> element
var t = document.createTextNode("Element added with Javascript");       // Create a text node
para.appendChild(t);                                          // Append the text to <p>
para.className = 'animation-enter'                            // Add animation enter
document.body.appendChild(para);                              // Append <p> to <body>

.animation-enter{
  animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

<p class="animation-enter">On page Load </p>