问:
Log Appium testresults to console
Appium won't log the test results (of the UI-tests, executed with adb emulator) to the debug output (Deug.WriteLine).

According to the documentation, get test logs is possible with the following line

```<code>ILogs logs = driver.Manage().Logs;
</code>```

Hower, Appium has different log types:

Browser

Client

Driver

Profiler

Server

I tried every single log type with the following code. But by executing I don't get any result and the test will (where I put the code) fail. Does anyone have a solution for this problem?

```<code>ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Browser);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Client);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Driver);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Profiler);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Server);

foreach (var log in logs)
{
    Debug.WriteLine("Time: " + log.Timestamp);
    Debug.WriteLine("Message: " + log.Message);
    Debug.WriteLine("Level: " + log.Level);
}
</code>```

答:
I just figure out.

Check this article first
relaxed Security AppiumService

Get the log type

```<code>    IReadOnlyCollection<string> logTypes = driver.Manage().Logs.AvailableLogTypes;
    foreach (string logType in logTypes)
    {
        Console.WriteLine(logType);
        //logcat
        //bugreport
        //server
    }
</code>```

Print logs

```<code>public static void PrintLogs(string logType)
{
    try
    {
        ILogs _logs = driver.Manage().Logs;
        var browserLogs = _logs.GetLog(logType);
        if (browserLogs.Count > 0)
        {
            foreach (var log in browserLogs)
            {
                //log the message in a file
                Console.WriteLine(log);
            }
        }
    }
    catch(Exception e)
    {
        //There are no log types present
        Console.WriteLine(e.ToString());
    }
</code>```

Picture : C# Console Print appium log

Title: Log Appium testresults to console

Body:
Appium won't log the test results (of the UI-tests, executed with adb emulator) to the debug output (Deug.WriteLine).

According to the documentation, get test logs is possible with the following line

ILogs logs = driver.Manage().Logs;

Hower, Appium has different log types:

Browser

Client

Driver

Profiler

Server

I tried every single log type with the following code. But by executing I don't get any result and the test will (where I put the code) fail. Does anyone have a solution for this problem?

ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Browser);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Client);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Driver);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Profiler);
//  ReadOnlyCollection<LogEntry> logs = _driver.Manage().Logs.GetLog(LogType.Server);

foreach (var log in logs)
{
    Debug.WriteLine("Time: " + log.Timestamp);
    Debug.WriteLine("Message: " + log.Message);
    Debug.WriteLine("Level: " + log.Level);
}

Body:
I just figure out.

Check this article first
relaxed Security AppiumService

Get the log type

    IReadOnlyCollection<string> logTypes = driver.Manage().Logs.AvailableLogTypes;
    foreach (string logType in logTypes)
    {
        Console.WriteLine(logType);
        //logcat
        //bugreport
        //server
    }

Print logs

public static void PrintLogs(string logType)
{
    try
    {
        ILogs _logs = driver.Manage().Logs;
        var browserLogs = _logs.GetLog(logType);
        if (browserLogs.Count > 0)
        {
            foreach (var log in browserLogs)
            {
                //log the message in a file
                Console.WriteLine(log);
            }
        }
    }
    catch(Exception e)
    {
        //There are no log types present
        Console.WriteLine(e.ToString());
    }

Picture : C# Console Print appium log


来源: stackexchange

问:
C/C++: goto into the for loop
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}
</code>```

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

答:
First, I need to say that you must reconsider doing this some other way. I've rarely seen someone using goto this days if not for error management.

But if you really want to stick with it, there are a few things you'll need to keep in mind:

Jumping from outside the loop to the middle won't make your code loop. (check the comments below for more info)

Be careful and don't use variables that are set before the label, for instance, referring to *data_to_request. This includes iwhich is set on the for statement and is not initialized when you jump to the label.

Personally, I think in this case I would rather duplicate the code for ...process data... then use goto. And if you pay close attention, you'll notice the return statement inside your for loop, meaning that the code of the label will never get executed unless there's a goto in the code to jump to it.

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    int i = 0;
    if( not_a_first_call )
    {
        ...process data...
        *data_to_request = i;
        return;
    }

    for (i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C/C++: goto into the for loop

Body:
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

Body:
First, I need to say that you must reconsider doing this some other way. I've rarely seen someone using goto this days if not for error management.

But if you really want to stick with it, there are a few things you'll need to keep in mind:

Jumping from outside the loop to the middle won't make your code loop. (check the comments below for more info)

Be careful and don't use variables that are set before the label, for instance, referring to *data_to_request. This includes iwhich is set on the for statement and is not initialized when you jump to the label.

Personally, I think in this case I would rather duplicate the code for ...process data... then use goto. And if you pay close attention, you'll notice the return statement inside your for loop, meaning that the code of the label will never get executed unless there's a goto in the code to jump to it.

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    int i = 0;
    if( not_a_first_call )
    {
        ...process data...
        *data_to_request = i;
        return;
    }

    for (i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
    }
}


问:
protobuf-net converts List<T> to List_T class when using .ToProto()
I have a requirement to take a library of C# classes that implement protobuf-net, and convert them into .proto files, which need to be converted using protoc into .py files. I understand that the .ToProto() function does this just fine, but I came up against an issue involving collections and generics when converting from .proto to .py files. When trying to serialize a list of DateTimes, for example I get the following error X.proto:64:13. "List_TimeSpan" is not defined. As this had not caused an issue upon serialization into a protobuf file, I wasn't aware of this situation at the time.

I am currently using proto-buf.net 2.3.2 for this project; it's the version some of my other work has been done with and I am aware that this could just be solved with a version upgrade. I'm just not sure if that is the answer with the digging I've done so far. If there's something else that I'm missing, I would truly appreciate any help that can be thrown my way.

答:
If we consider:

[ProtoContract]
public class Foo {
    [ProtoMember(12)]
    public List<DateTime> Times { get; } = new List<DateTime>();
}
```

<p>then <code>GetProto<T>()</code> in both v2.3.2 (the version mentioned in the question) and v2.4.4 (the current default version) generate:</p>

<pre class="lang-proto prettyprint-override"><code>syntax = "proto2";
import "protobuf-net/bcl.proto"; // schema for protobuf-net's handling of core .NET types

message Foo {
   repeated .bcl.DateTime Times = 12;
}
</code>```

So on the surface of it, it should already be just fine. If you're doing something more exotic (perhaps using a list in a dictionary value?), I'd be happy to help, but I'm going to need more of a clue as to what you're doing. Posting some C# that shows the thing you're seeing would be a great place to start.

Note that when protobuf-net first came around, there was no agreed transmission format for date/time-like values, so protobuf-net made something up, but it turns out to not be a convenient fit for cross-platform work; the following is a hard breaking change (it is not data compatible), but if possible, I would strongly recommend the well-known format that Google added later:

[ProtoContract]
public class Foo {
    [ProtoMember(12, DataFormat = DataFormat.WellKnown)]
    public List<DateTime> Times { get; } = new List<DateTime>();
}
```

<p>which generates:</p>

<pre class="lang-proto prettyprint-override"><code>syntax = "proto2";
import "google/protobuf/timestamp.proto";

