问:
Smoothstate causing jQuery function to runs once per session
I have a jquery function for my index.html page that runs when the page is ready. Its grabs an articles supporting image and follows the mouse cursor within a predefined area. However, upon visiting other pages and returning back to the index.html page the function no longer runs unless I perform a page refresh. How can I fix this?

Edit: It looks like the smoothstate function is causing the issue here as everything works as it is once I remove (smoothstate)[https://github.com/miguel-perez/smoothState.js].
HTML

```<code><div id="main">

<p>Hover over titles</p>

<div class="content1">
  <a><h2>Title 1 goes here </h2></a>
  <img src="http://lorempixel.com/400/400/sports" alt="Image"/>
</div>

<div class="content2">
  <a><h2>Title 2 goes here </h2></a>
  <img src="http://lorempixel.com/300/300/people" alt="Image"/>
</div>

<div class="content2">
  <a><h2>Title 3 goes here </h2></a>
  <img src="http://lorempixel.com/200/300/technology" alt="Image"/>
</div>

</div>
</code>```

jQuery

```<code>$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $(this).siblings('img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $(this).siblings('img').hide();
        });
    });
});

// Smoothstate

$(function(){
  'use strict';
  var $page = $('#main'),
      options = {
        debug: true,
        prefetch: true,
        cacheLength: 2,
        forms: 'form',
        onStart: {
          duration: 250, // Duration of our animation
          render: function ($container) {
            // Add your CSS animation reversing class
            $container.addClass('is-exiting');
            // Restart your animation
            smoothState.restartCSSAnimations();
          }
        },
        onReady: {
          duration: 1000,
          render: function ($container, $newContent) {
            // Remove your CSS animation reversing class
            $container.removeClass('is-exiting');
            // Inject the new content
            $container.html($newContent);

          }
        }
      },
      smoothState = $page.smoothState(options).data('smoothState');
});
</code>```

答: Please refer following answers, closely related to what you want to do: browser event for window.focus() </p>

Body:
I have a jquery function for my index.html page that runs when the page is ready. Its grabs an articles supporting image and follows the mouse cursor within a predefined area. However, upon visiting other pages and returning back to the index.html page the function no longer runs unless I perform a page refresh. How can I fix this?

Edit: It looks like the smoothstate function is causing the issue here as everything works as it is once I remove (smoothstate)[https://github.com/miguel-perez/smoothState.js].
HTML

Hover over titles

Title 1 goes here

Title 2 goes here

Title 3 goes here

jQuery

$(document).ready(function(){
    $('h2').on('mouseenter mousemove', function(evt){
        $(this).siblings('img').css({left: evt.pageX+30, top: evt.pageY-15}).show();
        $(this).on('mouseleave', function(){
            $(this).siblings('img').hide();
        });
    });
});

// Smoothstate

$(function(){
  'use strict';
  var $page = $('#main'),
      options = {
        debug: true,
        prefetch: true,
        cacheLength: 2,
        forms: 'form',
        onStart: {
          duration: 250, // Duration of our animation
          render: function ($container) {
            // Add your CSS animation reversing class
            $container.addClass('is-exiting');
            // Restart your animation
            smoothState.restartCSSAnimations();
          }
        },
        onReady: {
          duration: 1000,
          render: function ($container, $newContent) {
            // Remove your CSS animation reversing class
            $container.removeClass('is-exiting');
            // Inject the new content
            $container.html($newContent);

          }
        }
      },
      smoothState = $page.smoothState(options).data('smoothState');
});


来源: stackexchange

问:
Django Redis Cache Admin Interface
I implemented Redis Caching in my Django.. However, is there a Friendly User Interface to just check the cache values. Something like you can see all the cache keys and its values in Django Admin</p>

答:
You can check the status of your Redis Cache with the help of this github library,

https://github.com/erussell/django-redis-status

It is only accessible in the django-admin page.
By the way, you can always check your redis database using redis-cli.

I don't know whether I am getting your question in the correct way or not.
But this may help.

ContentLicense: CC BY-SA 3.0

Title: Django Redis Cache Admin Interface


问:
messagebox appeared second time
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

```<code>Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub
</code>```

答:
Here is the solution,</p>

```<code>Public Class Form1
            Dim message as boolean = true
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
            If TextBox3.Text = Nothing Then
            If message Then 'show the message as true
            message = False 'set the message false for textbox_changed not appear again
            Textbox1.Clear()
            message = True 'set the message true for next time textbox change appear again
            MsgBox("Enter Number to Textbox3")
    End If
                    Else
                        Dim digit As Integer = CInt(TextBox3.Text)
                        If TextBox1.TextLength = digit Then
                            Dim fields() As String = ListBox1.Text.Split(";")
                            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
                            If idx <> -1 Then
                                ListBox1.SelectedIndex = idx
                                ListBox1.SelectedIndex.ToString(fields(0))
                                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                                PrintDocument1.Print()
                            Else
                                TextBox1.Clear()
                            End If
                        End If
                    End If
                End Sub
</code>```

Title: messagebox appeared second time

Body:
In my code, when TextBox3 does not have any value, it must show a notice in a MsgBox to enter a value in TextBox1

But when I run it the MsgBoxnotice appears twice in the screen when it should show only once.

Here is my code:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox3.Text = Nothing Then
        TextBox1.Clear()
        MsgBox("Enter Number to Textbox1")
    Else
        Dim digit As Integer = CInt(TextBox3.Text)
        If TextBox1.TextLength = digit Then
            Dim fields() As String = ListBox1.Text.Split(";")
            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
            If idx <> -1 Then
                ListBox1.SelectedIndex = idx
                ListBox1.SelectedIndex.ToString(fields(0))
                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                PrintDocument1.Print()
            Else
                TextBox1.Clear()
            End If
        End If
    End If
End Sub

Body:
Here is the solution,

Public Class Form1
            Dim message as boolean = true
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
            If TextBox3.Text = Nothing Then
            If message Then 'show the message as true
            message = False 'set the message false for textbox_changed not appear again
            Textbox1.Clear()
            message = True 'set the message true for next time textbox change appear again
            MsgBox("Enter Number to Textbox3")
    End If
                    Else
                        Dim digit As Integer = CInt(TextBox3.Text)
                        If TextBox1.TextLength = digit Then
                            Dim fields() As String = ListBox1.Text.Split(";")
                            Dim idx As Integer = ListBox1.FindString(TextBox1.Text)
                            If idx <> -1 Then
                                ListBox1.SelectedIndex = idx
                                ListBox1.SelectedIndex.ToString(fields(0))
                                ListBox2.Items.Add(Now() + Space(1) + ListBox1.Text.Substring(0, 13))
                                PrintDocument1.Print()
                            Else
                                TextBox1.Clear()
                            End If
                        End If
                    End If
                End Sub


问:
Select Case conversion not displaying properly, how can i fix?
I have an executable that when run takes an inputted date and then selects what date suffix is needed with it, however it is always defaulting to the case else.

when i have 02/04/2017 as format DD/MM/YYYY the result of the below case is 2th April instead of 2nd...

Could anyone enlighten me on the problem.

```<code>    Dim Datewc As Date = Nothing

    If CheckBox1.Checked Then
        Datewc = TextBox1.Text
    End If

    'Determine date suffix
    Dim datsuff As String = ""

    Select Case CInt(Datewc.Day)
        Case 1 Or 21 Or 31
            datsuff = "st"
        Case 2 Or 22
            datsuff = "nd"
        Case 3 Or 23
            datsuff = "rd"
        Case Else
            datsuff = "th"
    End Select
</code>```

答:
Parse you date

```<code>Dim dDate As DateTime =
  DateTime.ParseExact(TextBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
</code>```

Change your code a little, should work.
Day function returns integer, no need to Cast using CInt.

```<code> 'Determine date suffix
Dim datsuff As String = ""

Select Case Datewc.Day
    Case 1 , 21 , 31
        datsuff = "st"
    Case 2 , 22
        datsuff = "nd"
    Case 3 , 23
        datsuff = "rd"
    Case Else
        datsuff = "th"
End Select
</code>```

Explanation

Case 2 Or 22 means Case ((2 Or 22) ==true), It will be false hence going to else part.

Body:
I have an executable that when run takes an inputted date and then selects what date suffix is needed with it, however it is always defaulting to the case else.

when i have 02/04/2017 as format DD/MM/YYYY the result of the below case is 2th April instead of 2nd...

Could anyone enlighten me on the problem.

    Dim Datewc As Date = Nothing

    If CheckBox1.Checked Then
        Datewc = TextBox1.Text
    End If

    'Determine date suffix
    Dim datsuff As String = ""

    Select Case CInt(Datewc.Day)
        Case 1 Or 21 Or 31
            datsuff = "st"
        Case 2 Or 22
            datsuff = "nd"
        Case 3 Or 23
            datsuff = "rd"
        Case Else
            datsuff = "th"
    End Select

Body:
Parse you date

Dim dDate As DateTime =
  DateTime.ParseExact(TextBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)

Change your code a little, should work.
Day function returns integer, no need to Cast using CInt.

 'Determine date suffix
Dim datsuff As String = ""

Select Case Datewc.Day
    Case 1 , 21 , 31
        datsuff = "st"
    Case 2 , 22
        datsuff = "nd"
    Case 3 , 23
        datsuff = "rd"
    Case Else
        datsuff = "th"
End Select

Explanation

Case 2 Or 22 means Case ((2 Or 22) ==true), It will be false hence going to else part.


问:
Singleton CDI @Inject null pointer exception
I need to fire events from some ejb (Stateless and Singleton) using dependency injection. I do not use Spring, Guice etc.
The problem is that I get NPE in one of beans when calling its method through getInstance(). Here is the code snippet:

```<code>@Stateless
@LocalBean
public class ControllerStartStop {
    @Inject
    private Event<SomeWebMessage> webEvent;

    public String startCircle(String passwordP, String passwordH) {
    .........
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));   // this works fine
    MainDay.getInstance().startDay();      // NullPointerException
</code>```

Here is MainDay singleton:

```<code>@Singleton
public class MainDay {
    private static final MainDay mDay = new MainDay();
    public static MainDay getInstance() {   return mDay ;   }

    @Inject
    private Event<SomeWebMessage> webEvent;

    public void startDay() {
        String s = new String("MainDay");
        webEvent.fire(new SomeWebMessage(s,0));   // NullPointerException
</code>```

beans.xml is in META-INF:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">

</beans>
</code>```

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*.
I have no idea what is the reason

答:
Note that @Singleton means that the container (EJB or CDI, depends on which annotation it is) will manage the instance, i.e. you shouldn't create it yourself.

If you create the instance via private static final MainDay mDay = new MainDay(); there won't be any injection by the container and thus webEvent will be null. Besides that the container won't know about that instance and using  @Inject MainDay somewhere else is very likely to produce another instance.

Thus just use inject (or lookups if you need to) directly:

```<code>class ControllerStartStop  {
  @Inject
  private MainDay mDay;

  ...
  public String startCircle(String passwordP, String passwordH) {
    ...
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));
    mDay.startDay();
    ...
  }
</code>```

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*. I have no idea what is the reason

Without knowing your code it's only a guess but I'd assume you're injecting MainDay here or using a CDI/JNDI lookup. Hence the container will create an instance if there is none and will inject the Event objects.

Body:
I need to fire events from some ejb (Stateless and Singleton) using dependency injection. I do not use Spring, Guice etc.
The problem is that I get NPE in one of beans when calling its method through getInstance(). Here is the code snippet:

@Stateless
@LocalBean
public class ControllerStartStop {
    @Inject
    private Event<SomeWebMessage> webEvent;

    public String startCircle(String passwordP, String passwordH) {
    .........
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));   // this works fine
    MainDay.getInstance().startDay();      // NullPointerException

Here is MainDay singleton:

@Singleton
public class MainDay {
    private static final MainDay mDay = new MainDay();
    public static MainDay getInstance() {   return mDay ;   }

    @Inject
    private Event<SomeWebMessage> webEvent;

    public void startDay() {
        String s = new String("MainDay");
        webEvent.fire(new SomeWebMessage(s,0));   // NullPointerException

beans.xml is in META-INF:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">

</beans>

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*.
I have no idea what is the reason

Body:
Note that @Singleton means that the container (EJB or CDI, depends on which annotation it is) will manage the instance, i.e. you shouldn't create it yourself.

If you create the instance via private static final MainDay mDay = new MainDay(); there won't be any injection by the container and thus webEvent will be null. Besides that the container won't know about that instance and using  @Inject MainDay somewhere else is very likely to produce another instance.

Thus just use inject (or lookups if you need to) directly:

class ControllerStartStop  {
  @Inject
  private MainDay mDay;

  ...
  public String startCircle(String passwordP, String passwordH) {
    ...
    String res = "some msg";
    webEvent.fire(new SomeWebMessage(res, 0));
    mDay.startDay();
    ...
  }

There is no NPE when I fire event from a call of static method like MainDay.initDS() or when method startDay() is invoked by a Sheduler (@Schedule(hour = "", minute = "", second = "/10")*. I have no idea what is the reason

Without knowing your code it's only a guess but I'd assume you're injecting MainDay here or using a CDI/JNDI lookup. Hence the container will create an instance if there is none and will inject the Event objects.


问:
git merge appear conflict,how to solve?
My project have a master and a branch named develop. I write some code in a java file named A in develop, than i  switch to the master . when I merge the develop branch, i get the latest code of develop branch  to master. Until now,no errors. But problems appear behind! i switch to branch name develop,when i continue write some code  in the file named A in develop.than I push the file to remote branch named develop. I switch to master, and merge the develop branch. appear conflict in the file named A! why ? and Please tell how to sole it .  if i merge the file conflict continue. There are  still conflicts in the file in next.! Please help me to solve it !</p>

答:
If there are multiple people working on this project, I'd recommend taking a pull from the remote branch before making any changes. This would help avoid the merge conflicts that may arise as other people might be making changes to the same file.

If you are the only one making a change in this project, I'd recommend taking a look at this document Git Branching - Basic Branching and Merging , especially under the Basic Merge Conflicts heading.

Title: git merge appear conflict,how to solve?


问:
php image type, mozila and IE7
i insert image in page and strangely I get a picture of the types.

show type with: $_FILES['img']['type'].

Result:

```<code>Firefox: image/jpeg
IE7: 'image/pjpeg'

Firefox: image/png
IE7: image/x-png
</code>```

Now i use this filter:

```<code>$type_filter = array('image/gif', 'image/jpeg', 'image/png', 'image/jpg', 'image/bmp', 'image/x-png', 'image/pjpeg');
</code>```

It is good, or something else is missing?
Thanks

答:
I usually do something like this:</p>

```<code>if(stristr($_FILES['image']['type'], "image")){
enter code here
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: php image type, mozila and IE7

Body:
i insert image in page and strangely I get a picture of the types.

show type with: $_FILES['img']['type'].

Result:

Firefox: image/jpeg
IE7: 'image/pjpeg'

Firefox: image/png
IE7: image/x-png

Now i use this filter:

$type_filter = array('image/gif', 'image/jpeg', 'image/png', 'image/jpg', 'image/bmp', 'image/x-png', 'image/pjpeg');

It is good, or something else is missing?
Thanks

Body:
I usually do something like this:

if(stristr($_FILES['image']['type'], "image")){
enter code here
}


问:
Traverse through each row for a column text
I have a below grid

The html code is at pastebin.com/GBP3AZNQ

I want to verify whether "test123" is present. I want to traverse through each row of column master obligationname and look for the text test123.

Can anyone guide me how to do this?

答:
check this code out. it check if the given text is available in the table.</p>

```<code>    this.searchCourseGrid = function(course){
          var row = element.all(by.css('css path to tr'));
          var cells = row.all(by.tagName('td'));
          var cellTexts = cells.map(function (cell) {
          return cell.getText();
          }).then(function(cellTexts){
            expect(cellTexts).toContain(course);
          });
};
</code>```

Body:
check this code out. it check if the given text is available in the table.

    this.searchCourseGrid = function(course){
          var row = element.all(by.css('css path to tr'));
          var cells = row.all(by.tagName('td'));
          var cellTexts = cells.map(function (cell) {
          return cell.getText();
          }).then(function(cellTexts){
            expect(cellTexts).toContain(course);
          });
};


问:
How to detect if a particular string is present at the start of a new line inside a textarea using javascript?
I have a text area where I need detect if '+' is followed by a space character at the start of each new line.I can get the keyCode on keyDown event,However this will return the keyCode even if the character is present in the middle of the string.I need to call a function only if the particular character combination is at the start of the new line in the text area.Could any one suggest me how to do this?</p>

答:
You need to intercept when the user put the string + and (space) in a textarea and check in what position is it.

You could check the previous characters of last digited key, so:

Listen on key down event

Check if last key is space (because is the last char of the sequence you're looking for)

Then check the previous characters, in your case a newLine (\n) followed by the string "+ "

$("#test").keydown(function(e){
  if(e.key==' ')
    console.log(startsWith(e.target, '\n+'));
});

/*
  Returns true when:
  - text in 'target' starts with 'exp'
  - starting by current cursor position
*/
function startsWith(target, exp){
  var expLen = exp.length;
  var str = $(target).val();
  if(target.selectionStart > expLen){
    str = $(target).val();
  } else {
    if("\n" + $(target).val() == exp){
      return true;
    }
  }

  var start = target.selectionStart - expLen;

  var subStr = $(target).val().substr(start, expLen);
  if(subStr==exp) {
    return true;
  } else {
    return false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test"></textarea></code>```

Note:
I added following condition

```<code>if(target.selectionStart > expLen){
  str = $(target).val();
} else {
  if("\n" + $(target).val() == exp){
    return true;
  }
}
</code>```

To find "+ " expression at the begin of the textarea's text.

I hope it helps you. Bye.

Body:
You need to intercept when the user put the string + and (space) in a textarea and check in what position is it.

You could check the previous characters of last digited key, so:

Listen on key down event

Check if last key is space (because is the last char of the sequence you're looking for)

Then check the previous characters, in your case a newLine (\n) followed by the string "+ "

$("#test").keydown(function(e){
  if(e.key==' ')
    console.log(startsWith(e.target, '\n+'));
});

/*
  Returns true when:
  - text in 'target' starts with 'exp'
  - starting by current cursor position
*/
function startsWith(target, exp){
  var expLen = exp.length;
  var str = $(target).val();
  if(target.selectionStart > expLen){
    str = $(target).val();
  } else {
    if("\n" + $(target).val() == exp){
      return true;
    }
  }

  var start = target.selectionStart - expLen;

  var subStr = $(target).val().substr(start, expLen);
  if(subStr==exp) {
    return true;
  } else {
    return false;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test"></textarea>

Note:
I added following condition

if(target.selectionStart > expLen){
  str = $(target).val();
} else {
  if("\n" + $(target).val() == exp){
    return true;
  }
}

To find "+ " expression at the begin of the textarea's text.

I hope it helps you. Bye.


问:
Android how to get location update in batch
I am trying to get location update in background with the batched version of Fused Location Provider Api.

I am doing this by following Google guidelines by requesting a location updates with a callback on a broadcast PendingIntent.

For the location request I used setMaxWaitTime to get the location update results in batched as specific by Google API documentation.

My problem is that my broadcast receiver didn’t get the location in batch and still get one location at a time from location service.

I also tried a new PendingIntent location update sample project from google but the location update still return only one location at a time.

For information I tested on a Nexus 5X device as it has a batching sensor hardware.

Am I missing something ?

Here is an example of the code :

Build and connected Google Api Client

```<code>private static final long UPDATE_INTERVAL = 60000; // Every 60 seconds.
private static final long FASTEST_UPDATE_INTERVAL = 30000; // Every 30 seconds
private static final long MAX_WAIT_TIME = 60000 * 5; // Batch every 5 minutes.

public void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setMaxWaitTime(MAX_WAIT_TIME);

    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle connectionHint) {
    try {
        // Create a pending intent to listening on location service when the update become available
        Intent mIntent = new Intent(context, LocationReceiver.class);
        mPendingIntent = PendingIntent.getBroadcast(context, 42, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        // Permission check before launching location services
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

BroadcastReceiver class

```<code>public class LocationReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
    try {

        // Check if intent has location result
        if (LocationResult.hasResult(intent)) {
            // Get our location from the LocationResult
            LocationResult locationResult = LocationResult.extractResult(intent);
            if (locationResult != null) {

                List<Location> locations = locationResult.getLocations();

                for (Location location : locations) {
                    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.FRANCE);
                    String dateString = formatter.format(new java.util.Date(location.getTime()));

                    Log.d(TAG, "LOCATION: lat:" + location.getLatitude() + " long:" + location.getLongitude() +
                            " radius:" + location.getAccuracy() + " date:" + dateString);
                }

            } else {
                Log.d(TAG, "Location is null");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

}

Thanks for any help.

答:
After testing for a few days it seems that location batching is working with my code.

I noticed that I have to move with my phone for batching to work and it is random. Some time location update will be delayed and delivered a batch and sometime it will deliver just one location.

Body:
I am trying to get location update in background with the batched version of Fused Location Provider Api.

I am doing this by following Google guidelines by requesting a location updates with a callback on a broadcast PendingIntent.

For the location request I used setMaxWaitTime to get the location update results in batched as specific by Google API documentation.

My problem is that my broadcast receiver didn’t get the location in batch and still get one location at a time from location service.

I also tried a new PendingIntent location update sample project from google but the location update still return only one location at a time.

For information I tested on a Nexus 5X device as it has a batching sensor hardware.

Am I missing something ?

Here is an example of the code :

Build and connected Google Api Client

private static final long UPDATE_INTERVAL = 60000; // Every 60 seconds.
private static final long FASTEST_UPDATE_INTERVAL = 30000; // Every 30 seconds
private static final long MAX_WAIT_TIME = 60000 * 5; // Batch every 5 minutes.

public void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    mLocationRequest.setMaxWaitTime(MAX_WAIT_TIME);

    mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle connectionHint) {
    try {
        // Create a pending intent to listening on location service when the update become available
        Intent mIntent = new Intent(context, LocationReceiver.class);
        mPendingIntent = PendingIntent.getBroadcast(context, 42, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        // Permission check before launching location services
        if (ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

BroadcastReceiver class

public class LocationReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
    try {

        // Check if intent has location result
        if (LocationResult.hasResult(intent)) {
            // Get our location from the LocationResult
            LocationResult locationResult = LocationResult.extractResult(intent);
            if (locationResult != null) {

                List<Location> locations = locationResult.getLocations();

                for (Location location : locations) {
                    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.FRANCE);
                    String dateString = formatter.format(new java.util.Date(location.getTime()));

                    Log.d(TAG, "LOCATION: lat:" + location.getLatitude() + " long:" + location.getLongitude() +
                            " radius:" + location.getAccuracy() + " date:" + dateString);
                }

            } else {
                Log.d(TAG, "Location is null");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Thanks for any help.


问:
How can I make a div 80% the size of the page?
I'd like to make a page container div have a top margin of 10% and bottom margin of 10%. How can I make the div take the remaining 80% of the page, all the time ( no matter if it has content or not )?</p>

答:
This should work:</p>

```<code><!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            div {
                position: absolute;
                height: 80%;
                width: 80%;
                top: 10%;
                left: 10%;
                background-color: #FFCC00;
            }
        </style>
    </head>
    <body>
        <div>
            This should prove my point.
        </div>
    </body>
</html>
</code>```

Body:
This should work:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            div {
                position: absolute;
                height: 80%;
                width: 80%;
                top: 10%;
                left: 10%;
                background-color: #FFCC00;
            }
        </style>
    </head>
    <body>
        <div>
            This should prove my point.
        </div>
    </body>
</html>


问:
How can I create an interactive object in pygame?
In a pygame program I am creating, I have need for an interactive object on the screen that will call a function when the player character moves onto it and presses the enter key. Here is the code I have so far:

```<code>import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP] and y > 0: y -= 5
    if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
    if pressed[pygame.K_LEFT] and x > 0: x -= 5
    if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    myfont = pygame.font.SysFont("monospace", 15)

    label = myfont.render("Start the experiment simulator", 1, (255,255,255))
    screen.blit(label, (100, 100))

    label2 = myfont.render("Start the quiz", 1, (255,255,255))
    screen.blit(label2, (550, 100))

    label3 = myfont.render("Quit game", 1, (255,255,255))
    screen.blit(label3, (350, 400))

    pygame.draw.rect(screen, red, pygame.Rect(600, 125, 30, 30))
    pygame.draw.rect(screen, red, pygame.Rect(225, 125, 30, 30))
    pygame.draw.rect(screen, red, pygame.Rect(375, 425, 30, 30))

    pygame.display.flip()
    clock.tick(60)
</code>```

At the moment, the object is just a test so would be best to be a small red rectangle, about half the size of the player, that I can replace with an icon later on. This rectangle should be placed below the 'quit game' label on the pygame window and quit the game when interacted with. This is one method that I have tried so far:

```<code>if pressed[pygame.K_RETURN] and x >= 375 or x <= 405 and y >=425 or y <= 455:
            pygame.display.quit()
            pygame.quit()
            sys.exit()
</code>```

Where theoretically the system checks if the user is in a specific area and has pressed the enter key before performing the command.

答:
Answer to my own question, I managed to make my first attempt work by adding brackets around the x and y checks in this section:

```<code>and x >= 375 or x <= 405 and y >=425 or y <= 455:
</code>```

So that it now reads:

```<code>and (x >= 375 and x <= 405) and (y >= 425 and y <= 455):
</code>```

Body:
In a pygame program I am creating, I have need for an interactive object on the screen that will call a function when the player character moves onto it and presses the enter key. Here is the code I have so far:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP] and y > 0: y -= 5
    if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
    if pressed[pygame.K_LEFT] and x > 0: x -= 5
    if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    myfont = pygame.font.SysFont("monospace", 15)

    label = myfont.render("Start the experiment simulator", 1, (255,255,255))
    screen.blit(label, (100, 100))

    label2 = myfont.render("Start the quiz", 1, (255,255,255))
    screen.blit(label2, (550, 100))

    label3 = myfont.render("Quit game", 1, (255,255,255))
    screen.blit(label3, (350, 400))

    pygame.draw.rect(screen, red, pygame.Rect(600, 125, 30, 30))
    pygame.draw.rect(screen, red, pygame.Rect(225, 125, 30, 30))
    pygame.draw.rect(screen, red, pygame.Rect(375, 425, 30, 30))

    pygame.display.flip()
    clock.tick(60)

At the moment, the object is just a test so would be best to be a small red rectangle, about half the size of the player, that I can replace with an icon later on. This rectangle should be placed below the 'quit game' label on the pygame window and quit the game when interacted with. This is one method that I have tried so far:

if pressed[pygame.K_RETURN] and x >= 375 or x <= 405 and y >=425 or y <= 455:
            pygame.display.quit()
            pygame.quit()
            sys.exit()

Where theoretically the system checks if the user is in a specific area and has pressed the enter key before performing the command.

Body:
Answer to my own question, I managed to make my first attempt work by adding brackets around the x and y checks in this section:

and x >= 375 or x <= 405 and y >=425 or y <= 455:

So that it now reads:

and (x >= 375 and x <= 405) and (y >= 425 and y <= 455):


问:
In Skylark - given Label - how to read the tags of the original rule
In my skylark (bazel) rule implementation, I have a depset of File objects from which I extract a depset of Label Objects.

In common attributes I found that all skylark rules may have tags attribute, where I can give a list of free strings.

Is there any way I can reach the tags of the original rule?

(my final goal is to extract from the original depset the files that are originated from rule with tag "X").

答:
Rules propagate information downstream (to rules depending on them) via Providers. Providers are pieces of information (structs) that a rule can either return or not. I find it useful to view Providers as interfaces a rule can choose to implement. For example a Skylark rule that returns a cc provider can be viewed as if it implemented the C++ rule interface, so we can expect it to be a meaningful dependency of C++ rules and of any rule that happens to read cc providers. If the rule doesn't implement the java provider though, then we can't expect it to work as a java rule's dependency.

A rule can only access information in its direct dependencies, and only via Providers. Therefore to access the tags of a dependency, the dependency would have to expose a Provider with that information. AFAIK there's no such provider that a rule could expose, but if the dependent rules (whose tags you want to extract) are also Skylark rules and you can modify their implementation, then just return a custom provider with their tags in it and you're done.

If however you want to depend on native *_test rules for example (the ones typically using tags), you'll need to employ a wrapper.

The basic idea is to write a Skylark macro to wrap such rules. Instead of writing e.g. cc_test(..., tags=...) in the BUILD file, you'd write my_macro(..., tags=...).

The macro's implementation would instantiate two rules: the native.cc_test and a simple Skylark rule (that you have to implement) which only has a tags attribute and a single label attribute for the test rule. The macro passes the tags to both rules (plus the rest of the attributes to the cc_test), and the Skylark rule depends on the test rule so it has access to its depset of files, and can return a custom provider with the depset and the tags data within one struct.


问:
C# .NET standard 1.6 with excessive dependencies in published application
I am trying out Visual Studio 2017 and .NET Core in what is my first attempt at C#/.NET in a few years (returning from Golang). I tried to create a small hello world style networking application that just listens and echos the input from tcp clients:

```<code>using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace TaskSockets
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            TcpListener server = new TcpListener(IPAddress.Any, 5555);
            server.Start();

            while (true)
            {
                TcpClient newClient = server.AcceptTcpClientAsync().Result;

                Task.Run(async () => {

                    StreamWriter sWriter = new StreamWriter(newClient.GetStream(), Encoding.ASCII);
                    StreamReader sReader = new StreamReader(newClient.GetStream(), Encoding.ASCII);

                    Boolean bClientConnected = true;
                    String sData = null;

                    while (bClientConnected)
                    {
                        sData = await sReader.ReadLineAsync();

                        Console.WriteLine("Client: " + sData);
                    }
                });
            }

        }
    }
}
</code>```

My project/build config looks like the following:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netstandard1.6</TargetFramework>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
  </PropertyGroup>
  <ItemGroup>
     <PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.1.1" />
     <PackageReference Include="Microsoft.NETCore.DotNetHostPolicy" Version="1.1.0" />
   </ItemGroup>

</Project>
</code>```

After publishing the application (dotnet publish) I get a folder with the executable I need. The problem I encounter, however, is that the folder contains 205 files (mostly .NET related DLL files) and is more than 30 MB in size. This includes dll files with reference to .NET libraries I don't even use such as System.Xml and Linq.

Is there any way to reduce the number of files and size of the published application so that just what I need is included?

UPDATE:
Tried to re-create the project from scratch using the dotnet tool rather than visual studio:

dotnet new console --language C# --name Socket --output Socket
  --framework netcoreapp1.0

This created this project (which for some reason compiles to a dll despite the exe output type and console application target):

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
</Project>
</code>```

Then manually modify the csproj file so it looks like this:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
  </PropertyGroup>
  <ItemGroup>
     <PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.0.6" />
   </ItemGroup>
</Project>
</code>```

Now publish with:

dotnet publish --runtime win7-x64 --configuration Release

And go to:

./bin/Release/netcoreapp1.0/win7-x64

Now suddenly there is a working exe-file and just a few DLL files that is approximately 1 MB in size. By deleting the subfolder called "publish" I now have something that works without most of the bloat. No idea why this worked and if its considered expected behavior. No idea what the publish folder is for either or whether or not its needed for deployment on a computer without .NET installed. Microsoft have some work to do on its documentation.

答:
Have a look at https://learn.microsoft.com/en-us/dotnet/articles/core/deploying/index

In the 1st case, your publish command generates output for a Framework-dependent deployment that is relying on the presence of the .NET Core framework on the target machine. Your code (in the form of dll(s)) will be executed by the runtime.

In the 2nd case, when you specify the target runtime using the --runtime option, publish generates output for a Self-contained deployment in which the used version of the .NET Core framework is included. There's a way to reduce the total size of the output as described in the above mention article in the Deploying a self-contained deployment with a smaller footprintsection.

As for why <OutputType>Exe</OutputType> didn't generate a exe-file, check out https://learn.microsoft.com/en-us/dotnet/articles/core/tools/dotnet-build

It basically says the generated

binaries include the project's code in Intermediate Language (IL)
  files with a .dll extension

and that the difference between specifying and not specifying <OutputType>Exe</OutputType>

is that the IL DLL for a library doesn't contain entry points and
  can't be executed.

Body:
I am trying out Visual Studio 2017 and .NET Core in what is my first attempt at C#/.NET in a few years (returning from Golang). I tried to create a small hello world style networking application that just listens and echos the input from tcp clients:

using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;

namespace TaskSockets
{
    class Program
    {

        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            TcpListener server = new TcpListener(IPAddress.Any, 5555);
            server.Start();

            while (true)
            {
                TcpClient newClient = server.AcceptTcpClientAsync().Result;

                Task.Run(async () => {

                    StreamWriter sWriter = new StreamWriter(newClient.GetStream(), Encoding.ASCII);
                    StreamReader sReader = new StreamReader(newClient.GetStream(), Encoding.ASCII);

                    Boolean bClientConnected = true;
                    String sData = null;

                    while (bClientConnected)
                    {
                        sData = await sReader.ReadLineAsync();

                        Console.WriteLine("Client: " + sData);
                    }
                });
            }

        }
    }
}

My project/build config looks like the following:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netstandard1.6</TargetFramework>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
  </PropertyGroup>
  <ItemGroup>
     <PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.1.1" />
     <PackageReference Include="Microsoft.NETCore.DotNetHostPolicy" Version="1.1.0" />
   </ItemGroup>

</Project>

After publishing the application (dotnet publish) I get a folder with the executable I need. The problem I encounter, however, is that the folder contains 205 files (mostly .NET related DLL files) and is more than 30 MB in size. This includes dll files with reference to .NET libraries I don't even use such as System.Xml and Linq.

Is there any way to reduce the number of files and size of the published application so that just what I need is included?

UPDATE:
Tried to re-create the project from scratch using the dotnet tool rather than visual studio:

dotnet new console --language C# --name Socket --output Socket
  --framework netcoreapp1.0

This created this project (which for some reason compiles to a dll despite the exe output type and console application target):

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
  </PropertyGroup>
</Project>

Then manually modify the csproj file so it looks like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.0</TargetFramework>
    <RuntimeIdentifiers>win7-x64</RuntimeIdentifiers>
  </PropertyGroup>
  <ItemGroup>
     <PackageReference Include="Microsoft.NETCore.Runtime.CoreCLR" Version="1.0.6" />
   </ItemGroup>
</Project>

Now publish with:

dotnet publish --runtime win7-x64 --configuration Release

And go to:

./bin/Release/netcoreapp1.0/win7-x64

Now suddenly there is a working exe-file and just a few DLL files that is approximately 1 MB in size. By deleting the subfolder called "publish" I now have something that works without most of the bloat. No idea why this worked and if its considered expected behavior. No idea what the publish folder is for either or whether or not its needed for deployment on a computer without .NET installed. Microsoft have some work to do on its documentation.


问:
What's the meaning of p = (int(*)[3])malloc(3*sizeof(*p));
```<code>#include<stdio.h>
#include<stdlib.h>

int main()
{
     int i, j;
     int(*p)[3];
     p = (int(*)[3])malloc(3*sizeof(*p));
     for(i=0; i<3; i++)
     {
         for(j=0; j<3; j++)
             printf("%d", p[i][j]);
     }
     return 0;
}
</code>```

<p>p is a pointer to an array of 3 integer then why it is behaving as a 2D array </p>

答:
It is a completely superfluous cast that only adds clutter. Or in case of C++ it is needed, but you should never be using malloc in C++...

p is an array pointer to an array of type int [3]. *p is an array and therefore 3*sizeof(*p) gives the size of 3 such arrays, 3*3*sizeof(int). So the code allocates an array of arrays - a 2D array.

p is set to point at the first element of that array. p[i] is pointer arithmetic on an array pointer and gives you array number i. Therefore a pointer to a 1D array can be used to access a 2D array.

A better way to write the malloc call would be this:

```<code>p = malloc( sizeof(int[3][3]) );
</code>```

You example never initializes the arrays, so printing their contents would give garbage and possibly undefined behavior. Corrected code:

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

int main (void)
{
     int(*p)[3];
     p = malloc( sizeof(int[3][3]) );
     for(size_t i=0; i<3; i++)
     {
         for(size_t j=0; j<3; j++)
         {
             p[i][j] = (int)j;
             printf("%d ", p[i][j]);
         }
         printf("\n");
     }

     free(p);
     return 0;
}
</code>```

Related topic: Correctly allocating multi-dimensional arrays.

Body:
#include<stdio.h>
#include<stdlib.h>

int main()
{
     int i, j;
     int(*p)[3];
     p = (int(*)[3])malloc(3*sizeof(*p));
     for(i=0; i<3; i++)
     {
         for(j=0; j<3; j++)
             printf("%d", p[i][j]);
     }
     return 0;
}

p is a pointer to an array of 3 integer then why it is behaving as a 2D array

Body:
It is a completely superfluous cast that only adds clutter. Or in case of C++ it is needed, but you should never be using malloc in C++...

p is an array pointer to an array of type int [3]. *p is an array and therefore 3*sizeof(*p) gives the size of 3 such arrays, 3*3*sizeof(int). So the code allocates an array of arrays - a 2D array.

p is set to point at the first element of that array. p[i] is pointer arithmetic on an array pointer and gives you array number i. Therefore a pointer to a 1D array can be used to access a 2D array.

A better way to write the malloc call would be this:

p = malloc( sizeof(int[3][3]) );

You example never initializes the arrays, so printing their contents would give garbage and possibly undefined behavior. Corrected code:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
     int(*p)[3];
     p = malloc( sizeof(int[3][3]) );
     for(size_t i=0; i<3; i++)
     {
         for(size_t j=0; j<3; j++)
         {
             p[i][j] = (int)j;
             printf("%d ", p[i][j]);
         }
         printf("\n");
     }

     free(p);
     return 0;
}

Related topic: Correctly allocating multi-dimensional arrays.


问:
Linq query to check substring between a list and string
I have a list of strings and a string, and I want that if the string contains any of the string which is present in the list the system returns false. I am using following lambda expression:

```<code> result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper() == lo_operandVal.ToString().ToUpper());
</code>```

Following is the dataset:

lo_operandVal = "ABC DEF GHI Post Office Box"
ro_operandVal is the list of strings with following elements:

Post Office Box

P.O. BOX

when I evaluate this expression it always returns true.

答:
Use .Contains() to see if the text is contained within the list, instead of trying to match strings exactly using the equals operator.

```<code> result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper().Contains(lo_operandVal.ToString().ToUpper()));
</code>```

Body:
I have a list of strings and a string, and I want that if the string contains any of the string which is present in the list the system returns false. I am using following lambda expression:

 result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper() == lo_operandVal.ToString().ToUpper());

Following is the dataset:

lo_operandVal = "ABC DEF GHI Post Office Box"
ro_operandVal is the list of strings with following elements:

Post Office Box

P.O. BOX

when I evaluate this expression it always returns true.

Body:
Use .Contains() to see if the text is contained within the list, instead of trying to match strings exactly using the equals operator.

 result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper().Contains(lo_operandVal.ToString().ToUpper()));


问:
Moving data in one table to another table Based on condition
I need help in figuring out the solution for my problem.

1. I have a 4 tables

```<code>a. CLientdetails
b. ClientAccountDetails
c. ClientExistingData
d. ClientNotExistindata.
</code>```

Clinet details contains data related to the name of the client, startingdate, endingDate

ClientAccountDetails contains data related to specific client(ie multiple accounts asscoiated with his name, status of the account, money)

using SSIS package i import data from Excel sheet(data related to excel sheet is of ClientAccountDetails) into a different table called IMPORTClientDetails.

when all the data gets imported to the table using ssis package. i would write some query to move that into the ClientAccountDetails table based on the Name of the Client.

2. My question is

If the Client name from IMPORTClientDetails doesnot exist in the ClientDetails table i want the data to be moved to ClientNotExistindata

if the Client name from IMPORTClientDetails  exist then i want to move that into ClientAccountDetails

答:
This can be done with two simple INSERT/SELECT statements.</p>

```<code>INSERT INTO ClientAccountDetails(COLUMN1,COLUMN2, ETC)
SELECT COLUMN3,COLUMN4, ETC
FROM IMPORTClientDetails ICD
WHERE ICD.Client IN (SELECT Client FROM ClientDetails);

INSERT INTO ClientNotExistindata(COLUMN1,COLUMN2, ETC)
SELECT COLUMN3,COLUMN4, ETC
FROM IMPORTClientDetails ICD
WHERE ICD.Client NOT IN (SELECT Client FROM ClientDetails);
</code>```

Body:
I need help in figuring out the solution for my problem.

1. I have a 4 tables

a. CLientdetails
b. ClientAccountDetails
c. ClientExistingData
d. ClientNotExistindata.

Clinet details contains data related to the name of the client, startingdate, endingDate

ClientAccountDetails contains data related to specific client(ie multiple accounts asscoiated with his name, status of the account, money)

using SSIS package i import data from Excel sheet(data related to excel sheet is of ClientAccountDetails) into a different table called IMPORTClientDetails.

when all the data gets imported to the table using ssis package. i would write some query to move that into the ClientAccountDetails table based on the Name of the Client.

2. My question is

If the Client name from IMPORTClientDetails doesnot exist in the ClientDetails table i want the data to be moved to ClientNotExistindata

if the Client name from IMPORTClientDetails  exist then i want to move that into ClientAccountDetails

Body:
This can be done with two simple INSERT/SELECT statements.

INSERT INTO ClientAccountDetails(COLUMN1,COLUMN2, ETC)
SELECT COLUMN3,COLUMN4, ETC
FROM IMPORTClientDetails ICD
WHERE ICD.Client IN (SELECT Client FROM ClientDetails);

INSERT INTO ClientNotExistindata(COLUMN1,COLUMN2, ETC)
SELECT COLUMN3,COLUMN4, ETC
FROM IMPORTClientDetails ICD
WHERE ICD.Client NOT IN (SELECT Client FROM ClientDetails);


问:
How to loop SELECT SUM of daily MAX and MIN
I have 2 tables that I'm trying to select, unit and feed.

Table unit is a metadata table that contains

```<code>unitid, userid, guid, fields, createdat
</code>```

and the other table, feed, contains

```<code>feedid, unitid, value, createdat
</code>```

Sample data for table unit:

```
1,1000,'0b243396-a015-11e6-8001-9cf387d90940','a','2016-11-04 21:36:32.71281'
2,1000,'0b243396-a015-11e6-8001-9cf387d90941','b','2016-11-04 21:40:32.71281'
3,1001,'0b243396-a015-11e6-8001-9cf387d90942','b','2016-11-04 21:47:32.71281'
4,1001,'0b243396-a015-11e6-8001-9cf387d90943','c','2016-11-04 21:50:32.71281'
```

and table feed:

```
1,1,'0.0021','2016-11-05 00:50:32.71281'
2,1,'0.0025','2016-11-05 01:00:32.71281'
3,2,'0.0008','2016-11-05 00:51:22.71281'
4,2,'0.0018','2016-11-05 01:01:22.71281'
...
24,1,'0.0800','2016-11-05 23:55:32.71281'
25,2,'0.0540','2016-11-05 23:55:32.71281'
```

What I'm trying to get is select total of MIN and MAX of every unit registered by userid = n.

I already tried this:

```<code>SELECT SUM(value::DOUBLE PRECISION)::text FROM
((SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat DESC LIMIT 1)
UNION ALL
(SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat ASC LIMIT 1)) t
</code>```

But I'm not sure where I should put the userid = n clause.

So how can I select total of MIN and MAX of every units registered by spesific userid? (daily interval)

答:
Is this what you are looking for?</p>

```<code>SELECT f.unitid,
       min(f.value) + max(f.value)
FROM unit u
   JOIN feed f ON u.id = f.unitid
WHERE u.userid = 1000
GROUP BY f.unitid;

┌────────┬──────────┐
│ unitid │ ?column? │
├────────┼──────────┤
│      1 │   0.0821 │
│      2 │   0.0548 │
└────────┴──────────┘
(2 rows)
</code>```

Body:
I have 2 tables that I'm trying to select, unit and feed.

Table unit is a metadata table that contains

unitid, userid, guid, fields, createdat

and the other table, feed, contains

feedid, unitid, value, createdat

Sample data for table unit:

1,1000,'0b243396-a015-11e6-8001-9cf387d90940','a','2016-11-04 21:36:32.71281'
2,1000,'0b243396-a015-11e6-8001-9cf387d90941','b','2016-11-04 21:40:32.71281'
3,1001,'0b243396-a015-11e6-8001-9cf387d90942','b','2016-11-04 21:47:32.71281'
4,1001,'0b243396-a015-11e6-8001-9cf387d90943','c','2016-11-04 21:50:32.71281'

and table feed:

1,1,'0.0021','2016-11-05 00:50:32.71281'
2,1,'0.0025','2016-11-05 01:00:32.71281'
3,2,'0.0008','2016-11-05 00:51:22.71281'
4,2,'0.0018','2016-11-05 01:01:22.71281'
...
24,1,'0.0800','2016-11-05 23:55:32.71281'
25,2,'0.0540','2016-11-05 23:55:32.71281'

What I'm trying to get is select total of MIN and MAX of every unit registered by userid = n.

I already tried this:

SELECT SUM(value::DOUBLE PRECISION)::text FROM
((SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat DESC LIMIT 1)
UNION ALL
(SELECT f.value FROM feed f, unit u WHERE f.unitid = unit.id AND f.createdat >= now()::date + interval '1h' ORDER BY f.createdat ASC LIMIT 1)) t

But I'm not sure where I should put the userid = n clause.

So how can I select total of MIN and MAX of every units registered by spesific userid? (daily interval)

Body:
Is this what you are looking for?

SELECT f.unitid,
       min(f.value) + max(f.value)
FROM unit u
   JOIN feed f ON u.id = f.unitid
WHERE u.userid = 1000
GROUP BY f.unitid;

┌────────┬──────────┐
│ unitid │ ?column? │
├────────┼──────────┤
│      1 │   0.0821 │
│      2 │   0.0548 │
└────────┴──────────┘
(2 rows)


问:
JavaFXPorts - Problems with ScrollBar on Mobile Devices
I'm currently developing a mobile application with JavaFX, using GluonHQ and JavaFXPorts. One of my screens contains a listview as you can see from the screenshot below, which was taken from my iPhone 6.

I have noticed the following problems with the scrollbar in mobile devices:

The first time i touch the screen the scroll bar appears a bit off place and then moves to the correct right position. This just happens quickly only the first time. (Screenshot)

I noticed that the scrollbar appears every time i touch the screen and not only when I touch and drag. On native iOS applications the scrollbar appears only when you touch and drag. If you keep your finger on screen and then remove it the scrollbar does not appear.

The scrollbar always takes some time to disappear when I remove my finger from the screen, whilst in native apps it disappears instantly.

Can anyone help me on fixing these issues. How can you define the time the scrollbar appears before it hides again?

You can experience this situation by just creating a ListView and load it with some items.

UPDATE

Thanks to the answer of Jose Pereda below, I have managed to overcome all three problems described above. Here is the code I used to reach the desired results. Watch this short video to get a quick idea of how the new scrolling bar appears and behaves. Again, Jose, you are the boss! Please go ahead with any comments for improvement.

```<code>public class ScrollBarView {

   public static void changeView(ListView<?> listView) {

       listView.skinProperty().addListener(new ChangeListener<Object>() {
           private StackPane thumb;
           private ScrollBar scrollBar;
           boolean touchReleased = true, inertia = false;

           @Override
           public void changed(ObservableValue<? extends Object> observable, Object oldValue, Object newValue) {
               scrollBar = (ScrollBar) listView.lookup(".scroll-bar");

               // "hide" thumb as soon as the scroll ends
               listView.setOnScrollFinished(e -> {
                  if (thumb != null) {
                     touchReleased = true;
                     playAnimation();
                  } // if
               });

               // Fix for 1. When user touches first time, the bar is set invisible so that user cannot see it is
               // placed in the wrong position.
               listView.setOnTouchPressed(e -> {
                  if (thumb == null) {
                     thumb = (StackPane) scrollBar.lookup(".thumb");
                     thumb.setOpacity(0);
                     initHideBarAnimation();
                  } // if
               });

               // Try to play animation whenever an inertia scroll takes place
               listView.addEventFilter(ScrollEvent.SCROLL, e -> {
                   inertia = e.isInertia();
                   playAnimation();
               });

               // As soon as the scrolling starts the thumb become visible.
               listView.setOnScrollStarted(e -> {
                   sbTouchTimeline.stop();
                   thumb.setOpacity(1);
                   touchReleased = false;
               });
           } // changed

           private Timeline sbTouchTimeline;
           private KeyFrame sbTouchKF1, sbTouchKF2;

           // Initialize the animation that hides the thumb when no scrolling takes place.
           private void initHideBarAnimation() {
              if (sbTouchTimeline == null) {
                 sbTouchTimeline = new Timeline();
                 sbTouchKF1 = new KeyFrame(Duration.millis(50), new KeyValue(thumb.opacityProperty(), 1));
                 sbTouchKF2 = new KeyFrame(Duration.millis(200), (e) -> inertia = false, new KeyValue(thumb.opacityProperty(), 0));
                 sbTouchTimeline.getKeyFrames().addAll(sbTouchKF1, sbTouchKF2);
              } // if
           } // initHideBarAnimation

           // Play animation whenever touch is released, and when an inertia scroll is running but thumb reached its bounds.
           private void playAnimation() {
              if(touchReleased)
                 if(!inertia || (scrollBar.getValue() != 0.0 && scrollBar.getValue() != 1))
                    sbTouchTimeline.playFromStart();
           } // playAnimation()
       });
   } // changeView
} // ScrollBarView
</code>```

答:
As mentioned in the comments, the first issue is known, and for now it hasn't been fixed. The problem seems to be related to the initial width of the scrollbar (20 pixels as in desktop), and then is set to 8 pixels (as in touch enabled devices), and moved to its final position with this visible shift of 12 pixels to the right.

As for the second and third issues, if you don't want to patch and build the JDK yourself, it is possible to override the default behavior, as the ScrollBar control is part of the VirtualFlow control of a ListView, and both can be found on runtime via lookups.

Once you have the control, you can play with its visibility according to your needs. The only problem with this property is that it is already bound and constantly called from the layoutChildren method.

This is quite a hacky solution, but it works for both 2) and 3):

```<code>public class BasicView extends View {

    private final ListView<String> listView;
    private ScrollBar scrollbar;
    private StackPane thumb;

    public BasicView(String name) {
        super(name);

        listView = new ListView<>();
        // add your items

        final InvalidationListener skinListener = new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                if (listView.getSkin() != null) {
                    listView.skinProperty().removeListener(this);
                    scrollbar = (ScrollBar) listView.lookup(".scroll-bar");
                    listView.setOnScrollFinished(e -> {
                        if (thumb != null) {
                            // "hide" thumb as soon as scroll/drag ends
                            thumb.setStyle("-fx-background-color: transparent;");
                        }
                    });
                    listView.setOnScrollStarted(e -> {
                        if (thumb == null) {
                            thumb = (StackPane) scrollbar.lookup(".thumb");
                        }
                        if (thumb != null) {
                            // "show" thumb again only when scroll/drag starts
                            thumb.setStyle("-fx-background-color: #898989;");
                        }
                    });

                }
            }
        };
        listView.skinProperty().addListener(skinListener);
        setCenter(listView);
    }

}
</code>```

Body:
I'm currently developing a mobile application with JavaFX, using GluonHQ and JavaFXPorts. One of my screens contains a listview as you can see from the screenshot below, which was taken from my iPhone 6.

I have noticed the following problems with the scrollbar in mobile devices:

The first time i touch the screen the scroll bar appears a bit off place and then moves to the correct right position. This just happens quickly only the first time. (Screenshot)

I noticed that the scrollbar appears every time i touch the screen and not only when I touch and drag. On native iOS applications the scrollbar appears only when you touch and drag. If you keep your finger on screen and then remove it the scrollbar does not appear.

The scrollbar always takes some time to disappear when I remove my finger from the screen, whilst in native apps it disappears instantly.

Can anyone help me on fixing these issues. How can you define the time the scrollbar appears before it hides again?

You can experience this situation by just creating a ListView and load it with some items.

UPDATE

Thanks to the answer of Jose Pereda below, I have managed to overcome all three problems described above. Here is the code I used to reach the desired results. Watch this short video to get a quick idea of how the new scrolling bar appears and behaves. Again, Jose, you are the boss! Please go ahead with any comments for improvement.

public class ScrollBarView {

   public static void changeView(ListView<?> listView) {

       listView.skinProperty().addListener(new ChangeListener<Object>() {
           private StackPane thumb;
           private ScrollBar scrollBar;
           boolean touchReleased = true, inertia = false;

           @Override
           public void changed(ObservableValue<? extends Object> observable, Object oldValue, Object newValue) {
               scrollBar = (ScrollBar) listView.lookup(".scroll-bar");

               // "hide" thumb as soon as the scroll ends
               listView.setOnScrollFinished(e -> {
                  if (thumb != null) {
                     touchReleased = true;
                     playAnimation();
                  } // if
               });

               // Fix for 1. When user touches first time, the bar is set invisible so that user cannot see it is
               // placed in the wrong position.
               listView.setOnTouchPressed(e -> {
                  if (thumb == null) {
                     thumb = (StackPane) scrollBar.lookup(".thumb");
                     thumb.setOpacity(0);
                     initHideBarAnimation();
                  } // if
               });

               // Try to play animation whenever an inertia scroll takes place
               listView.addEventFilter(ScrollEvent.SCROLL, e -> {
                   inertia = e.isInertia();
                   playAnimation();
               });

               // As soon as the scrolling starts the thumb become visible.
               listView.setOnScrollStarted(e -> {
                   sbTouchTimeline.stop();
                   thumb.setOpacity(1);
                   touchReleased = false;
               });
           } // changed

           private Timeline sbTouchTimeline;
           private KeyFrame sbTouchKF1, sbTouchKF2;

           // Initialize the animation that hides the thumb when no scrolling takes place.
           private void initHideBarAnimation() {
              if (sbTouchTimeline == null) {
                 sbTouchTimeline = new Timeline();
                 sbTouchKF1 = new KeyFrame(Duration.millis(50), new KeyValue(thumb.opacityProperty(), 1));
                 sbTouchKF2 = new KeyFrame(Duration.millis(200), (e) -> inertia = false, new KeyValue(thumb.opacityProperty(), 0));
                 sbTouchTimeline.getKeyFrames().addAll(sbTouchKF1, sbTouchKF2);
              } // if
           } // initHideBarAnimation

           // Play animation whenever touch is released, and when an inertia scroll is running but thumb reached its bounds.
           private void playAnimation() {
              if(touchReleased)
                 if(!inertia || (scrollBar.getValue() != 0.0 && scrollBar.getValue() != 1))
                    sbTouchTimeline.playFromStart();
           } // playAnimation()
       });
   } // changeView
} // ScrollBarView

Body:
As mentioned in the comments, the first issue is known, and for now it hasn't been fixed. The problem seems to be related to the initial width of the scrollbar (20 pixels as in desktop), and then is set to 8 pixels (as in touch enabled devices), and moved to its final position with this visible shift of 12 pixels to the right.

As for the second and third issues, if you don't want to patch and build the JDK yourself, it is possible to override the default behavior, as the ScrollBar control is part of the VirtualFlow control of a ListView, and both can be found on runtime via lookups.

Once you have the control, you can play with its visibility according to your needs. The only problem with this property is that it is already bound and constantly called from the layoutChildren method.

This is quite a hacky solution, but it works for both 2) and 3):

public class BasicView extends View {

    private final ListView<String> listView;
    private ScrollBar scrollbar;
    private StackPane thumb;

    public BasicView(String name) {
        super(name);

        listView = new ListView<>();
        // add your items

        final InvalidationListener skinListener = new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                if (listView.getSkin() != null) {
                    listView.skinProperty().removeListener(this);
                    scrollbar = (ScrollBar) listView.lookup(".scroll-bar");
                    listView.setOnScrollFinished(e -> {
                        if (thumb != null) {
                            // "hide" thumb as soon as scroll/drag ends
                            thumb.setStyle("-fx-background-color: transparent;");
                        }
                    });
                    listView.setOnScrollStarted(e -> {
                        if (thumb == null) {
                            thumb = (StackPane) scrollbar.lookup(".thumb");
                        }
                        if (thumb != null) {
                            // "show" thumb again only when scroll/drag starts
                            thumb.setStyle("-fx-background-color: #898989;");
                        }
                    });

                }
            }
        };
        listView.skinProperty().addListener(skinListener);
        setCenter(listView);
    }

}


问:
Web API Attribute Routing URI Issue
I want to route my API through this URI

```<code>localhost/api/ServiceA/1234
</code>```

where isbn=1234

currently I am retrieving json from the UrI mentioned below

```<code>localhost/1234
</code>```

where 1234 is isbn

How can I get the same json results with the following uri?

```<code>localhost/api/ServiceA/1234
</code>```

Currently I am getting null with the above URL

With the following code using attribute routing I am getting the results with

I have an API Countroller

```<code>public class ServiceAController : ApiController
{
    [Route("api/ServiceA/{isbn}")]
    public Book GetBook(string isbn)
    {
        using (AppDbContext db = new AppDbContext())
        {
            var query = from b in db.Books
                        where b.ISBN == isbn && b.Source == "Book Store 1"
                        select b;
            return query.SingleOrDefault();
        }
    }
}
</code>```

答:
Looks like you forgot to keep the [HttpGet] attribute for your method.

Ex:

```<code>[Route("api/ServiceA/{isbn}")]
[HttpGet]
public Book GetBook(string isbn){
    // ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Web API Attribute Routing URI Issue

Body:
I want to route my API through this URI

localhost/api/ServiceA/1234

where isbn=1234

currently I am retrieving json from the UrI mentioned below

localhost/1234

where 1234 is isbn

How can I get the same json results with the following uri?

localhost/api/ServiceA/1234

Currently I am getting null with the above URL

With the following code using attribute routing I am getting the results with

I have an API Countroller

public class ServiceAController : ApiController
{
    [Route("api/ServiceA/{isbn}")]
    public Book GetBook(string isbn)
    {
        using (AppDbContext db = new AppDbContext())
        {
            var query = from b in db.Books
                        where b.ISBN == isbn && b.Source == "Book Store 1"
                        select b;
            return query.SingleOrDefault();
        }
    }
}

Body:
Looks like you forgot to keep the [HttpGet] attribute for your method.

Ex:

[Route("api/ServiceA/{isbn}")]
[HttpGet]
public Book GetBook(string isbn){
    // ...
}


问:
VBA Alignment of text within a textbox
I wants to know got any way to display a text inside the textbox together with align left and right.
The textbox property just only left or right.
Example:

答:
I have been trying to align amount with 3 decimal places in the right of a text box. The string variable I use is addnreport.

I used a temporary string StrX which I RSet (Right Pad)
In atext editor, it shows up as expected but in the Text Box, the values on the extreme right seem to be centre aligned no matter what you do.

```<code>addnreport = addnreport & acc & vbTab & month & vbTab & "PL"
            RSet StrX = (Format(Round(amount, 3), "#,###,###,##0.000"))
            addnreport = addnreport & StrX & vbCrLf
</code>```

Title: VBA Alignment of text within a textbox

Body:
I have been trying to align amount with 3 decimal places in the right of a text box. The string variable I use is addnreport.

I used a temporary string StrX which I RSet (Right Pad)
In atext editor, it shows up as expected but in the Text Box, the values on the extreme right seem to be centre aligned no matter what you do.

addnreport = addnreport & acc & vbTab & month & vbTab & "PL"
            RSet StrX = (Format(Round(amount, 3), "#,###,###,##0.000"))
            addnreport = addnreport & StrX & vbCrLf


问:
Java Date oddity
Out of curiosity, why do I receive an IllegalArgumentException for the MONTH in the below test case?

```<code>public class Testing {
    public static void main(String args[]) {

      Calendar c = Calendar.getInstance(Locale.getDefault());
      c.setLenient(false);
      Date d = new Date();

      c.set(Calendar.MONTH, Calendar.FEBRUARY);
      c.set(Calendar.DAY_OF_MONTH, 30);
      c.set(Calendar.YEAR, 2010);

      d = c.getTime();  //Exception is not thrown until this line

      System.out.println(d.toString());
    }
}
</code>```

I looked at the GregorianCalendar which is the default on my system, and realize that the MONTH field would in fact be the first one to differ in the two Feb 30, vs March 2 in this case, but shouldn't this IllegalArgumentException be what causes the overflow, or was it just deemed to difficult to "discover"?

答:
Because February always has less than 30 days.  And you are setting the day on the  Calendar instance to 30.  So, when you try to create an invalid Date, Java will not let you because that would be an invalid date and you have chosen setLienient(false).

Try the following:

```<code>c.set(Calendar.DAY_OF_MONTH, 28);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
c.set(Calendar.YEAR, 2010);
</code>```

That should work.

This is ultimately caused because you are calling c.setLenient(false);.  This causes Java to be strict about the dates it allows.

See the Javadoc for the method:

public void setLenient(boolean lenient)

Title: Java Date oddity

Body:
Out of curiosity, why do I receive an IllegalArgumentException for the MONTH in the below test case?

public class Testing {
    public static void main(String args[]) {

      Calendar c = Calendar.getInstance(Locale.getDefault());
      c.setLenient(false);
      Date d = new Date();

      c.set(Calendar.MONTH, Calendar.FEBRUARY);
      c.set(Calendar.DAY_OF_MONTH, 30);
      c.set(Calendar.YEAR, 2010);

      d = c.getTime();  //Exception is not thrown until this line

      System.out.println(d.toString());
    }
}

I looked at the GregorianCalendar which is the default on my system, and realize that the MONTH field would in fact be the first one to differ in the two Feb 30, vs March 2 in this case, but shouldn't this IllegalArgumentException be what causes the overflow, or was it just deemed to difficult to "discover"?

Body:
Because February always has less than 30 days.  And you are setting the day on the  Calendar instance to 30.  So, when you try to create an invalid Date, Java will not let you because that would be an invalid date and you have chosen setLienient(false).

Try the following:

c.set(Calendar.DAY_OF_MONTH, 28);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
c.set(Calendar.YEAR, 2010);

That should work.

This is ultimately caused because you are calling c.setLenient(false);.  This causes Java to be strict about the dates it allows.

See the Javadoc for the method:

public void setLenient(boolean lenient)


问:
Select rows from two tables
I've tried a lot of the solutions to this problem in other similar questions, but I can't make it work.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, week. Again, same procedure with the week-column. The other 3 I fill out with the matches we should bet on.

I then have a query:

```<code>SELECT *
FROM game
WHERE week = '.$week;
</code>```

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

```<code>'SELECT * FROM game WHERE week = '.$week.' JOIN * FROM matches WHERE week = '.$week;
</code>```

but as you probably now, that won't work :/

But what should I do then?

答:
Your Query should be like this.
You basically link matches with game using the week. You can also link using the id of matches which is better and more unique. But try this below</p>

```<code>  select g.*,m.* FROM game g inner join matches m on g.week=m.week where g.week='.$week;
</code>```

Title: Select rows from two tables

Body:
I've tried a lot of the solutions to this problem in other similar questions, but I can't make it work.

I have a table in my database called 'game' with the columns: k1, k1r, k2, k2r, k3, k3r and week. The week-column is automatically inserted with the week of the year and the others are user-inputs from a betting game I made.

Then I have a table called 'matches' with the columns: match1, match2, match3, week. Again, same procedure with the week-column. The other 3 I fill out with the matches we should bet on.

I then have a query:

SELECT *
FROM game
WHERE week = '.$week;

$week is already set as $week = Date('W');

It outputs a table, where I write the matches in 3 columns and then echoes the users bets in the rows under the matches. But instead of me changing the php-script every time there are new matches, I would like it to take them from the table 'matches'. In that way, I also keep the old matches in the database.

So, now to my question :)

What I would like to do is something like:

'SELECT * FROM game WHERE week = '.$week.' JOIN * FROM matches WHERE week = '.$week;

but as you probably now, that won't work :/

But what should I do then?

Body:
Your Query should be like this.
You basically link matches with game using the week. You can also link using the id of matches which is better and more unique. But try this below

  select g.*,m.* FROM game g inner join matches m on g.week=m.week where g.week='.$week;


问:
access violation at 0x00840bd7: read of address 0x00000000'. Process.... (5644) "
After selecting the name of the table in my bd grid I want to have the colones that belongs to this table by double clicking but I find this error

lorque j double click Exception 'first chance' to $ 00840BD7 Exception class $ C0000005 with a message 'access violation at 0x00840bd7: read of address 0x00000000'. Process conversion.exe (5644) "
  here is the  code :

```<code>procedure TForm5.DBGrid1DblClick(Sender: TObject);

begin
    FDQuery2.SQL.Clear;
FDQuery2.SQL.Text := 'select column_name from information_schema.columns where table_schema="bases" and table_name = "'+DBGrid2.SelectedField.ToString+'"';
FDQuery2.Open;
ListBox2.Clear;
FDQuery2.GetFieldNames(ListBox2.Items);
end;
</code>```

can you help me ?

答:
If you rewrite your code like this:

```<code>var
  AField : TField;
begin
  AField := DBGrid2.SelectedField;
  Caption := AField.ToString;

  FDQuery2.Close;
  FDQuery2.SQL.Text := 'select column_name from information_schema.columns where table_schema="bases" and table_name = "'+DBGrid2.SelectedField.ToString+'"';
  FDQuery2.Open;
  ListBox2.Clear;
  FDQuery2.GetFieldNames(ListBox2.Items);
</code>```

and run it, you should be able to see immediately what your problem is.

ToString does NOT return the value in the selected field of the grid - in your case it returns TStringField, which is the type of the field. not its string value.  To get its string value from the table use DBGRid2.SelectedField.AsString.

There are a couple of other things I think are wrong with your code:

Using a DBGrid's SelectedField to access a field's value.  In general, that is ok to do, but since in your case you already know which field you need - Table_Name - what's the point of requiring the user to click it?  Also, the user may select the wrong column.

Better to use FDQuery2.FieldByName('Table_Name').AsString

I bet your DBGrid2 is connected to FDQuery2 via its datasource.  If so, basing your query on what's already displayed in DBGrid2 is asking for trouble unless you know what you are doing.  If you are still working with the code in your other q, you would do better to get the Table_Name value from FDQuery1.

In any case, in my answer to your other q, Display database structure from Delphi (rad studio), I showed you how to set up a master-detail linkage between the two tables so that the second one, the table columns one, is automatically synced with the selected table in the first one.

Body:
After selecting the name of the table in my bd grid I want to have the colones that belongs to this table by double clicking but I find this error

lorque j double click Exception 'first chance' to $ 00840BD7 Exception class $ C0000005 with a message 'access violation at 0x00840bd7: read of address 0x00000000'. Process conversion.exe (5644) "
  here is the  code :

procedure TForm5.DBGrid1DblClick(Sender: TObject);

begin
    FDQuery2.SQL.Clear;
FDQuery2.SQL.Text := 'select column_name from information_schema.columns where table_schema="bases" and table_name = "'+DBGrid2.SelectedField.ToString+'"';
FDQuery2.Open;
ListBox2.Clear;
FDQuery2.GetFieldNames(ListBox2.Items);
end;

can you help me ?

Body:
If you rewrite your code like this:

var
  AField : TField;
begin
  AField := DBGrid2.SelectedField;
  Caption := AField.ToString;

  FDQuery2.Close;
  FDQuery2.SQL.Text := 'select column_name from information_schema.columns where table_schema="bases" and table_name = "'+DBGrid2.SelectedField.ToString+'"';
  FDQuery2.Open;
  ListBox2.Clear;
  FDQuery2.GetFieldNames(ListBox2.Items);

and run it, you should be able to see immediately what your problem is.

ToString does NOT return the value in the selected field of the grid - in your case it returns TStringField, which is the type of the field. not its string value.  To get its string value from the table use DBGRid2.SelectedField.AsString.

There are a couple of other things I think are wrong with your code:

Using a DBGrid's SelectedField to access a field's value.  In general, that is ok to do, but since in your case you already know which field you need - Table_Name - what's the point of requiring the user to click it?  Also, the user may select the wrong column.

Better to use FDQuery2.FieldByName('Table_Name').AsString

I bet your DBGrid2 is connected to FDQuery2 via its datasource.  If so, basing your query on what's already displayed in DBGrid2 is asking for trouble unless you know what you are doing.  If you are still working with the code in your other q, you would do better to get the Table_Name value from FDQuery1.

In any case, in my answer to your other q, Display database structure from Delphi (rad studio), I showed you how to set up a master-detail linkage between the two tables so that the second one, the table columns one, is automatically synced with the selected table in the first one.


答:
Use contains as follows:</p>

```<code> result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper().Contains(lo_operandVal.ToString().ToUpper()));
</code>```

Title: Linq query to check substring between a list and string

Body:
I have a list of strings and a string, and I want that if the string contains any of the string which is present in the list the system returns false. I am using following lambda expression:

 result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper() == lo_operandVal.ToString().ToUpper());

Following is the dataset:

lo_operandVal = "ABC DEF GHI Post Office Box"
ro_operandVal is the list of strings with following elements:

Post Office Box

P.O. BOX

when I evaluate this expression it always returns true.

Body:
Use contains as follows:

 result = !(((string[])ro_operandVal).ToList<string>()).Any(x => x.ToString().ToUpper().Contains(lo_operandVal.ToString().ToUpper()));


问:
Run validator less often, when leaving field, rather than as user types in Vaadin 8 Binder
In Vaadin 8, the new Binder feature can have one or more validators attached to a field. These validators run immediately, as a user types in a TextField for example.

Is there a way to avoid running the validators so often, instead running only when the focus leaves the user such as when the user presses Tab to move to another field?

答:
The default behavior of the TextField when to trigger a value change event has changed in Vaadin 8. But if you set the ValueChangeMode to BLUR it will work as you know from Vaadin 7.

```<code>// BLUR gives the old Vaadin 7 behavior, LAZY is default.
textField.setValueChangeMode(ValueChangeMode.BLUR);
</code>```

From the Vaadin 8 sources:

```<code>/**
 * Fires a server-side event when the field loses focus.
 */
BLUR,

/**
 * On every user event, schedule a server-side event after a defined
 * interval, cancelling the currently-scheduled event if any. This is a good
 * choice if you want to, for instance, wait for a small break in the user's
 * typing before sending the event.
 */
LAZY
</code>```

The validation is automatically done after the value change. With the modification of the ValueChangeMode you can run the value change event and the validation less often.

Body:
The default behavior of the TextField when to trigger a value change event has changed in Vaadin 8. But if you set the ValueChangeMode to BLUR it will work as you know from Vaadin 7.

// BLUR gives the old Vaadin 7 behavior, LAZY is default.
textField.setValueChangeMode(ValueChangeMode.BLUR);

From the Vaadin 8 sources:

/**
 * Fires a server-side event when the field loses focus.
 */
BLUR,

/**
 * On every user event, schedule a server-side event after a defined
 * interval, cancelling the currently-scheduled event if any. This is a good
 * choice if you want to, for instance, wait for a small break in the user's
 * typing before sending the event.
 */
LAZY

The validation is automatically done after the value change. With the modification of the ValueChangeMode you can run the value change event and the validation less often.


问:
jQuery Ajax clicks doesn't work unless page is refreshed
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

```<code>  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});
</code>```

Is there anything I am missing or done wrong?

答:
$(document).on('click') event should called once on page load. No need to add document change on row add.

OR

You can first unbind event then bind again like

```<code> $(document).off("click", '.up_vote').on("click", '.up_vote', function () {
       alert("done");
       // Code here...
 });
</code>```

Body:
I've been messing around with some JS and ajax in my PHP project and I am facing some problems. The ajax only seems to work when the page is refreshed after clicking or just refresh to click. I'm using jquery 3.2.1.

I was first using .live() but that is deprecated now and I read that .on() is an alternative so I am using that now.

This is my JS part:

  $(".up_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'upvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $(".down_vote").on("click", function() {
    var post_id = $(this).attr('postid');
    $.ajax({
      type: "POST",
      data: {
        'post_id': post_id,
        'action': 'downvote'
      },
      url: '<?php echo $url; ?>/includes/functions.php',
      dataType: 'json',
      success: function(response) {
        if (response.ResponseCode == 200) {
          $('#postbox_' + post_id).load('<?php echo $url; ?>/index.php #postbox_' + post_id + ' >*');
        } else {
          alert(response.Message);
        }
      }
    });
  });

  $("#btnpost").click(function() {
    var post = $("#post_feed").val();
    if (post == "") {
      alert("This can't be empty.");
      return false;
    } else {
      $.ajax({
        type: "POST",
        data: {
          'post_feed': post,
          'action': 'post'
        },
        url: '<?php echo $url; ?>/includes/functions.php',
        dataType: 'json',
        success: function(response) {
          if (response.ResponseCode == 200) {
            $("#post_feed").val("");
            $('#feed_div').load('<?php echo $url; ?>/index.php #feed_div');
          } else {
            alert(response.Message);
          }
        }
      });
    }
  });
});

Is there anything I am missing or done wrong?

Body:
$(document).on('click') event should called once on page load. No need to add document change on row add.

OR

You can first unbind event then bind again like

 $(document).off("click", '.up_vote').on("click", '.up_vote', function () {
       alert("done");
       // Code here...
 });


答:
you can try the below linq -
if any value in list found in string then it will return false, and if none of them found then it will return true.

```<code>var result = ro_operandVal.All(c=>lo_operandVal.IndexOf(c) < 0);
</code>```

Update

both are object type and you know their exact type that they are List<string> and string you can type cast them.

```<code>var result = ((List<string>)ro_operandVal).All(c=>lo_operandVal.ToString().IndexOf(c) < 0);
</code>```

Body:
you can try the below linq -
if any value in list found in string then it will return false, and if none of them found then it will return true.

var result = ro_operandVal.All(c=>lo_operandVal.IndexOf(c) < 0);

Update

both are object type and you know their exact type that they are List<string> and string you can type cast them.

var result = ((List<string>)ro_operandVal).All(c=>lo_operandVal.ToString().IndexOf(c) < 0);


问:
How to store time series data in a list (or any other data structure) to get reasonable trends over a variety of horizons?
Say I want to store a forex rate trend in which, I receive two updates every second on average. But I don't want to store all updates against the timestamp over a day as the data would be huge. But I want to show every update in the last two minutes, every second update in the last 1 hour and so on with reducing frequencies over a day. Which algorithm/data structure is best for this?  </p>

答: You could use a circular buffer. But generally StackOverflow is not for questions like that.</p>