message Foo {
   repeated .google.protobuf.Timestamp Times = 12;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If we consider:

[ProtoContract]
public class Foo {
    [ProtoMember(12)]
    public List<DateTime> Times { get; } = new List<DateTime>();
}

then GetProto<T>() in both v2.3.2 (the version mentioned in the question) and v2.4.4 (the current default version) generate:

syntax = "proto2";
import "protobuf-net/bcl.proto"; // schema for protobuf-net's handling of core .NET types

message Foo {
   repeated .bcl.DateTime Times = 12;
}

So on the surface of it, it should already be just fine. If you're doing something more exotic (perhaps using a list in a dictionary value?), I'd be happy to help, but I'm going to need more of a clue as to what you're doing. Posting some C# that shows the thing you're seeing would be a great place to start.

Note that when protobuf-net first came around, there was no agreed transmission format for date/time-like values, so protobuf-net made something up, but it turns out to not be a convenient fit for cross-platform work; the following is a hard breaking change (it is not data compatible), but if possible, I would strongly recommend the well-known format that Google added later:

[ProtoContract]
public class Foo {
    [ProtoMember(12, DataFormat = DataFormat.WellKnown)]
    public List<DateTime> Times { get; } = new List<DateTime>();
}

which generates:

syntax = "proto2";
import "google/protobuf/timestamp.proto";

message Foo {
   repeated .google.protobuf.Timestamp Times = 12;
}


问:
Databinding for TextWatcher is not working Android
I am making a password creation screen, and I want to show a password strength indicator as they type.
My layout looks like this:

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="viewModel"
            type="com.example.PasswordViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:textChangedListener="@{viewModel.passwordTextWatcher}" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@{viewModel.passwordQuality}"/>

    </LinearLayout>

</layout>
</code>```

PasswordViewModel.java is like below

```<code>public class PasswordViewModel extends BaseObservable {

    private String password;

    @Bindable
    public String getPasswordQuality() {
        if (password == null || password.isEmpty()) {
            return "Enter a password";
        } else if (password.equals("password")) {
            return "Very bad";
        } else if (password.length() < 6) {
            return "Short";
        } else {
            return "Okay";
        }
    }

    public void setPassword(String password) {
        this.password = password;
        notifyPropertyChanged(BR.passwordQuality);
    }

@Bindable
public TextWatcher getPasswordTextWatcher() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Do nothing.
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setPassword(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            // Do nothing.
        }
    };
}
</code>```

And Finally

```<code>public class EditTextBindingAdapters {

    @BindingAdapter("textChangedListener")
    public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
        editText.addTextChangedWatcher(textWatcher);
    }
}
</code>```

But when I start to write onTextChanged method is not calling! can anyone help me to resolve this issue? thanks, in advance.

答:
According your description of problem, it seems you did not initialized binding in your activity. if this is the case then

First check that you have initialized the binding in your activity and set the ViewModel on it like below

```<code>ActivityMainBinding activityMainBinding = null;
PasswordViewModel passwordViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    passwordViewModel = new PasswordViewModel();
    activityMainBinding.setViewModel(passwordViewModel);

}
</code>```

Now the second problem is addTextChangedWatcher, add addTextChangedListener in place of that.

like this

```<code> public class EditTextBindingAdapters {

    @BindingAdapter("textChangedListener")
    public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
        editText.addTextChangedListener(textWatcher);
    }

}
</code>```

Body:
I am making a password creation screen, and I want to show a password strength indicator as they type.
My layout looks like this:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="viewModel"
            type="com.example.PasswordViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:textChangedListener="@{viewModel.passwordTextWatcher}" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@{viewModel.passwordQuality}"/>

    </LinearLayout>

</layout>

PasswordViewModel.java is like below

public class PasswordViewModel extends BaseObservable {

    private String password;

    @Bindable
    public String getPasswordQuality() {
        if (password == null || password.isEmpty()) {
            return "Enter a password";
        } else if (password.equals("password")) {
            return "Very bad";
        } else if (password.length() < 6) {
            return "Short";
        } else {
            return "Okay";
        }
    }

    public void setPassword(String password) {
        this.password = password;
        notifyPropertyChanged(BR.passwordQuality);
    }

@Bindable
public TextWatcher getPasswordTextWatcher() {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Do nothing.
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            setPassword(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            // Do nothing.
        }
    };
}

And Finally

public class EditTextBindingAdapters {

    @BindingAdapter("textChangedListener")
    public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
        editText.addTextChangedWatcher(textWatcher);
    }
}

But when I start to write onTextChanged method is not calling! can anyone help me to resolve this issue? thanks, in advance.

Body:
According your description of problem, it seems you did not initialized binding in your activity. if this is the case then

First check that you have initialized the binding in your activity and set the ViewModel on it like below

ActivityMainBinding activityMainBinding = null;
PasswordViewModel passwordViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    passwordViewModel = new PasswordViewModel();
    activityMainBinding.setViewModel(passwordViewModel);

}

Now the second problem is addTextChangedWatcher, add addTextChangedListener in place of that.

like this

 public class EditTextBindingAdapters {

    @BindingAdapter("textChangedListener")
    public static void bindTextWatcher(EditText editText, TextWatcher textWatcher) {
        editText.addTextChangedListener(textWatcher);
    }

}


问:
Fix IE/Edge CSS clip-path
I'm having troubles with clip-path property with IE11/Edge browsers while using clip-path CSS property.

The snippet below is what I have so far and is working good in all browsers, apart Microsoft ones.
I cannot understand how to solve this.

.banner {
  overflow: visible;
  position: relative;
  min-height: 50vh;
  background-size: cover;
  background-position: right;
  background-repeat: no-repeat;
  display: flex;
  background-image: url("https://i.picsum.photos/id/435/2000/800.jpg");
}

.banner-clickable {
  margin: 0;
  position:absolute;
  top:0;
  left:0;
  width: 100%;
  height: 100%;
  background: transparent;
  clip-path: polygon(0% 35%, 0% 75%, 100% 100%, 100% 0%);
}

.banner-clickable:hover {
  cursor:pointer;
}

.banner::after, .banner::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(#ee3b26, #ee3b26);
  cursor: auto;
}

.banner::before {
  clip-path: polygon(0% 0%, 0% 35%, calc(100% + 1px) 0%);
}

.banner:after {
  clip-path:  polygon(0% 75%, 0% calc(100% + 1px), calc(100% + 1px) calc(100% + 1px));
  background: #fff
}

.banner > * {
  z-index: 100;
}

.banner {
  z-index: -1;
  min-height: 72vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="banner">
  <div class="banner-clickable"></div>
  <div class="scrollBt">
    LINK
  </div>
</section></code>```

And a jsfiddle to help: JsFille

答:
IE 11 only supports the CSS clip-path property in SVG. It's hard to make it exactly the same in IE 11 like using clip-path in other modern browsers. I think the easiest way is to use an image in IE, the image should be the same as the outcome of applying css styles in other browsers. I use a image like this and target the css styles with no IE browsers:

@supports not (-ms-high-contrast: none) {
/* Non-IE styles here */
  #photo {
    display: none;
  }
  .banner {
    overflow: visible;
    position: relative;
    min-height: 50vh;
    background-size: cover;
    background-position: right;
    background-repeat: no-repeat;
    display: flex;
    background-image: url("https://i.picsum.photos/id/435/2000/800.jpg");
  }
  .banner-clickable {
    margin: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
    clip-path: polygon(0% 35%, 0% 75%, 100% 100%, 100% 0%);
  }
  .banner-clickable:hover {
    cursor: pointer;
  }
  .banner::after,
  .banner::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(#ee3b26, #ee3b26);
    cursor: auto;
  }
  .banner::before {
    clip-path: polygon(0% 0%, 0% 35%, calc(100% + 1px) 0%);
  }
  .banner:after {
    clip-path: polygon(0% 75%, 0% calc(100% + 1px), calc(100% + 1px) calc(100% + 1px));
    background: #fff
  }
  .banner>* {
    z-index: 100;
  }
  .banner {
    z-index: -1;
    min-height: 72vh;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="banner">
  <div class="banner-clickable"></div>
  <div class="scrollBt">
    LINK
  </div>
  <div id="photo" style="position:absolute; top:5px; left:5px; z-index:-999;">
    <img src="https://i.stack.imgur.com/NpNAO.jpg" style="width:100%" />
  </div>
</section></code>```

Title: Fix IE/Edge CSS clip-path

Body:
I'm having troubles with clip-path property with IE11/Edge browsers while using clip-path CSS property.

The snippet below is what I have so far and is working good in all browsers, apart Microsoft ones.
I cannot understand how to solve this.

.banner {
  overflow: visible;
  position: relative;
  min-height: 50vh;
  background-size: cover;
  background-position: right;
  background-repeat: no-repeat;
  display: flex;
  background-image: url("https://i.picsum.photos/id/435/2000/800.jpg");
}

.banner-clickable {
  margin: 0;
  position:absolute;
  top:0;
  left:0;
  width: 100%;
  height: 100%;
  background: transparent;
  clip-path: polygon(0% 35%, 0% 75%, 100% 100%, 100% 0%);
}

.banner-clickable:hover {
  cursor:pointer;
}

.banner::after, .banner::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(#ee3b26, #ee3b26);
  cursor: auto;
}

.banner::before {
  clip-path: polygon(0% 0%, 0% 35%, calc(100% + 1px) 0%);
}

.banner:after {
  clip-path:  polygon(0% 75%, 0% calc(100% + 1px), calc(100% + 1px) calc(100% + 1px));
  background: #fff
}

.banner > * {
  z-index: 100;
}

.banner {
  z-index: -1;
  min-height: 72vh;
}

    LINK

And a jsfiddle to help: JsFille

Body:
IE 11 only supports the CSS clip-path property in SVG. It's hard to make it exactly the same in IE 11 like using clip-path in other modern browsers. I think the easiest way is to use an image in IE, the image should be the same as the outcome of applying css styles in other browsers. I use a image like this and target the css styles with no IE browsers:

@supports not (-ms-high-contrast: none) {
/* Non-IE styles here */
  #photo {
    display: none;
  }
  .banner {
    overflow: visible;
    position: relative;
    min-height: 50vh;
    background-size: cover;
    background-position: right;
    background-repeat: no-repeat;
    display: flex;
    background-image: url("https://i.picsum.photos/id/435/2000/800.jpg");
  }
  .banner-clickable {
    margin: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: transparent;
    clip-path: polygon(0% 35%, 0% 75%, 100% 100%, 100% 0%);
  }
  .banner-clickable:hover {
    cursor: pointer;
  }
  .banner::after,
  .banner::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(#ee3b26, #ee3b26);
    cursor: auto;
  }
  .banner::before {
    clip-path: polygon(0% 0%, 0% 35%, calc(100% + 1px) 0%);
  }
  .banner:after {
    clip-path: polygon(0% 75%, 0% calc(100% + 1px), calc(100% + 1px) calc(100% + 1px));
    background: #fff
  }
  .banner>* {
    z-index: 100;
  }
  .banner {
    z-index: -1;
    min-height: 72vh;
  }
}

<section class="banner">
  <div class="banner-clickable"></div>
  <div class="scrollBt">
    <a href="#content" class="scroll">LINK</a>
  </div>
  <div id="photo" style="position:absolute; top:5px; left:5px; z-index:-999;">
    <img src="https://i.stack.imgur.com/NpNAO.jpg" style="width:100%" />
  </div>
</section>


问:
SQL behaviour when executing queries with conjunctions
If I have a SQL query that is performing an existence check against three tables:

```<code>IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')
</code>```

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?

答:
Edit: there is a bug in SQL Server apparently that kiboshes short circuiting occasionally. See comments on RedFilter's answer. If you want short circuiting, use nested IFs.

Generally SQL is declarative, not procedural, so you can never assume any expression or query will be evaluated in the order its written. Edit: except for CASE...

```<code>IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
BEGIN
    IF EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    BEGIN
        IF EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')
        BEGIN
</code>```

This would also change how locks are applied: now you'll have separate locks for each query instead of locks for all three tables for the duration of the first AND expression

Body:
If I have a SQL query that is performing an existence check against three tables:

IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?

Body:
Edit: there is a bug in SQL Server apparently that kiboshes short circuiting occasionally. See comments on RedFilter's answer. If you want short circuiting, use nested IFs.

Generally SQL is declarative, not procedural, so you can never assume any expression or query will be evaluated in the order its written. Edit: except for CASE...

IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
BEGIN
    IF EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    BEGIN
        IF EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')
        BEGIN

This would also change how locks are applied: now you'll have separate locks for each query instead of locks for all three tables for the duration of the first AND expression


问:
EventBus - Subscriber class and its super classes have no public methods with the @subscribe annotation
I'm creating an Android application using EventBus for posting asynchronous broadcasts to other classes, but I'm running into an error during execution.

MainActivity.java

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.maps.model.LatLng;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    //Globals
    public String uname = null;
    public double lat = 0;
    public double lng = 0;

    //Get GUI handles
    public Button sendButton; //
    public EditText username;
    public Button MapButton; //
    public EditText LatBox;
    public EditText LngBox;

    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //register EventBus
        EventBus.getDefault().register(this);

        super.onCreate(savedInstanceState);
        //set GUI for MainActivity
        setContentView(R.layout.activity_main);

        //get handlers
        LatBox = (EditText)findViewById(R.id.LatBox);
        LngBox = (EditText)findViewById(R.id.LngBox);

        MapButton = (Button)findViewById(R.id.locationButton);
        //Call the class which will handle finding coordinates
        MapButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent MapIntent = new Intent(getApplicationContext(), MapClass.class);
                startActivityForResult(MapIntent, 0);
            }
        });

        sendButton = (Button)findViewById(R.id.Submit);
        //Set action for Button
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Get username from user
                username  = (EditText)findViewById(R.id.UsernameText);
                uname = username.getText().toString();

                //Generate intent to start IntentService
                Intent i = new Intent(getApplicationContext(), Register.class);

                //Put the extra field of username
                i.putExtra("username", uname);
                i.putExtra("latitude", lat);
                i.putExtra("longitude", lng);
                i.putExtra("type", "meetup.be2015.gcm_meetup.MAIN_ACTIVITY");

                //Start the IntentService on a different thread
                startService(i);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LatLng currentPos){

        LatBox.setText(String.valueOf(currentPos.latitude));
        LngBox.setText(String.valueOf(currentPos.longitude));

        lat = currentPos.latitude;
        lng = currentPos.longitude;
    }
}
</code>```

MapClass.java

```<code>import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MapClass extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private GoogleMap mgoogleMap;
    private LatLng latLng;
    private GoogleApiClient client;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mgoogleMap = googleMap;
        mgoogleMap.setMyLocationEnabled(true);      //Sets location to current position
        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location MLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (MLastLocation != null) {
            latLng = new LatLng(MLastLocation.getLatitude(), MLastLocation.getLongitude());

            //Post the LatLng to MainActivity
            EventBus.getDefault().post(latLng);

            //Send sticky event to Register and MyGcmListenerService
            EventBus.getDefault().postSticky(latLng);

        } else {
            Log.d("onConnected", "Value of LatLng is NULL");
            latLng = new LatLng(0, 0);   //equator
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Notify
        Log.d("ConnectionSuspended", "Connection Suspended. Status: " +   i);
        mgoogleMap.clear();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //Notify
        Log.d("ConnectionFailed", "Connection Failed. Status: " + connectionResult.toString());
        mgoogleMap.clear();
        mGoogleApiClient.disconnect();
    }

    @Subscribe
    public void onEvent() {
        Log.d("EVENT", "EVENT");
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

    }
}
</code>```

The LogCat shows the following:

```<code>03-08 22:54:56.970 8570-8570/meetup.be2015.gcm_meetup E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{meetup.be2015.gcm_meetup/meetup.be2015.gcm_meetup.MapClass}:
org.greenrobot.eventbus.EventBusException: Subscriber class meetup.be2015.gcm_meetup.MapClass
and its super classes have no public methods with the @Subscribe annotation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2118)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2143)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class meetup.be2015.gcm_meetup.MapClass
and its super classes have no public methods with the @Subscribe annotation
at org.greenrobot.eventbus.SubscriberMethodFinder.findSubscriberMethods(SubscriberMethodFinder.java:67)
at org.greenrobot.eventbus.EventBus.register(EventBus.java:136)
at meetup.be2015.gcm_meetup.MapClass.onStart(MapClass.java:91)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
at android.app.Activity.performStart(Activity.java:5198)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2091)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2143)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Why is this happening? Am I doing something wrong?

答:
I was using Subscribe annotation from wrong package.

It should be
import org.greenrobot.eventbus.Subscribe

I was using
import com.squareup.otto.Subscribe

Body:
I'm creating an Android application using EventBus for posting asynchronous broadcasts to other classes, but I'm running into an error during execution.

MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.maps.model.LatLng;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class MainActivity extends AppCompatActivity {

    //Globals
    public String uname = null;
    public double lat = 0;
    public double lng = 0;

    //Get GUI handles
    public Button sendButton; //
    public EditText username;
    public Button MapButton; //
    public EditText LatBox;
    public EditText LngBox;

    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //register EventBus
        EventBus.getDefault().register(this);

        super.onCreate(savedInstanceState);
        //set GUI for MainActivity
        setContentView(R.layout.activity_main);

        //get handlers
        LatBox = (EditText)findViewById(R.id.LatBox);
        LngBox = (EditText)findViewById(R.id.LngBox);

        MapButton = (Button)findViewById(R.id.locationButton);
        //Call the class which will handle finding coordinates
        MapButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent MapIntent = new Intent(getApplicationContext(), MapClass.class);
                startActivityForResult(MapIntent, 0);
            }
        });

        sendButton = (Button)findViewById(R.id.Submit);
        //Set action for Button
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Get username from user
                username  = (EditText)findViewById(R.id.UsernameText);
                uname = username.getText().toString();

                //Generate intent to start IntentService
                Intent i = new Intent(getApplicationContext(), Register.class);

                //Put the extra field of username
                i.putExtra("username", uname);
                i.putExtra("latitude", lat);
                i.putExtra("longitude", lng);
                i.putExtra("type", "meetup.be2015.gcm_meetup.MAIN_ACTIVITY");

                //Start the IntentService on a different thread
                startService(i);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LatLng currentPos){

        LatBox.setText(String.valueOf(currentPos.latitude));
        LngBox.setText(String.valueOf(currentPos.longitude));

        lat = currentPos.latitude;
        lng = currentPos.longitude;
    }
}

MapClass.java

import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

public class MapClass extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private GoogleApiClient mGoogleApiClient;
    private GoogleMap mgoogleMap;
    private LatLng latLng;
    private GoogleApiClient client;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mgoogleMap = googleMap;
        mgoogleMap.setMyLocationEnabled(true);      //Sets location to current position
        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location MLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (MLastLocation != null) {
            latLng = new LatLng(MLastLocation.getLatitude(), MLastLocation.getLongitude());

            //Post the LatLng to MainActivity
            EventBus.getDefault().post(latLng);

            //Send sticky event to Register and MyGcmListenerService
            EventBus.getDefault().postSticky(latLng);

        } else {
            Log.d("onConnected", "Value of LatLng is NULL");
            latLng = new LatLng(0, 0);   //equator
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Notify
        Log.d("ConnectionSuspended", "Connection Suspended. Status: " +   i);
        mgoogleMap.clear();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //Notify
        Log.d("ConnectionFailed", "Connection Failed. Status: " + connectionResult.toString());
        mgoogleMap.clear();
        mGoogleApiClient.disconnect();
    }

    @Subscribe
    public void onEvent() {
        Log.d("EVENT", "EVENT");
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

    @Override
    public void onStop() {
        super.onStop();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

    }
}

The LogCat shows the following:

03-08 22:54:56.970 8570-8570/meetup.be2015.gcm_meetup E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{meetup.be2015.gcm_meetup/meetup.be2015.gcm_meetup.MapClass}:
org.greenrobot.eventbus.EventBusException: Subscriber class meetup.be2015.gcm_meetup.MapClass
and its super classes have no public methods with the @Subscribe annotation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2118)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2143)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)
Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class meetup.be2015.gcm_meetup.MapClass
and its super classes have no public methods with the @Subscribe annotation
at org.greenrobot.eventbus.SubscriberMethodFinder.findSubscriberMethods(SubscriberMethodFinder.java:67)
at org.greenrobot.eventbus.EventBus.register(EventBus.java:136)
at meetup.be2015.gcm_meetup.MapClass.onStart(MapClass.java:91)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1178)
at android.app.Activity.performStart(Activity.java:5198)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2091)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2143)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:174)
at android.app.ActivityThread.main(ActivityThread.java:4952)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
at dalvik.system.NativeStart.main(Native Method)

Why is this happening? Am I doing something wrong?


问:
How do I find the most recent joda DateTime in map?
I have a map that is updated from Firebase Realtime Database, so I don't know the map size in advance.

In the map I have a String as key, and a Joda DateTime as value.

I don't know how to iterate through the map to return the most recent Datetime.

I'll try to explain better:

```<code>//on returning results from Realtime Database
  Map<String, DateTime> myMap = new HashMap<>();

    if(dataSnapshot.exists){

       for(DataSnapshot data:dataSnapshot.getChildren()){

           String key = data.getKey();
           DateTime dateTime = // I get the data and convert it to Datetime; no problem here; I can do it.

           myMap.put(key, dateTime);

       }

   //outside the Loop
   //HERE IS WHAT I NEED HELP WITH

      for(DateTime date:myMap.values()){

         // 1 - check if date is after the next date in map
         // 2 - if it is, then keep it
         // 3 - if it is not, then remove
         // 4 - in the end, only one pair of key/value with the most recent date is left

      }

    }
</code>```

Can you guys please, help me?
Thank you so much

EDIT: Sorry, one more thing. I'm using a minimum sdk in Android that doesn't ler me use Java 8. I have to use Java 7 features.

答:
Java 7 solution

I'm using a minimum sdk in Android that doesn't ler me use Java 8. I
  have to use Java 7 features.

```<code>    Map<String, DateTime> myMap = new HashMap<>();
    myMap.put("a", new DateTime("2020-01-31T23:34:56Z"));
    myMap.put("b", new DateTime("2020-03-01T01:23:45Z"));
    myMap.put("m", new DateTime("2020-03-01T01:23:45Z"));
    myMap.put("c", new DateTime("2020-02-14T07:14:21Z"));

    if (myMap.isEmpty()) {
        System.out.println("No data");
    } else {
        Collection<DateTime> dateTimes = myMap.values();
        DateTime latest = Collections.max(dateTimes);

        System.out.println("Latest date-time is " + latest);
    }
</code>```

Output from this snippet is in my time zone (tested on jdk.1.7.0_67):

Latest date-time is 2020-03-01T02:23:45.000+01:00

We need to check first whether the map is empty because Collections.max() would throw an exception if it is.

If you need to delete all entries from the map except that or those holding the latest date:

```<code>        dateTimes.retainAll(Collections.singleton(latest));
        System.out.println(myMap);
</code>```

{b=2020-03-01T02:23:45.000+01:00, m=2020-03-01T02:23:45.000+01:00}

Is it a little bit tricky? The retainAll method deletes from a collection all elements that are not in the collection passed as argument. We pass a set of just one element, the latest date-time, so all other elements are deleted. And deleting elements from the collection we got from myMap.values() is reflected back in the map from which we got the collection, so entries where the value is not the latest date are removed. So this call accomplishes it.

Side note: consider ThreeTenABP

If you are not already using Joda-Time a lot, you may consider using java.time, the modern Java date and time API and the successor of Joda-Time, instead. It has been backported and works on low Android API levels too.

java.time links

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Oracle tutorial: Date Time explaining how to use java.time.

Body:
I have a map that is updated from Firebase Realtime Database, so I don't know the map size in advance.

In the map I have a String as key, and a Joda DateTime as value.

I don't know how to iterate through the map to return the most recent Datetime.

I'll try to explain better:

//on returning results from Realtime Database
  Map<String, DateTime> myMap = new HashMap<>();

    if(dataSnapshot.exists){

       for(DataSnapshot data:dataSnapshot.getChildren()){

           String key = data.getKey();
           DateTime dateTime = // I get the data and convert it to Datetime; no problem here; I can do it.

           myMap.put(key, dateTime);

       }

   //outside the Loop
   //HERE IS WHAT I NEED HELP WITH

      for(DateTime date:myMap.values()){

         // 1 - check if date is after the next date in map
         // 2 - if it is, then keep it
         // 3 - if it is not, then remove
         // 4 - in the end, only one pair of key/value with the most recent date is left

      }

    }

Can you guys please, help me?
Thank you so much

EDIT: Sorry, one more thing. I'm using a minimum sdk in Android that doesn't ler me use Java 8. I have to use Java 7 features.

Body:
Java 7 solution

I'm using a minimum sdk in Android that doesn't ler me use Java 8. I
  have to use Java 7 features.

    Map<String, DateTime> myMap = new HashMap<>();
    myMap.put("a", new DateTime("2020-01-31T23:34:56Z"));
    myMap.put("b", new DateTime("2020-03-01T01:23:45Z"));
    myMap.put("m", new DateTime("2020-03-01T01:23:45Z"));
    myMap.put("c", new DateTime("2020-02-14T07:14:21Z"));

    if (myMap.isEmpty()) {
        System.out.println("No data");
    } else {
        Collection<DateTime> dateTimes = myMap.values();
        DateTime latest = Collections.max(dateTimes);

        System.out.println("Latest date-time is " + latest);
    }

Output from this snippet is in my time zone (tested on jdk.1.7.0_67):

Latest date-time is 2020-03-01T02:23:45.000+01:00

We need to check first whether the map is empty because Collections.max() would throw an exception if it is.

If you need to delete all entries from the map except that or those holding the latest date:

        dateTimes.retainAll(Collections.singleton(latest));
        System.out.println(myMap);

{b=2020-03-01T02:23:45.000+01:00, m=2020-03-01T02:23:45.000+01:00}

Is it a little bit tricky? The retainAll method deletes from a collection all elements that are not in the collection passed as argument. We pass a set of just one element, the latest date-time, so all other elements are deleted. And deleting elements from the collection we got from myMap.values() is reflected back in the map from which we got the collection, so entries where the value is not the latest date are removed. So this call accomplishes it.

Side note: consider ThreeTenABP

If you are not already using Joda-Time a lot, you may consider using java.time, the modern Java date and time API and the successor of Joda-Time, instead. It has been backported and works on low Android API levels too.

java.time links

Java Specification Request (JSR) 310, where java.time was first described.

ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).

ThreeTenABP, Android edition of ThreeTen Backport

Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Oracle tutorial: Date Time explaining how to use java.time.


问:
Unable to retrieve Data Oracle Fusion BI Publisher
1.Main Code:

```<code>SELECT
  iodv.organization_id,
  iodv.organization_name,
  mil.SUBINVENTORY_CODE subinventory_name,
  mil.inventory_location_id locator_id,
  mil.segment11 || '.' || mil.segment12 || '.' || mil.segment13 locator_name
FROM
  inv_item_locations mil,
  inv_organization_definitions_v iodv
WHERE
  1 = 1
  and iodv.organization_id = mil.organization_id
  and iodv.Organization_Code = ':Organizations'
  and mil.SUBINVENTORY_CODE = ':p_Subinventories'
</code>```

Parameter p_SubInventories:

```<code>select
distinct
iil.Subinventory_code
from
inv_item_locations iil,
INV_ORG_PARAMETERS iop
where
1=1
and iil.ORGANIZATION_ID=iop.ORGANIZATION_ID
and iop.ORGANIZATION_CODE= :Organizations
</code>```

Parameter for Organizations:

```<code>select distinct organization_code from inv_org_parameters
</code>```

Unable to retrieve data with the above query in Data Model @ Oracle BI Publisher......

答:
LEFT JOIN here</p>

```<code>SELECT
  iodv.organization_id,
  iodv.organization_name,
  mil.SUBINVENTORY_CODE subinventory_name,
  mil.inventory_location_id locator_id,
  mil.segment11 || '.' || mil.segment12 || '.' || mil.segment13 locator_name
FROM
  inv_item_locations mil
LEFT JOIN
    inv_organization_definitions_v iodv
ON
    iodv.organization_id = mil.organization_id
WHERE 1 = 1
  AND iodv.Organization_Code = ':Organizations'
  AND mil.SUBINVENTORY_CODE = ':p_Subinventories'
</code>```

Body:
1.Main Code:

SELECT
  iodv.organization_id,
  iodv.organization_name,
  mil.SUBINVENTORY_CODE subinventory_name,
  mil.inventory_location_id locator_id,
  mil.segment11 || '.' || mil.segment12 || '.' || mil.segment13 locator_name
FROM
  inv_item_locations mil,
  inv_organization_definitions_v iodv
WHERE
  1 = 1
  and iodv.organization_id = mil.organization_id
  and iodv.Organization_Code = ':Organizations'
  and mil.SUBINVENTORY_CODE = ':p_Subinventories'

Parameter p_SubInventories:

select
distinct
iil.Subinventory_code
from
inv_item_locations iil,
INV_ORG_PARAMETERS iop
where
1=1
and iil.ORGANIZATION_ID=iop.ORGANIZATION_ID
and iop.ORGANIZATION_CODE= :Organizations

Parameter for Organizations:

select distinct organization_code from inv_org_parameters

Unable to retrieve data with the above query in Data Model @ Oracle BI Publisher......

Body:
LEFT JOIN here

SELECT
  iodv.organization_id,
  iodv.organization_name,
  mil.SUBINVENTORY_CODE subinventory_name,
  mil.inventory_location_id locator_id,
  mil.segment11 || '.' || mil.segment12 || '.' || mil.segment13 locator_name
FROM
  inv_item_locations mil
LEFT JOIN
    inv_organization_definitions_v iodv
ON
    iodv.organization_id = mil.organization_id
WHERE 1 = 1
  AND iodv.Organization_Code = ':Organizations'
  AND mil.SUBINVENTORY_CODE = ':p_Subinventories'


问:
i want to insert data into database directly from a table (view) but when i click add btn only the first or the last row get insterted
here in this code i have passed the hardcoded value of month if i remove january it accepts december i.e last row how to solve this issue

controller

public function storeLeave(Request $request){

      $admin= new Admin();
      $admin->employee_name=$request->input('employee_name');
      $admin->month=$request->input('month_JANUARY');
      $admin->earned_leave=$request->input('earned_leave_JANUARY');
      $admin->casual_leave=$request->input('casual_leave_JANUARY');
      $admin->sick_leave=$request->input('sick_leave_JANUARY');

      $admin->save();
  }
```

<p><strong>blade file (table)</strong></p>

```

        MONTHS
        EARNED LEAVE
        CASUAL LEAVE
        SICK LEAVE

    @foreach($months as $month)

             <input readonly value="{{$month}}-<?php echo date("Y"); ?>" name="month_{{$month}}" id="month" style="background:none; border: none;">
             <input type="text" style="background:none; border: none " name="earned_leave_{{$month}}" id="earned_leave" >
             <input type="text"  style="background:none; border: none" name="casual_leave_{{$month}}" id="casual_leave">
             <input type="text"   style="background:none; border: none" name="sick_leave_{{$month}}" id="sick_leave">

                <input type="submit" class="btn btn-success" name="submit" id="add_leave"  value="ADD">
                <input type="hidden" name="_method" value="POST">

        @endforeach

```

答:
You must use a for loop inserting in database. The code below is the example on how you handle the for loop. Happy Coding.</p>

```<code>       for($i=0; $i < count($request->employee_name); ++$i) {
          Admin::create([
            "employee_name" => $request->employee_name[$i],
         ]);
       }
</code>```

Body:
here in this code i have passed the hardcoded value of month if i remove january it accepts december i.e last row how to solve this issue

controller

public function storeLeave(Request $request){

      $admin= new Admin();
      $admin->employee_name=$request->input('employee_name');
      $admin->month=$request->input('month_JANUARY');
      $admin->earned_leave=$request->input('earned_leave_JANUARY');
      $admin->casual_leave=$request->input('casual_leave_JANUARY');
      $admin->sick_leave=$request->input('sick_leave_JANUARY');

      $admin->save();
  }

blade file (table)

        MONTHS
        EARNED LEAVE
        CASUAL LEAVE
        SICK LEAVE

    @foreach($months as $month)

             <input readonly value="{{$month}}-<?php echo date("Y"); ?>" name="month_{{$month}}" id="month" style="background:none; border: none;">
             <input type="text" style="background:none; border: none " name="earned_leave_{{$month}}" id="earned_leave" >
             <input type="text"  style="background:none; border: none" name="casual_leave_{{$month}}" id="casual_leave">
             <input type="text"   style="background:none; border: none" name="sick_leave_{{$month}}" id="sick_leave">

                <input type="submit" class="btn btn-success" name="submit" id="add_leave"  value="ADD">
                <input type="hidden" name="_method" value="POST">

        @endforeach

Body:
You must use a for loop inserting in database. The code below is the example on how you handle the for loop. Happy Coding.

       for($i=0; $i < count($request->employee_name); ++$i) {
          Admin::create([
            "employee_name" => $request->employee_name[$i],
         ]);
       }


问:
Visual Studio Code - Shortcut - Collapse all files in explorer
Can you anyone provide the shortcut for collapse all files in visual studio code explorer?</p>

答: You can collapse all folders using cmd/ctrl left-arrow.


问:
Custom Templates/Forms for Django Comments
How would I make my own custom templates/forms for the built in Django Comments Framework?</p>

答:
If you just want to override (specific) templates put them in templates/comments (a technique not only valid for contrib.comments but for all reusable apps including Django's admin.).

If you want to edit the builtin forms you have to extend contrib.comments as mentioned and explained in the docs.


问:
React API call outside useEffect
I was curious to know if making an API request outside of the lifecycle/useEffect is a valid way to make the call?

https://stackblitz.com/edit/react-useeffect-button has two functional components, the parent component makes an API call and passes the data to the child component, initially specified the limit of data to be fetched from the endpoint as 2 and the parent component has a LoadMore function that is passed as a prop along with the data to the child component.

Using the react-slick slider to display the images in the child component and the Load button onClick will call the function LoadMore inside the parent component and then it makes an API call and appends the new data from API to the old Data. The load button will append one Image to the existing images.

is this a good way to make API requests or should it be done only in the lifecycle methods?

答:
This depends on your needs.

if you think whenever your params change,API call will be triggered.
   in this case, you should set the API call inside the useEffect.

If you want your API call triggered on page load(ComponentDidMount). In this case, you should set API call inside the useEffect

Otherwise no need to set api call inside useEffect.

In your case no need to set API call inside useEffect. because you hit the API call when the user clicks the button. So no need to use useEffect.

Title: React API call outside useEffect


问:
In EF Core, how can I perform a group by and select a list of comma separated values?
In this little ASP.Net Core application, I am attempting to group students by their enrollment date and return the students' names in a comma separated string, as opposed to another kind of aggregation.

When using SQL, I've used the stuff function in the past, and I haven't been able to perform the equivalent operation as a subquery in LINQ.

Core won't allow me to perform client-side GroupBys, which I tried at first.

Client side GroupBy is not supported.

I've tried the following code and received an InvalidOperationException:

```<code>IQueryable<EnrollmentDateGroup> data =
        _context.Students
        .GroupBy(s => s.EnrollmentDate)
        .Select(s => new EnrollmentDateGroup()
        {
          EnrollmentDate = s.Key,
          StudentCount = s.Count(),
          //BELOW IS NOT WORKING
          StudentNamesCSV = string.Join(",", s.Select(x => x.FirstMidName + " " + x.LastName))
        });
</code>```

Another attempt and error message, moving away from using the already grouped data:

SqlException: Column 'Student.EnrollmentDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

```<code>//ALSO NOT WORKING
...
StudentNamesCSV = string.Join(",", _context.Students
  .Where(x => x.EnrollmentDate == s.Key)
  .Select(x => x.FirstMidName + " " + x.LastName))
...
</code>```

Any ideas are welcome! Thank you.

答:
Try to use below linq code: </p>

```<code>var result = ((from uu in _context.Students.AsEnumerable()
                       select new
                       {
                           EnrollmentDate = uu.EnrollmentDate,
                           FullName = uu.FirstMidName + " " + uu.LastName
                       }).GroupBy(cc => cc.EnrollmentDate).
                       Select(s => new EnrollmentDateGroup()
                       {
                           EnrollmentDate = s.Key,
                           StudentCount = s.Count(),
                           StudentNamesCSV = string.Join(",", s.Select(ee => ee.FullName).ToList())
                       })
                       ).ToList();
</code>```

Body:
In this little ASP.Net Core application, I am attempting to group students by their enrollment date and return the students' names in a comma separated string, as opposed to another kind of aggregation.

When using SQL, I've used the stuff function in the past, and I haven't been able to perform the equivalent operation as a subquery in LINQ.

Core won't allow me to perform client-side GroupBys, which I tried at first.

Client side GroupBy is not supported.

I've tried the following code and received an InvalidOperationException:

IQueryable<EnrollmentDateGroup> data =
        _context.Students
        .GroupBy(s => s.EnrollmentDate)
        .Select(s => new EnrollmentDateGroup()
        {
          EnrollmentDate = s.Key,
          StudentCount = s.Count(),
          //BELOW IS NOT WORKING
          StudentNamesCSV = string.Join(",", s.Select(x => x.FirstMidName + " " + x.LastName))
        });

Another attempt and error message, moving away from using the already grouped data:

SqlException: Column 'Student.EnrollmentDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

//ALSO NOT WORKING
...
StudentNamesCSV = string.Join(",", _context.Students
  .Where(x => x.EnrollmentDate == s.Key)
  .Select(x => x.FirstMidName + " " + x.LastName))
...

Any ideas are welcome! Thank you.

Body:
Try to use below linq code:

var result = ((from uu in _context.Students.AsEnumerable()
                       select new
                       {
                           EnrollmentDate = uu.EnrollmentDate,
                           FullName = uu.FirstMidName + " " + uu.LastName
                       }).GroupBy(cc => cc.EnrollmentDate).
                       Select(s => new EnrollmentDateGroup()
                       {
                           EnrollmentDate = s.Key,
                           StudentCount = s.Count(),
                           StudentNamesCSV = string.Join(",", s.Select(ee => ee.FullName).ToList())
                       })
                       ).ToList();


问:
How to extract rows from a list of lists?
I have a list of lists and I'm trying to extract rows from list and plot them over a common x-variable. So I'm trying to extract each row at a time using a loop,

```<code>for i in range(10):
    tlist = list(zip(*v_avg_store))
    tlist[0]
    print(tlist)
    x = np.array(steps_store)
    y = np.array(tlist)
    plt.plot(x,y)

v_avg_store = [100,23,23,45,12,122], [2,1232,123,43,545,645], [234,23,43,556,33,45]

</code>```

I want to extract each set of data and plot,

```<code>ex: 100,23,23,45,12,122 (y-axis) vs index (x-axis)
</code>```

for each set on the same plot.

Which returns me the error,

x = np.array(steps_store)
   y = np.array(tlist)
   plt.plot(x,y)
   plt.xlabel("steps")

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
           if x.shape[0] != y.shape[0]:
               raise ValueError("x and y must have same first dimension, but "have shapes {} and {}".format(x.shape, y.shape))
            if x.ndim > 2 or y.ndim > 2:
                 raise ValueError("x and y can be no greater than 2-D, but have "

ValueError: x and y must have same first dimension, but have shapes (99990,) and (50000, 10)

How should I address this issue? Is there a way to extract row by row form the list of list and plot them at the same time all on one plot?

答:
What's the value of steps_store? Also I'm assuming tlistis your 2 dimensional list of lists.

A 2D list example being:

x = [[1,2,3] , [4,5,6] , [7,8,9] ,[10 , 11 ,12]] # list of lists

The rows are considered the lists inside the list. So x[0] would be the row [1 2,3] , the column's correspond to the value inside the list of the row. So x[0][0] is row 0, column 0 and that corresponds to 1.

You already extracted a row (assuming tlist is a list of lists) when you called tlist[0]. However you did not assign a variable to the extracted list but instead passed the entire tlist list it to value y.

Your error means that x = np.array(steps_store) and y = np.array(tlist) aren't the same dimension (one might be a 1D list, the other might be a 2D list), without knowing what exactly the values of tlist and steps_store is.

Make sure your lists dimensions agree then extract the row with:

rowList = tlist[0]

and pass it into a numpy array:

x = np.array(rowList)

Body:
I have a list of lists and I'm trying to extract rows from list and plot them over a common x-variable. So I'm trying to extract each row at a time using a loop,

for i in range(10):
    tlist = list(zip(*v_avg_store))
    tlist[0]
    print(tlist)
    x = np.array(steps_store)
    y = np.array(tlist)
    plt.plot(x,y)

v_avg_store = [100,23,23,45,12,122], [2,1232,123,43,545,645], [234,23,43,556,33,45]

I want to extract each set of data and plot,

ex: 100,23,23,45,12,122 (y-axis) vs index (x-axis)

for each set on the same plot.

Which returns me the error,

x = np.array(steps_store)
   y = np.array(tlist)
   plt.plot(x,y)
   plt.xlabel("steps")

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
           if x.shape[0] != y.shape[0]:
               raise ValueError("x and y must have same first dimension, but "have shapes {} and {}".format(x.shape, y.shape))
            if x.ndim > 2 or y.ndim > 2:
                 raise ValueError("x and y can be no greater than 2-D, but have "

ValueError: x and y must have same first dimension, but have shapes (99990,) and (50000, 10)

How should I address this issue? Is there a way to extract row by row form the list of list and plot them at the same time all on one plot?


问:
SwiftUI: How to align view to HStack's subview?
I want to align the circle to the TileView "1"'s center  at top left. Is there any other like centre constraint of UIView?

```<code>struct BoardView: View {
    var body: some View {
        ZStack {
            VStack {
                HStack {
                    TileView(number: 1)
                    TileView(number: 2)
                }
                HStack {
                    TileView(number: 3)
                    TileView(number: 4)
                }
            }
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(Color.red.opacity(0.8))

        }
    }
}
</code>```

答:
Using GeometryReader and preference

GeometryReader - let us to get geometryProxy of a view ( according to the parent view / space provide by parent )

Note:- child view stays at their own (parent cant force them position or size)

.preference(key:,value:) - this modifier let us get some values( geometryProxy ) out of the view. so that we can access child's geometry proxy from parent as well.

comment below for any question about these topics.

here is the code,
(plus point - you can animate your circle's position easily.(by adding .animation() modifier. Ex- if you want your circle move when user touch on a title)

complete code

```<code>import SwiftUI

struct ContentView: View {

    @State var centerCoordinateOfRectangele: MyPreferenceData = MyPreferenceData(x: 0, y: 0)
    var body: some View {

        ZStack {
            VStack {
                HStack {
                    GeometryReader { (geometry)  in
                        TileView(number: 1)
                            .preference(key: MyPreferenceKey.self, value: MyPreferenceData(x: geometry.frame(in: .named("spaceIWantToMoveMyView")).midX, y:  geometry.frame(in: .named("spaceIWantToMoveMyView")).midY))

                    }
                    TileView(number: 2)
                }.onPreferenceChange(MyPreferenceKey.self) { (value) in
                        self.centerCoordinateOfRectangele = value
                }
                HStack {
                    TileView(number: 3)
                    TileView(number: 4)
                }
            }
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(Color.red.opacity(0.8))
                .position(x: centerCoordinateOfRectangele.x, y: centerCoordinateOfRectangele.y)

        }
        .coordinateSpace(name: "spaceIWantToMoveMyView") //to get values relative to this layout
                                                        // watch where i have use this name

    }
}

struct TileView: View{
    let number: Int

    var body: some View{
        GeometryReader { (geometry) in
            RoundedRectangle(cornerRadius: 30)
        }
    }
}

struct MyPreferenceData:Equatable {
    let x: CGFloat
    let y: CGFloat
}

struct MyPreferenceKey: PreferenceKey {

    typealias Value = MyPreferenceData

    static var defaultValue: MyPreferenceData = MyPreferenceData(x: 0, y: 0)

    static func reduce(value: inout MyPreferenceData, nextValue: () -> MyPreferenceData) {
        value = nextValue()
    }
}
</code>```

Code explanation ->

data model which I want to grab from the child view

```<code>struct MyPreferenceData:Equatable {
    let x: CGFloat
    let y: CGFloat
}
</code>```

Key

```<code>struct MyPreferenceKey: PreferenceKey {

    typealias Value = MyPreferenceData

    static var defaultValue: MyPreferenceData = MyPreferenceData(x: 0, y: 0)

    static func reduce(value: inout MyPreferenceData, nextValue: () -> MyPreferenceData) {
        value = nextValue()
    }
}
</code>```

defaultValue - SwiftUI use this, when there are no explicit value set
reduce() - getCalled when SwiftUI want to give values (we can use .preference() modifier on many views with the same key)

we add the .preference() modifier which we want to get values

Body:
I want to align the circle to the TileView "1"'s center  at top left. Is there any other like centre constraint of UIView?

struct BoardView: View {
    var body: some View {
        ZStack {
            VStack {
                HStack {
                    TileView(number: 1)
                    TileView(number: 2)
                }
                HStack {
                    TileView(number: 3)
                    TileView(number: 4)
                }
            }
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(Color.red.opacity(0.8))

        }
    }
}

Body:
Using GeometryReader and preference

GeometryReader - let us to get geometryProxy of a view ( according to the parent view / space provide by parent )

Note:- child view stays at their own (parent cant force them position or size)

.preference(key:,value:) - this modifier let us get some values( geometryProxy ) out of the view. so that we can access child's geometry proxy from parent as well.

comment below for any question about these topics.

here is the code,
(plus point - you can animate your circle's position easily.(by adding .animation() modifier. Ex- if you want your circle move when user touch on a title)

complete code

import SwiftUI

struct ContentView: View {

    @State var centerCoordinateOfRectangele: MyPreferenceData = MyPreferenceData(x: 0, y: 0)
    var body: some View {

        ZStack {
            VStack {
                HStack {
                    GeometryReader { (geometry)  in
                        TileView(number: 1)
                            .preference(key: MyPreferenceKey.self, value: MyPreferenceData(x: geometry.frame(in: .named("spaceIWantToMoveMyView")).midX, y:  geometry.frame(in: .named("spaceIWantToMoveMyView")).midY))

                    }
                    TileView(number: 2)
                }.onPreferenceChange(MyPreferenceKey.self) { (value) in
                        self.centerCoordinateOfRectangele = value
                }
                HStack {
                    TileView(number: 3)
                    TileView(number: 4)
                }
            }
            Circle()
                .frame(width: 30, height: 30)
                .foregroundColor(Color.red.opacity(0.8))
                .position(x: centerCoordinateOfRectangele.x, y: centerCoordinateOfRectangele.y)

        }
        .coordinateSpace(name: "spaceIWantToMoveMyView") //to get values relative to this layout
                                                        // watch where i have use this name

    }
}

struct TileView: View{
    let number: Int

    var body: some View{
        GeometryReader { (geometry) in
            RoundedRectangle(cornerRadius: 30)
        }
    }
}

struct MyPreferenceData:Equatable {
    let x: CGFloat
    let y: CGFloat
}

struct MyPreferenceKey: PreferenceKey {

    typealias Value = MyPreferenceData

    static var defaultValue: MyPreferenceData = MyPreferenceData(x: 0, y: 0)

    static func reduce(value: inout MyPreferenceData, nextValue: () -> MyPreferenceData) {
        value = nextValue()
    }
}

Code explanation ->

data model which I want to grab from the child view

struct MyPreferenceData:Equatable {
    let x: CGFloat
    let y: CGFloat
}

Key

struct MyPreferenceKey: PreferenceKey {

    typealias Value = MyPreferenceData

    static var defaultValue: MyPreferenceData = MyPreferenceData(x: 0, y: 0)

    static func reduce(value: inout MyPreferenceData, nextValue: () -> MyPreferenceData) {
        value = nextValue()
    }
}

defaultValue - SwiftUI use this, when there are no explicit value set
reduce() - getCalled when SwiftUI want to give values (we can use .preference() modifier on many views with the same key)

we add the .preference() modifier which we want to get values


答:
If you are making an API call to get data from initial render then using a lifecycle hook is a good approach. In your scenario, you want to make an API request when hitting a button. In that case it can be a simple function without any lifecycle hook method.

The only key part here is that you are maintaining the state and rendering the view from the state.

Title: React API call outside useEffect

Body:
I was curious to know if making an API request outside of the lifecycle/useEffect is a valid way to make the call?

https://stackblitz.com/edit/react-useeffect-button has two functional components, the parent component makes an API call and passes the data to the child component, initially specified the limit of data to be fetched from the endpoint as 2 and the parent component has a LoadMore function that is passed as a prop along with the data to the child component.

Using the react-slick slider to display the images in the child component and the Load button onClick will call the function LoadMore inside the parent component and then it makes an API call and appends the new data from API to the old Data. The load button will append one Image to the existing images.

is this a good way to make API requests or should it be done only in the lifecycle methods?


问:
Getting list of Facebook friends with latest API
I'm using the most recent version of the Facebook SDK (which lets to connect to something called the 'graph API' though I'm not sure). I've adapted Facebook's example code to let me connect to Facebook and that works... but I can't get a list of my friends.

```<code>$friends = $facebook->api('friends.get');
</code>```

This produces the error message: "Fatal error: Uncaught OAuthException: (#803) Some of the aliases you requested do not exist: friends.get thrown in /mycode/facebook.php on line 543"

No clue why that is or what that means. Can someone tell me the right syntax (for the latest Facebook API) to get a list of friends? (I tried "$friends = $facebook->api->friends_get();" and get a different error, "Fatal error: Call to a member function friends_get() on a non-object in /mycode/example.php on line 129".)

I can confirm that BEFORE this point in my code, things are fine: I'm connected to Facebook with a valid session and I can get my info and dump it to the screen just... i.e. this code executes perfectly before the failed friends.get call:

```<code>$session = $facebook->getSession();
if ($session) {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
}
print_r($me);
</code>```

答:
header('Content-type: text/html; charset=utf-8');

input in your page.

ContentLicense: CC BY-SA 2.5

Body:
I'm using the most recent version of the Facebook SDK (which lets to connect to something called the 'graph API' though I'm not sure). I've adapted Facebook's example code to let me connect to Facebook and that works... but I can't get a list of my friends.

$friends = $facebook->api('friends.get');

This produces the error message: "Fatal error: Uncaught OAuthException: (#803) Some of the aliases you requested do not exist: friends.get thrown in /mycode/facebook.php on line 543"

No clue why that is or what that means. Can someone tell me the right syntax (for the latest Facebook API) to get a list of friends? (I tried "$friends = $facebook->api->friends_get();" and get a different error, "Fatal error: Call to a member function friends_get() on a non-object in /mycode/example.php on line 129".)

I can confirm that BEFORE this point in my code, things are fine: I'm connected to Facebook with a valid session and I can get my info and dump it to the screen just... i.e. this code executes perfectly before the failed friends.get call:

$session = $facebook->getSession();
if ($session) {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
}
print_r($me);


问:
Error "void is an invalid type for the variable passwordMethod1"

Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

```<code>public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method
</code>```

}//end of the class

答:
You are missing ( String password) Correct your method parameter

From

```<code>public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      }
</code>```

To

```<code>public  void  passwordMethod1( String password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      }
</code>```

Lastly add the passwordMethod1 method outside from Main method.

Hope this will help you.

Body:
Discription: This program check password between 7 to 16

characters which contain only characters, numeric digits and underscore

and first character*/

import java.util.*;

public class PasswordValidationOne {
 /**my hints on how to solve this problem
 * the length of the string must not less 7 and must not more than 16 character
 **/
public static void main (String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a password");
      String password = scan.nextLine();

      public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      } //end of method passwordMethod1()

}// end of main method

}//end of the class

Body:
You are missing ( String password) Correct your method parameter

From

public  void  passwordMethod1( password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      }

To

public  void  passwordMethod1( String password) {
            int lengthPassword = password.length(); // getting the length of the string password
            boolean containsDigit = password.matches("*.\\d*.");
            boolean containsUnderscore = password.contains("_");
            char firstCharacter = password.charAt(0);
            if((lengthPassword >= 7&& lengthPassword<=16)&& (containsDigit == true) && (containsUnderscore == true)&& (firstCharacter >= 'A' && firstCharacter <= 'z') )
                System.out.println("Password Accepted! You can proceed");
            else
                System.out.println("Password not accepted! Retry");
      }

Lastly add the passwordMethod1 method outside from Main method.

Hope this will help you.


问:
loop get vs mget, Is there any performance difference in redis lua?
Given a single instance redis which supports lua scripts. Is there any performance difference between calling 'mget' once and calling 'get' multiple times to retrieve the value of multiple keys?</p>

答:
Time-complexity-wise, both result in the same: O(N) = N*O(1).

But there is overhead associated with processing each command and parsing the result back to Lua. So MGET will give you better performance.

You can measure this. The following scripts receive a list of keys, one calls GET multiple times, the other one calls MGET.

Calling GET multiple times:

```<code>local t0 = redis.call('TIME')
local res = {}
for i = 1,table.getn(KEYS),1 do
    res[i] = redis.call('GET', KEYS[i])
end
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res
</code>```

Calling MGET once:

```<code>local t0 = redis.call('TIME')
local res = redis.call('MGET', unpack(KEYS))
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res
</code>```

Calling GET multiple times took 51 microseconds, vs MGET once 20 microseconds:

```<code>> EVAL "local t0 = redis.call('TIME') \n local res = {} \n for i = 1,table.getn(KEYS),1 do  \n     res[i] = redis.call('GET', KEYS[i]) \n end \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
 1) "value:1"
 2) "value:2"
 3) "value:3"
 4) "value:4"
 5) "value:5"
 6) "value:6"
 7) "value:7"
 8) "value:8"
 9) "value:9"
10) "value:10"
11) "Time taken: 51 microseconds"
12) "T0: 1581664542637472"
13) "T1: 1581664542637523"
> EVAL "local t0 = redis.call('TIME') \n local res = redis.call('MGET', unpack(KEYS)) \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
 1) "value:1"
 2) "value:2"
 3) "value:3"
 4) "value:4"
 5) "value:5"
 6) "value:6"
 7) "value:7"
 8) "value:8"
 9) "value:9"
10) "value:10"
11) "Time taken: 20 microseconds"
12) "T0: 1581664667232092"
13) "T1: 1581664667232112"
</code>```

Body:
Time-complexity-wise, both result in the same: O(N) = N*O(1).

But there is overhead associated with processing each command and parsing the result back to Lua. So MGET will give you better performance.

You can measure this. The following scripts receive a list of keys, one calls GET multiple times, the other one calls MGET.

Calling GET multiple times:

local t0 = redis.call('TIME')
local res = {}
for i = 1,table.getn(KEYS),1 do
    res[i] = redis.call('GET', KEYS[i])
end
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res

Calling MGET once:

local t0 = redis.call('TIME')
local res = redis.call('MGET', unpack(KEYS))
local t1 = redis.call('TIME')
local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2]
table.insert(res,'Time taken: '..micros..' microseconds')
table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2]))
table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2]))
return res

Calling GET multiple times took 51 microseconds, vs MGET once 20 microseconds:

> EVAL "local t0 = redis.call('TIME') \n local res = {} \n for i = 1,table.getn(KEYS),1 do  \n     res[i] = redis.call('GET', KEYS[i]) \n end \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
 1) "value:1"
 2) "value:2"
 3) "value:3"
 4) "value:4"
 5) "value:5"
 6) "value:6"
 7) "value:7"
 8) "value:8"
 9) "value:9"
10) "value:10"
11) "Time taken: 51 microseconds"
12) "T0: 1581664542637472"
13) "T1: 1581664542637523"
> EVAL "local t0 = redis.call('TIME') \n local res = redis.call('MGET', unpack(KEYS)) \n local t1 = redis.call('TIME') \n local micros = (t1[1]-t0[1])*1000000 + t1[2]-t0[2] \n table.insert(res,'Time taken: '..micros..' microseconds') \n table.insert(res,'T0: '..t0[1]..string.format('%06d', t0[2])) \n table.insert(res,'T1: '..t1[1]..string.format('%06d', t1[2])) \n return res" 10 key:1 key:2 key:3 key:4 key:5 key:6 key:7 key:8 key:9 key:10
 1) "value:1"
 2) "value:2"
 3) "value:3"
 4) "value:4"
 5) "value:5"
 6) "value:6"
 7) "value:7"
 8) "value:8"
 9) "value:9"
10) "value:10"
11) "Time taken: 20 microseconds"
12) "T0: 1581664667232092"
13) "T1: 1581664667232112"


问:
How to make log4j record to a file and print to console
I can make the log to go the console but I cant seem to make it go to a log file. Here is my properties file.

```<code>log4j.rootLogger=DEBUG, LOG , stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d{d/MM/yy HH:mm:ss}:%m%n
# log4j.appender.LOG.Threshold=INFO

log4j.appender.LOG=org.apache.log4j.RollingFileAppender
log4j.appender.LOG.File=C:\dev\harry\data\logs\core.log
log4j.appender.LOG.layout=org.apache.log4j.PatternLayout
log4j.appender.LOG.Append=true
log4j.appender.LOG.layout.ConversionPattern=%5p %d{d/MM/yy HH:mm:ss}:%m%n
# log4j.appender.LOG.Threshold=INFO
</code>```

答: The problem is that your single \ should be \\. This is true in most properties files.</p>

Body:
I can make the log to go the console but I cant seem to make it go to a log file. Here is my properties file.

log4j.rootLogger=DEBUG, LOG , stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d{d/MM/yy HH:mm:ss}:%m%n
# log4j.appender.LOG.Threshold=INFO

log4j.appender.LOG=org.apache.log4j.RollingFileAppender
log4j.appender.LOG.File=C:\dev\harry\data\logs\core.log
log4j.appender.LOG.layout=org.apache.log4j.PatternLayout
log4j.appender.LOG.Append=true
log4j.appender.LOG.layout.ConversionPattern=%5p %d{d/MM/yy HH:mm:ss}:%m%n
# log4j.appender.LOG.Threshold=INFO


答:
is this a good way to make API requests outside useEffect/lifecycle.?

It depends on your requirements.

should it be done only in the lifecycle methods?

It depends on your requirements.

There's nothing wrong making API request outside useEffect. But it should be done in some other function or it will cause the request to go on every re-render.
And if the response if being saved in a state variable.

Then it will go into the infinite loop.

When do we make the request in useEffect and when by some other function?

Requests that fetch data or send some info at the time of initialization of the component is supposed to be made in componentDidMount/useEffect

And requests that are supposed to be sent on some action (like in your case, onClick) so they are hit according to that event.

There's neither good or bad, it's all about your requirements.

Title: React API call outside useEffect