问:
Flutter.dev and the problem with macOS Catalina (Gatekeeper)
since I upgraded my MacBook to macOS Catalina. I'm getting permanent the message ("ideviceinfo" could not be open, because the developer is not verified) despite I disabled the "spctl". can somebody help please?
I downloaded the flutter version flutter_macos_v1.9.1+hotfix.4-stable.zip AND i use the Andriod Studio 3.5.1.</p>

```<code>[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.15 19A583, locale de-DE)
    • Flutter version 1.9.1+hotfix.4 at /Users/yousefmosa/0/prg/flutter
    • Framework revision cc949a8e8b (2 weeks ago), 2019-09-27 15:04:59 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/yousefmosa/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses

[!] Xcode - develop for iOS and macOS (Xcode 11.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.0, Build version 11A420a
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install:
        sudo gem install cocoapods
        pod setup

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 40.1.2
    • Dart plugin version 191.8423
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] IntelliJ IDEA Community Edition (version 2019.1.3)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 37.0.3
    • Dart plugin version 191.7830

[✓] VS Code (version 1.37.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.3.0

[✓] Connected device (1 available)
    • iPhone 11 Pro Max • XXX-6B2F-XXX-9B01-XXXXXX • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-0 (simulator)

! Doctor found issues in 2 categories.
</code>```

答:
This is because of recent changes in macOS Catalina.

```<code>sudo spctl --add "Path_to_flutter/bin/cache/artifacts/libimobiledevice/ideviceinfo"
</code>```

You might need to reboot the system in order to apply the changes.

You can run a GateKeeper script to fix the issue.

I have published an article with more information how to fix this.

Body:
since I upgraded my MacBook to macOS Catalina. I'm getting permanent the message ("ideviceinfo" could not be open, because the developer is not verified) despite I disabled the "spctl". can somebody help please?
I downloaded the flutter version flutter_macos_v1.9.1+hotfix.4-stable.zip AND i use the Andriod Studio 3.5.1.

[✓] Flutter (Channel stable, v1.9.1+hotfix.4, on Mac OS X 10.15 19A583, locale de-DE)
    • Flutter version 1.9.1+hotfix.4 at /Users/yousefmosa/0/prg/flutter
    • Framework revision cc949a8e8b (2 weeks ago), 2019-09-27 15:04:59 -0700
    • Engine revision b863200c37
    • Dart version 2.5.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Users/yousefmosa/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)
    ! Some Android licenses not accepted.  To resolve this, run: flutter doctor --android-licenses

[!] Xcode - develop for iOS and macOS (Xcode 11.0)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.0, Build version 11A420a
    ✗ CocoaPods not installed.
        CocoaPods is used to retrieve the iOS and macOS platform side's plugin code that responds to your plugin usage on the Dart side.
        Without CocoaPods, plugins will not work on iOS or macOS.
        For more info, see https://flutter.dev/platform-plugins
      To install:
        sudo gem install cocoapods
        pod setup

[✓] Android Studio (version 3.5)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 40.1.2
    • Dart plugin version 191.8423
    • Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b49-5587405)

[✓] IntelliJ IDEA Community Edition (version 2019.1.3)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 37.0.3
    • Dart plugin version 191.7830

[✓] VS Code (version 1.37.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.3.0

[✓] Connected device (1 available)
    • iPhone 11 Pro Max • XXX-6B2F-XXX-9B01-XXXXXX • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-0 (simulator)

! Doctor found issues in 2 categories.

Body:
This is because of recent changes in macOS Catalina.

sudo spctl --add "Path_to_flutter/bin/cache/artifacts/libimobiledevice/ideviceinfo"

You might need to reboot the system in order to apply the changes.

You can run a GateKeeper script to fix the issue.

I have published an article with more information how to fix this.


来源: stackexchange

问:
Scikit-Learn + Scipy.optimize external optimizers in Gaussian Processes regression
I am using the Gaussian Processes regression from Scikit-learn for the first time and I would like to use scipy.optimize external optimizers in:

gp = GaussianProcessRegressor(kernel=kernel, alpha=0.015, normalize_y=True, optimizer= EXT_OPT).
```

What is the correct way to use external optimization library?

答:
Actually I figured it out myself. It is quite easy as follows:

def optimizer(obj_func, initial_theta, bounds):
    optimResult = scipy.optimize.minimize(obj_func, initial_theta,  method='L-BFGS-B', jac=False)
    theta_opt = optimResult.x0
    func_min = optimResult.fun
    return theta_opt, func_min
```
<p>OR</p>
<pre class="lang-py prettyprint-override"><code>def optimizer(obj_func, initial_theta, bounds):
    theta_opt, func_min, _ = opt.fmin_l_bfgs_b(obj_func, initial_theta, bounds=bounds)
    return theta_opt, func_min
</code>```

gp = GaussianProcessRegressor(kernel=kernel, alpha=0.015, normalize_y=True, optimizer=optimizer)
```

ContentLicense: CC BY-SA 4.0

Body:
I am using the Gaussian Processes regression from Scikit-learn for the first time and I would like to use scipy.optimize external optimizers in:

gp = GaussianProcessRegressor(kernel=kernel, alpha=0.015, normalize_y=True, optimizer= EXT_OPT).

What is the correct way to use external optimization library?

Body:
Actually I figured it out myself. It is quite easy as follows:

def optimizer(obj_func, initial_theta, bounds):
    optimResult = scipy.optimize.minimize(obj_func, initial_theta,  method='L-BFGS-B', jac=False)
    theta_opt = optimResult.x0
    func_min = optimResult.fun
    return theta_opt, func_min

OR

def optimizer(obj_func, initial_theta, bounds):
    theta_opt, func_min, _ = opt.fmin_l_bfgs_b(obj_func, initial_theta, bounds=bounds)
    return theta_opt, func_min

gp = GaussianProcessRegressor(kernel=kernel, alpha=0.015, normalize_y=True, optimizer=optimizer)


问:
Spring Data REST: repository multiple value request parameters
Could anyone help me please? In fact, I have a project using Spring boot/Spring Data-REST. In my custom repository interface I create a new method like the following:

```<code>@Query("SELECT h FROM History h WHERE " +
        " (:fromDate IS NULL OR h.date >= :fromDate)" +
        " AND (:toDate IS NULL OR h.date <= :toDate)" +
        " AND (:ids IS NULL OR h.id IN :ids)")
 Page<History> findHistoryByCriteria(
        @Param("fromDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date fromDate,
        @Param("toDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date toDate,
        @Param("ids") List<Integer> ids);
</code>```

When I call it using the URL http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids[]=1&ids[]=2, I get wrong result. In log I get

```<code>TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [5] as [INTEGER] - [null]
TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [6] as [INTEGER] - [null]
</code>```

and if I try to use http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2, it returned me a valid result.

If I try to use  http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2&ids=3, I get an exception

```<code> nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]
</code>```

How should I call an URL containing a multiple value parameter (array) or what should I do to make it treating the parameter as an array or a collection?

Thank you in advance.

答:
For those of you coming here a few years later from when this question was asked, and since it is the top of the google search results, I ran into the same issue and figured out the following:

If you use a Collection type as an argument in your repository method, the only way to get SD Rest to transform it correctly is to pass the value as a comma separated string in a single query parameter as Rindra above comment states. It will not accept multiple parameters of the same name with different values. This is because the conversion code is not smart enough to know that the collection it was provided (e.g. List) is different than the collection that is expected (e.g. List) as it does not look at the inner collection type. It simply sees that a List is expected and a List was provided, so it skips any attempt to convert.

That said, if you instead use an array (Integer[]) instead of a collection, then you can pass the values as a comma separated string in a single query parameter AND as single values in multiple query parameters.

It comes down to the available registered converters in the conversion service. There is a StringToCollectionConverter in the case of "?ids=123,432" and a CollectionToArrayConverter in the case of "?ids=123&ids=432"

ContentLicense: CC BY-SA 3.0

Body:
Could anyone help me please? In fact, I have a project using Spring boot/Spring Data-REST. In my custom repository interface I create a new method like the following:

@Query("SELECT h FROM History h WHERE " +
        " (:fromDate IS NULL OR h.date >= :fromDate)" +
        " AND (:toDate IS NULL OR h.date <= :toDate)" +
        " AND (:ids IS NULL OR h.id IN :ids)")
 Page<History> findHistoryByCriteria(
        @Param("fromDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date fromDate,
        @Param("toDate") @DateTimeFormat(pattern = "MM/dd/yyyy") Date toDate,
        @Param("ids") List<Integer> ids);

When I call it using the URL http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids[]=1&ids[]=2, I get wrong result. In log I get

TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [5] as [INTEGER] - [null]
TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [6] as [INTEGER] - [null]

and if I try to use http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2, it returned me a valid result.

If I try to use  http://{hostname}:{port}/{context}/...?fromDate=08/01/2016&toDate=08/31/2016&ids=2&ids=3, I get an exception

 nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value element [1] did not match expected type [java.lang.Integer (n/a)]

How should I call an URL containing a multiple value parameter (array) or what should I do to make it treating the parameter as an array or a collection?

Thank you in advance.


问:
Why does including <windows.h> result in "error: expected ')' before numeric constant" on an unrelated #define statement
Can anybody explain what is going wrong here?  When I try to compile qtermwidget under MinGW-w64, and adding #include <windows.h> to source file BlockArray.cpp, I get the following compile error relating to #define BlockSize (1 << 12) in BlockArray.h:

```<code>In file included from E:/git/qtermwidget/lib/BlockArray.cpp:27:
E:/git/qtermwidget/lib/BlockArray.h:30:20: error: expected ')' before numeric constant
30 | #define BlockSize (1 << 12)
   |                   ~^
</code>```

Why is the addition of the windows.h header causing this error?  Assuming I really want to add this header, can I change the #define BlockSize (1 << 12) in BlockArray.h somehow to not break the compile?

答:
Thanks very much to Sam and busybee, I can confirm that there is a name conflict in winnt.h which is brought in via windows.h.  It's a typedef using the 'BlockSize' name, rather than another preprocessor definition, however:

```<code>typedef struct _TAPE_SET_MEDIA_PARAMETERS {
    ULONG BlockSize;
} TAPE_SET_MEDIA_PARAMETERS, *PTAPE_SET_MEDIA_PARAMETERS;
</code>```

Changing the #define BlockSize (1 << 12) in BlockArray.h to a new name, e.g. #define LXQT_BlockSize (1 << 12) resolves the conflict.

Body:
Can anybody explain what is going wrong here?  When I try to compile qtermwidget under MinGW-w64, and adding #include <windows.h> to source file BlockArray.cpp, I get the following compile error relating to #define BlockSize (1 << 12) in BlockArray.h:

In file included from E:/git/qtermwidget/lib/BlockArray.cpp:27:
E:/git/qtermwidget/lib/BlockArray.h:30:20: error: expected ')' before numeric constant
30 | #define BlockSize (1 << 12)
   |                   ~^

Why is the addition of the windows.h header causing this error?  Assuming I really want to add this header, can I change the #define BlockSize (1 << 12) in BlockArray.h somehow to not break the compile?

Body:
Thanks very much to Sam and busybee, I can confirm that there is a name conflict in winnt.h which is brought in via windows.h.  It's a typedef using the 'BlockSize' name, rather than another preprocessor definition, however:

typedef struct _TAPE_SET_MEDIA_PARAMETERS {
    ULONG BlockSize;
} TAPE_SET_MEDIA_PARAMETERS, *PTAPE_SET_MEDIA_PARAMETERS;

Changing the #define BlockSize (1 << 12) in BlockArray.h to a new name, e.g. #define LXQT_BlockSize (1 << 12) resolves the conflict.


问:
Remove single quotes and last comma in jquery string using Regex
I have a data

```<code>'abc','def','ghi',
</code>```

I want to remove the single quote on all character and want to remove only the last comma, example like below

```<code>abc,def,ghi
</code>```

How would i achieve that using regex for javascript?

I tried using this regex

```<code>.replace(^\'|,\s*$,"");
</code>```

But seems like it is only removing the first quote as shown below

```<code>abc','def','ghi',
</code>```

I am not very good in regex, i appreciate any help that i can get. Thanks

答:
try this:

```<code>.replace(/\'|,$/g, "");
</code>```

the ^ at the beggining made the regexp to only match the quote at the beggining of the string, also you have to add the g to keep looking after the first match

Body:
I have a data

'abc','def','ghi',

I want to remove the single quote on all character and want to remove only the last comma, example like below

abc,def,ghi

How would i achieve that using regex for javascript?

I tried using this regex

.replace(^\'|,\s*$,"");

But seems like it is only removing the first quote as shown below

abc','def','ghi',

I am not very good in regex, i appreciate any help that i can get. Thanks

Body:
try this:

.replace(/\'|,$/g, "");

the ^ at the beggining made the regexp to only match the quote at the beggining of the string, also you have to add the g to keep looking after the first match


问:
How to make realistic plane movement in unity
My current plane movement is ok for the first iteration except I cannot get around on how to make a effective roll movement. What I need is when you pitch up using up arrow on a bank is to make it pitch in the same direction of the angle your banked at. Ignore Propeller variable it is for something im working on later.

Heres my code

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
public GameObject plane;
public Rigidbody rb;
public float thrust = 100f;
public GameObject propeller;

void Update()
{

    if (Input.GetKey("left"))
    {
        plane.transform.Rotate(0, 0, 1, Space.World);
    }
    if (Input.GetKey("right"))
    {
        plane.transform.Rotate(0, 0, -1, Space.World);
    }
    if (Input.GetKey("space"))
    {
        rb.AddForce(transform.forward * thrust);
    }
    if (Input.GetKey(KeyCode.LeftControl))
    {
        rb.velocity = Vector3.zero;
        rb.angularVelocity = Vector3.zero;
    }
    if (Input.GetKey("down"))
    {
        plane.transform.Rotate(-1, 0, 0, Space.World);
    }
    if (Input.GetKey("up"))
    {
        plane.transform.Rotate(1, 0, 0, Space.World);
    }
}
</code>```

}

答:
I would recommend to see this link https://docs.unity3d.com/ScriptReference/Rigidbody.AddTorque.html.

It helped me to learn how to make a rolling ball in a project for school.

Adding torque will create an equivalent of an linear movement for round object.

Here an exemple

rb.AddTorque("the force in the x axis", the force in the y-axis, "the force int the z axis,"the force mode")

Body:
My current plane movement is ok for the first iteration except I cannot get around on how to make a effective roll movement. What I need is when you pitch up using up arrow on a bank is to make it pitch in the same direction of the angle your banked at. Ignore Propeller variable it is for something im working on later.

Heres my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
public GameObject plane;
public Rigidbody rb;
public float thrust = 100f;
public GameObject propeller;

void Update()
{

    if (Input.GetKey("left"))
    {
        plane.transform.Rotate(0, 0, 1, Space.World);
    }
    if (Input.GetKey("right"))
    {
        plane.transform.Rotate(0, 0, -1, Space.World);
    }
    if (Input.GetKey("space"))
    {
        rb.AddForce(transform.forward * thrust);
    }
    if (Input.GetKey(KeyCode.LeftControl))
    {
        rb.velocity = Vector3.zero;
        rb.angularVelocity = Vector3.zero;
    }
    if (Input.GetKey("down"))
    {
        plane.transform.Rotate(-1, 0, 0, Space.World);
    }
    if (Input.GetKey("up"))
    {
        plane.transform.Rotate(1, 0, 0, Space.World);
    }
}

}


问:
Why does all.equal in R not test for differences per observations where mismatch happen by tolerance amount, rather than the aggregate mean?
all.equal in R tests for differences (absolute / relative) for observations where mismatch happen, and then makes sure that it is within tolerance amount. Ideally, it should test all observations where mismatch happens by tolerance amount, and then report the differences... Why is the behavior so ?

e.g.  In the following case, I would expect the result of all.equal to be FALSE, as the first observation in x is not equal to y

```<code>> x = rep(1, 1000)
> y = rep(1, 1000)
> x = x + 0.001
> y[1] = 2
> print(all.equal(x, y, scale = 1, tolerance=0.01))
[1] TRUE

</code>```

答:
The all.equal function returns TRUE if the the target and current arguments are nearly equal up to a specified tolerance, which has a default value close to 1.5e-8. The function does not return FALSE otherwise, rather it returns the mean relative (scale=NULL) or absolute (scale=1) difference.

```<code>x = rep(1, 1000)
y = rep(1, 1000)
x = x + 0.001
y[1] = 2
print(all.equal(x, y, scale = 1)) # Omit the tolerance
[1] "Mean absolute difference: 0.001998"

mean(abs(x-y))
[1] 0.001998
</code>```

If you read the help page for all.equal, you would see the reason:

```<code>tolerance   numeric ≥ 0. Differences smaller than tolerance are not reported.
</code>```

Edit: Based on Aaron's assessment of the OP's source of confusion, perhaps the any function was required:

```<code>y[1] = 1
any(abs(x-y) > 0.01) # Element-wise comparison
[1] FALSE

y[1] = 2
any(abs(x-y) > 0.01)
[1] TRUE
</code>```

Body:
all.equal in R tests for differences (absolute / relative) for observations where mismatch happen, and then makes sure that it is within tolerance amount. Ideally, it should test all observations where mismatch happens by tolerance amount, and then report the differences... Why is the behavior so ?

e.g.  In the following case, I would expect the result of all.equal to be FALSE, as the first observation in x is not equal to y

> x = rep(1, 1000)
> y = rep(1, 1000)
> x = x + 0.001
> y[1] = 2
> print(all.equal(x, y, scale = 1, tolerance=0.01))
[1] TRUE

Body:
The all.equal function returns TRUE if the the target and current arguments are nearly equal up to a specified tolerance, which has a default value close to 1.5e-8. The function does not return FALSE otherwise, rather it returns the mean relative (scale=NULL) or absolute (scale=1) difference.

x = rep(1, 1000)
y = rep(1, 1000)
x = x + 0.001
y[1] = 2
print(all.equal(x, y, scale = 1)) # Omit the tolerance
[1] "Mean absolute difference: 0.001998"

mean(abs(x-y))
[1] 0.001998

If you read the help page for all.equal, you would see the reason:

tolerance   numeric ≥ 0. Differences smaller than tolerance are not reported.

Edit: Based on Aaron's assessment of the OP's source of confusion, perhaps the any function was required:

y[1] = 1
any(abs(x-y) > 0.01) # Element-wise comparison
[1] FALSE

y[1] = 2
any(abs(x-y) > 0.01)
[1] TRUE


问:
How to make the Espresso test wait until the page loads
I will log in. After that, a request to display a list of cards. Each time this request occurs at a different time and using sleep() is not very good. How can I make the test wait as long as the page is loading? Preferably with sample code.

```<code>@RunWith(AndroidJUnit4.class)
@LargeTest
public class AuthorizationTest {

private IdlingResource mIdlingResource;

@Rule
public ActivityTestRule<AuthorizationActivity> mActivityRule = new ActivityTestRule(AuthorizationActivity.class);

@Before
public void SetUp() throws Exception {
        Thread.sleep(4000);
    try {
        onView(allOf(withId(R.id.tiAuthLogin), (isDisplayed()))).check(matches(isDisplayed()));
    } catch (NoMatchingViewException e) {
        pressBack();
    }
}

@Test
public void checkMoneyBackButton() throws Exception {
    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    onView(isRoot()).perform(waitFor(40000));

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    Espresso.onView(ViewMatchers.withId(R.id.vpCard)).perform(ViewActions.swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}
</code>```

}

答:
I think you should separate the test scenario between login and see card list.
First scenario for login:

```<code>public class AuthorizationTest {
    @Rule
    public ActivityTestRule<AuthorizationActivity> mActivityRule = new ActivityTestRule(AuthorizationActivity.class);
private Activity activity;
    @Before()
    public void setup() {
        activityTestRule.launchActivity(new Intent());
        activity = activityTestRule.getActivity();
    }

    @After()
    public void tearDown() {
        activityTestRule.finishActivity();
    }
@Test
public void login() throws Exception {
    onView(withId(R.id.btnAuthLogin)).perform(click());
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();
    onView(isRoot()).perform(waitId(R.id.swipeRefreshLayout, 45000));
    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());
//asssert login success
onView(withId(R.id.toastloginsuccess)).check(matches(isDisplayed()));
}
</code>```

Second Scenario directly into card list activity.

```<code>public class CardListTest {
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
private Activity activity;
    @Before()
    public void setup() {
        activityTestRule.launchActivity(new Intent());
        activity = activityTestRule.getActivity();
    }

    @After()
    public void tearDown() {
        activityTestRule.finishActivity();
    }
@Test
public void checkMoneyBackButton() throws Exception {
//assertMainActivity
onView(withId(R.id.menuTitle)).check(matches(isDisplayed()));
//Assert what you want
onView(withId(R.id.btnTransferToCard)).check(matches(isDisplayed()));
// Do what you want
}
</code>```

Hope its help.

Body:
I will log in. After that, a request to display a list of cards. Each time this request occurs at a different time and using sleep() is not very good. How can I make the test wait as long as the page is loading? Preferably with sample code.

@RunWith(AndroidJUnit4.class)
@LargeTest
public class AuthorizationTest {

private IdlingResource mIdlingResource;

@Rule
public ActivityTestRule<AuthorizationActivity> mActivityRule = new ActivityTestRule(AuthorizationActivity.class);

@Before
public void SetUp() throws Exception {
        Thread.sleep(4000);
    try {
        onView(allOf(withId(R.id.tiAuthLogin), (isDisplayed()))).check(matches(isDisplayed()));
    } catch (NoMatchingViewException e) {
        pressBack();
    }
}

@Test
public void checkMoneyBackButton() throws Exception {
    onView(withId(R.id.btnAuthLogin)).perform(click());

    Thread.sleep(10000);
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();

    onView(isRoot()).perform(waitFor(40000));

    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());

    Thread.sleep(3000);

    Espresso.onView(ViewMatchers.withId(R.id.vpCard)).perform(ViewActions.swipeUp());

    onView(withId(R.id.statementMoneyBack)).check(matches(isDisplayed()));
}

}

Body:
I think you should separate the test scenario between login and see card list.
First scenario for login:

public class AuthorizationTest {
    @Rule
    public ActivityTestRule<AuthorizationActivity> mActivityRule = new ActivityTestRule(AuthorizationActivity.class);
private Activity activity;
    @Before()
    public void setup() {
        activityTestRule.launchActivity(new Intent());
        activity = activityTestRule.getActivity();
    }

    @After()
    public void tearDown() {
        activityTestRule.finishActivity();
    }
@Test
public void login() throws Exception {
    onView(withId(R.id.btnAuthLogin)).perform(click());
    onView(withId(R.id.etSessionKey1)).perform(typeText("1234"));
    closeSoftKeyboard();
    onView(isRoot()).perform(waitId(R.id.swipeRefreshLayout, 45000));
    ViewInteraction viewInteraction = Espresso.onView(withText("**** 0431"));
    viewInteraction.perform(click());
//asssert login success
onView(withId(R.id.toastloginsuccess)).check(matches(isDisplayed()));
}

Second Scenario directly into card list activity.

public class CardListTest {
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
private Activity activity;
    @Before()
    public void setup() {
        activityTestRule.launchActivity(new Intent());
        activity = activityTestRule.getActivity();
    }

    @After()
    public void tearDown() {
        activityTestRule.finishActivity();
    }
@Test
public void checkMoneyBackButton() throws Exception {
//assertMainActivity
onView(withId(R.id.menuTitle)).check(matches(isDisplayed()));
//Assert what you want
onView(withId(R.id.btnTransferToCard)).check(matches(isDisplayed()));
// Do what you want
}

Hope its help.


问:
Unable to retrieve enum type if the definition is located inside a class via reflection
How to retrieve the enum type if the enum is defined within a class?

Adapted from the code here:

```<code>namespace GetEnumReflectionTesting
{
    enum Foo { Bar = 5 }
    public class MyClass
    {
        enum Foo { Bar =6}
    }

    class Program
    {
        static void Main()
        {
            // Get the assembly containing the enum - Here it's the one executing
            var assembly = Assembly.GetExecutingAssembly();

            var enumType = assembly.GetType("GetEnumReflectionTesting.Foo"); //this obtains the GetEnumReflectionTesting.Foo
            var enumBarValue = enumType.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);

            var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass.Foo"); //but instead of GetEnumReflectionTesting.MyClass.Foo, this returns a null!
            var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);
        }
    }
}
</code>```

Here's something interesting, enumType retrieves the GetEnumReflectionTesting.Foo as expected, but enumType2 instead of retrieve GetEnumReflectionTesting.MyClass.Foo, it returns a null!

So what is the robust way to retrieve the enum type regardless of whether it is defined within a class, or not?

Note that in my scenario, the Foo enum is defined within a class, and I get it from third party vendor which I can't change. So don't suggest me moving the Foo enum outside of the class.

答:
Use + to separate a top-level class name from the nested class name:

var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass+Foo");
// ...............................................................^

var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);
```

<p>That much will result in:</p>

```Bar|6
```

<hr>

<p>Another way to do it is to get the top-level type and then call <code>GetNestedType</code> on it.</p>

<pre class="lang-cs prettyprint-override"><code>var containingType2 = assembly.GetType("GetEnumReflectionTesting.MyClass");
var enumType2 = containingType2.GetNestedType("Foo", BindingFlags.NonPublic);
var enumBarValue3 = enumType2.GetField("Bar").GetValue(null);
Console.WriteLine("{0}|{1}", enumBarValue3, (int)enumBarValue3);
</code>```

Note that you have to use Bindingflags.NonPublic because the way you've defined the nested Foo enum is implicitly private.  If the library you're using has the nested type as public, you can omit that parameter.

Body:
How to retrieve the enum type if the enum is defined within a class?

Adapted from the code here:

namespace GetEnumReflectionTesting
{
    enum Foo { Bar = 5 }
    public class MyClass
    {
        enum Foo { Bar =6}
    }

    class Program
    {
        static void Main()
        {
            // Get the assembly containing the enum - Here it's the one executing
            var assembly = Assembly.GetExecutingAssembly();

            var enumType = assembly.GetType("GetEnumReflectionTesting.Foo"); //this obtains the GetEnumReflectionTesting.Foo
            var enumBarValue = enumType.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue, (int)enumBarValue);

            var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass.Foo"); //but instead of GetEnumReflectionTesting.MyClass.Foo, this returns a null!
            var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
            Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);
        }
    }
}

Here's something interesting, enumType retrieves the GetEnumReflectionTesting.Foo as expected, but enumType2 instead of retrieve GetEnumReflectionTesting.MyClass.Foo, it returns a null!

So what is the robust way to retrieve the enum type regardless of whether it is defined within a class, or not?

Note that in my scenario, the Foo enum is defined within a class, and I get it from third party vendor which I can't change. So don't suggest me moving the Foo enum outside of the class.

Body:
Use + to separate a top-level class name from the nested class name:

var enumType2 = assembly.GetType("GetEnumReflectionTesting.MyClass+Foo");
// ...............................................................^

var enumBarValue2 = enumType2.GetField("Bar").GetValue(null);
Console.WriteLine("{0}|{1}", enumBarValue2, (int)enumBarValue2);

That much will result in:

Bar|6

Another way to do it is to get the top-level type and then call GetNestedType on it.

var containingType2 = assembly.GetType("GetEnumReflectionTesting.MyClass");
var enumType2 = containingType2.GetNestedType("Foo", BindingFlags.NonPublic);
var enumBarValue3 = enumType2.GetField("Bar").GetValue(null);
Console.WriteLine("{0}|{1}", enumBarValue3, (int)enumBarValue3);

Note that you have to use Bindingflags.NonPublic because the way you've defined the nested Foo enum is implicitly private.  If the library you're using has the nested type as public, you can omit that parameter.


问:
How can I use expressions to reduce array of objects
I am in the process of creating a flow which, upon the trigger activating, sends a prompt to a user.

The user selects a response, and then the flow sends a message in the appropriate channel. The prompt items come from the list channels action. I can use body('ListChannels')?['value] to parse the response. The response is an array with each object looking like:

```<code>{
  "id":"",
  "displayName":"General",
  "description":"Used to test in-development features",
  "email":"",
  "webUrl":""
}
</code>```

I want to reduce each object to just the displayName key and use the resulting as the inputs for the next action, this is the accepted input for that action:
["General", "Channel2", "Channel3"]

Is there a way to convert this using the provided expressions/actions for power automate? I also need to use the response to lookup the corresponding array entry "id" for sending a message to that channel.

答:
One possibility is to use looping and control statements to perform 'reduce' and 'lookup' actions:

For reduce: Initialize variable(s) (array) first and push the lookup value to the array(s):

Since the input for the next action requires options that are readable to the user we have to use the channel name.

For lookup: Loop through the original object array and compare each object channel name to your query value:

The user response is stored in selectedResponse. We can loop through each item from the original list channels response and compare this to each objects channel name. If there is a match. We can use the current items id as the argument to the "Post your own adaptive card" action.

Result:

Body:
I am in the process of creating a flow which, upon the trigger activating, sends a prompt to a user.

The user selects a response, and then the flow sends a message in the appropriate channel. The prompt items come from the list channels action. I can use body('ListChannels')?['value] to parse the response. The response is an array with each object looking like:

{
  "id":"",
  "displayName":"General",
  "description":"Used to test in-development features",
  "email":"",
  "webUrl":""
}

I want to reduce each object to just the displayName key and use the resulting as the inputs for the next action, this is the accepted input for that action:
["General", "Channel2", "Channel3"]

Is there a way to convert this using the provided expressions/actions for power automate? I also need to use the response to lookup the corresponding array entry "id" for sending a message to that channel.


问:
which jQuery Class should i use in this scenario?
I'm trying to get the images to move from right to left one-by-one when the mouse is over the arrow button, but I am unable to understand how and which jQuery class I can implement to execute the exact result.

My code is as follows:

```<code><div id="logos">
    <ul>
        <li style="float:left; margin-left:0px; margin-right:40px; "><img src="images/logo&typography_porjects.png" width="300" height="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <div class="clear"></div>
        <li style="float:left; margin-left:0px;"><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
        <li><img src="images/logo-no-image.jpg" height="130" width="130" /></li>
    </ul>
</div>
</code>```

and the CSS code is:

```<code>#logos { width:1200px; float:right; }
#logos ul { list-style:none; float:right; overflow:hidden; }
#logos ul li { display:inline; margin:0 0 0 10px; }
.clear { height:30px; width:100%; clear:both; }
</code>```

答:
You have to use jQuery effects, like for example this one: http://jqueryui.com/demos/effect/

Or use toogle with some image transformations, like changeing image top and left coordinates.

Body:
I'm trying to get the images to move from right to left one-by-one when the mouse is over the arrow button, but I am unable to understand how and which jQuery class I can implement to execute the exact result.

My code is as follows:

and the CSS code is:

#logos { width:1200px; float:right; }
#logos ul { list-style:none; float:right; overflow:hidden; }
#logos ul li { display:inline; margin:0 0 0 10px; }
.clear { height:30px; width:100%; clear:both; }


问:
Is it possible to select an anchor tag which contains a h1 which contains the text "Visit Site"?
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

```<code><a href="/blablabla" target="_blank" rel="noopener noreferrer canonical">
  <h1>Visit Site</h1>
</a>
</code>```

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

答:
You can use jQuery's contains selector to find the desired h1 based on text inside it. Once h1 is found, just select its parent which will be your anchor.</p>

```<code>let targetH1 = $('a h1:contains("Visit Site")');

console.log(targetH1.parent()); // this will give you the anchor element
</code>```

Body:
I am using Cypress.io to test my startup's website and would like to select a specific anchor tag.

However, that anchor tag does not have any unique attribute I can use to identify it, therefore I would like to use a child h1 tag containing the text "Visit Site" to help with identifying the anchor tag.

Visit Site

I would not be able to use the href attribute to help identify the anchor tag, as the written test would be used across other pages of the same structure but of different content.

My issue is that I do not know if its possible to select an element based on whether it contains an element of a certain text.

Body:
You can use jQuery's contains selector to find the desired h1 based on text inside it. Once h1 is found, just select its parent which will be your anchor.

let targetH1 = $('a h1:contains("Visit Site")');

console.log(targetH1.parent()); // this will give you the anchor element


答:
There is an easy way, use the $ operator

```<code>.replace(/'|,$/g, '')
</code>```

Title: Remove single quotes and last comma in jquery string using Regex

Body:
There is an easy way, use the $ operator

.replace(/'|,$/g, '')


问:
Flutter App Running Error: Dart can not be opened, Developer can not be verified after upgrading to Catalina
I was using the latest version of Android Studio IDE for creating flutter apps. But when I upgraded from Mojave to Catalina and tried to open my flutter code on IDE it gave me an error saying:

Dart can not be opened because the Developer can not be verified

What is the reason behind the error and how can I solve the issue?

Do I have to install flutter and relative development tools from scratch again or is there any other way to resolve the issue?

答:
Disabling entire Gate Keeper is definitely not a good idea as it will result running any type of program on your system.

You can add Dart to the white list by running this in terminal:

```<code>sudo spctl --add "Path_to_flutter/bin/cache/dart-sdk/bin/dart"
</code>```

You might require to reboot the system in order to apply the changes.

There are several other binaries other than Dart that may get blocked as well.

You can run GateKeeper script to fix the issue:

https://github.com/AmirKamali/Flutter_GateKeeper_Fix

I have published an article with more information how to fix this:

https://medium.com/@amir.n3t/how-to-fix-flutter-idevice-id-running-errors-in-mac-osx-catalina-7aa1f89f61aa

Body:
Disabling entire Gate Keeper is definitely not a good idea as it will result running any type of program on your system.

You can add Dart to the white list by running this in terminal:

sudo spctl --add "Path_to_flutter/bin/cache/dart-sdk/bin/dart"

You might require to reboot the system in order to apply the changes.

There are several other binaries other than Dart that may get blocked as well.

You can run GateKeeper script to fix the issue:

https://github.com/AmirKamali/Flutter_GateKeeper_Fix

I have published an article with more information how to fix this:

https://medium.com/@amir.n3t/how-to-fix-flutter-idevice-id-running-errors-in-mac-osx-catalina-7aa1f89f61aa


问:
Is there a way to dynamically create a counter if such "month" exists?
I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?

CODE

```<code>public HashMap<String, Integer> getDataPoint() {
    //My function code
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int janCounter = 0;
    int febCounter = 0;
    int marCounter = 0;
    int aprCounter = 0;
    int mayCounter = 0;
    int juneCounter = 0;
    int julyCounter = 0;
    int augCounter = 0;
    int septCounter = 0;
    int octCounter = 0;
    int novCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    OpenCsvReader reader = new OpenCsvReader();
    ArrayList <STPost> STArray = reader.loadST("file_path");

    Iterator STitr = STArray.iterator();
    while (STitr.hasNext()) {
        STPost St = (STPost) STitr.next();
        Date retrievedate = St.getTime();
        String strDate = sdf.format(retrievedate);
        if(strDate.equals("Jan")) {
            janCounter++;
        }
        else if (strDate.equals("Feb")) {
            febCounter++;
        }
        else if (strDate.equals("Mar")) {
            marCounter++;
        }
        else if (strDate.equals("Apr")) {
            aprCounter++;
        }
        else if (strDate.equals("May")) {
            mayCounter++;
        }
        else if (strDate.equals("June")) {
            juneCounter++;
        }
        else if (strDate.equals("July")) {
            julyCounter++;
        }
        else if (strDate.equals("Aug")) {
            augCounter++;
        }
        else if (strDate.equals("Sept")) {
            septCounter++;
        }
        else if (strDate.equals("Oct")) {
            octCounter++;
        }
        else if (strDate.equals("Nov")) {
            novCounter++;
        }
        else if (strDate.equals("Dec")) {
            decCounter++;
        }
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        numberOfPost.put("March", marCounter);
        numberOfPost.put("April", aprCounter);
        numberOfPost.put("May", mayCounter);
        numberOfPost.put("June", juneCounter);
        numberOfPost.put("July", julyCounter);
        numberOfPost.put("August", augCounter);
        numberOfPost.put("September", septCounter);
        numberOfPost.put("October", octCounter);
        numberOfPost.put("November", novCounter);
        numberOfPost.put("December", decCounter);
    }
  return numberOfPost
}
</code>```

答:
You already have a good start. Using a the hash map will make the code much tidier.
You can replace all those if statements and put statements with the code below:

```<code>if (!numberOfPosts.containsKey(strDate)) {
    numberOfPosts.put(strDate, 0);
}
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1);
</code>```

The if statement will create a dictionary entry if there is not one with the key of strDate. The value of the entry is set to 0.

```<code>numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1)
</code>```

The line above increments by 1 the dictionary entry with the key of strDate.

Body:
I would like to enquire or get some reference as to how can I dynamically create a counter for each month if the exists ? Currently, I am retrieving the dates from a CSV file and store it in an ArrayList, from there I am comparing the dates to check whether if such month exists. If the month exists then "counter++". Afterwards, store the counter in a hashmap. I understand my code currently is an inefficient way of coding. How could I make it better ?

CODE

public HashMap<String, Integer> getDataPoint() {
    //My function code
    HashMap<String, Integer> numberOfPost = new HashMap<String, Integer>();
    int janCounter = 0;
    int febCounter = 0;
    int marCounter = 0;
    int aprCounter = 0;
    int mayCounter = 0;
    int juneCounter = 0;
    int julyCounter = 0;
    int augCounter = 0;
    int septCounter = 0;
    int octCounter = 0;
    int novCounter = 0;
    int decCounter = 0;
    String pattern = "MMM";
    SimpleDateFormat sdf = new SimpleDateFormat(pattern);

    OpenCsvReader reader = new OpenCsvReader();
    ArrayList <STPost> STArray = reader.loadST("file_path");

    Iterator STitr = STArray.iterator();
    while (STitr.hasNext()) {
        STPost St = (STPost) STitr.next();
        Date retrievedate = St.getTime();
        String strDate = sdf.format(retrievedate);
        if(strDate.equals("Jan")) {
            janCounter++;
        }
        else if (strDate.equals("Feb")) {
            febCounter++;
        }
        else if (strDate.equals("Mar")) {
            marCounter++;
        }
        else if (strDate.equals("Apr")) {
            aprCounter++;
        }
        else if (strDate.equals("May")) {
            mayCounter++;
        }
        else if (strDate.equals("June")) {
            juneCounter++;
        }
        else if (strDate.equals("July")) {
            julyCounter++;
        }
        else if (strDate.equals("Aug")) {
            augCounter++;
        }
        else if (strDate.equals("Sept")) {
            septCounter++;
        }
        else if (strDate.equals("Oct")) {
            octCounter++;
        }
        else if (strDate.equals("Nov")) {
            novCounter++;
        }
        else if (strDate.equals("Dec")) {
            decCounter++;
        }
        numberOfPost.put("January", janCounter);
        numberOfPost.put("Feburary", febCounter);
        numberOfPost.put("March", marCounter);
        numberOfPost.put("April", aprCounter);
        numberOfPost.put("May", mayCounter);
        numberOfPost.put("June", juneCounter);
        numberOfPost.put("July", julyCounter);
        numberOfPost.put("August", augCounter);
        numberOfPost.put("September", septCounter);
        numberOfPost.put("October", octCounter);
        numberOfPost.put("November", novCounter);
        numberOfPost.put("December", decCounter);
    }
  return numberOfPost
}

Body:
You already have a good start. Using a the hash map will make the code much tidier.
You can replace all those if statements and put statements with the code below:

if (!numberOfPosts.containsKey(strDate)) {
    numberOfPosts.put(strDate, 0);
}
numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1);

The if statement will create a dictionary entry if there is not one with the key of strDate. The value of the entry is set to 0.

numberOfPosts.put(strDate, numberOfPosts.get(strDate) + 1)

The line above increments by 1 the dictionary entry with the key of strDate.


问:
How to check if all items in a list are of the same type?
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Edit:

I've now tried combining a couple of the answers into a section of the code:

```<code>def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()
</code>```

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

答:
Complete code.</p>

```<code>def check_input_type(value):
    try:
        value = int(value)
        print(f"Value {value} is an integer!")
        return value
    except ValueError:
        try:
            value = float(value)
            print(f"Value {value} is a float!")
            return value
        except ValueError:
            print(f"Value {value} is a string!")
            return value

def max_of_three():
    max_list = []
    while True:
        value = check_input_type(input(f"Please enter your value : "))
        if not max_list: # if list is empty, append first value.
            max_list.append(value)
        elif type(max_list[0]) == type(value): # checks the next value's type if equal to the first index's type
            max_list.append(value)
        else:
            print("Sorry, I do not understand. Please try again.")
        if len(max_list) != 3:
            continue
        return max_list

listr = max_of_three()

print(f"The maximum of these values {listr} is {max(listr)}!")
</code>```

Body:
I'm trying to have a function validate that all items in a list are of the same type. See "check for integer type" section. However, that section of my function returns False no matter the input at the moment.

What would be the best way to have that section check for the type of input (float, string, integer), return False if they are not all the same, and return True otherwise? And have the function ask for another input if they are not of all the same type.

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for integer type across the list:
    value = all(isinstance(item, int) for item in maxlist)
    print(value)

#    except:
#        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Edit:

I've now tried combining a couple of the answers into a section of the code:

def max_of_three():

    # Ask users to input values
    value1 = input('Enter the first value here:  \n')
    value2 = input('Enter the second value here:  \n')
    value3 = input('Enter the third value here:  \n')

    # Store values in a list
    maxlist = [value1, value2, value3]
    maxlist.sort()

    # Check for type across the list:
    try:
        typecheck = all(isinstance(item, type(maxlist[0])) for item in maxlist[1:])
    except typecheckerror:
        print('Please ensure all inputs are of the same type!')

    #print the values
    print('\n')
    print('The maximum of these values is: \n', maxlist[-1])

max_of_three()

Any pointers on how I could modify this to do what I'm trying to get to? It should return 'c' if I input (a,b,c) and give me the error message if I enter (1,2,a). When I print the value for typecheck, it returns a value of "True" even if I enter something like 1,2,a.

Body:
Complete code.

def check_input_type(value):
    try:
        value = int(value)
        print(f"Value {value} is an integer!")
        return value
    except ValueError:
        try:
            value = float(value)
            print(f"Value {value} is a float!")
            return value
        except ValueError:
            print(f"Value {value} is a string!")
            return value

def max_of_three():
    max_list = []
    while True:
        value = check_input_type(input(f"Please enter your value : "))
        if not max_list: # if list is empty, append first value.
            max_list.append(value)
        elif type(max_list[0]) == type(value): # checks the next value's type if equal to the first index's type
            max_list.append(value)
        else:
            print("Sorry, I do not understand. Please try again.")
        if len(max_list) != 3:
            continue
        return max_list

listr = max_of_three()

print(f"The maximum of these values {listr} is {max(listr)}!")


问:
How to implement the server URL in a python program
I'm new to python. And I extracted some links from twitter and tried to use the Memento Aggregator to create a histogram. I've already used docker online playground to open the Memento Aggregator and how do I write a program to implement these links from a txt to the Memento Aggregator?

My current code is

```<code>import requests

host = 'https://www.katacoda.com/courses/docker/playground'
with open('Extracted links.txt', 'w') as f:
    for line in f:
    response = requests.get(host+"/timemap/json/"+line)
</code>```

I used tweepy to extract some links. Here are some samples.

https://www.mytownneo.com/sports/20200215/no-comeback-this-time-barberton-crushes-tallmadge-boys-basketball
https://twitter.com/i/web/status/1228709479589404672
https://www.sctimes.com/story/sports/2020/02/14/albany-beats-no-1-sauk-centre-final-seconds/4768857002/
http://www.fiba.basketball/fiba-once-again-top-in-international-sports-federations-social-media-ranking-report-for-2019
https://twitter.com/i/web/status/1228709487600640000
How to write a python program to implement them in the docker containment and use the memogator to process these links?

I use this playground to run memogator.（https://www.katacoda.com/courses/docker/playground） I tried to let Memogator timemap to process these links but I got stuck at implementing these url links to the MemoGator.This is MemoGator which can process links. And here is the GitHub link. github.com/oduwsdl/memgator enter image description here

答:
You can use wget package to download the file and read the file:</p>

```<code>import wget

url="your URL"
filename = wget.download(url)
#Read csv/text
pdf = pd.read_csv(filename)
print ("Shape of dataset: ", pdf.shape)
print(pdf.head(5))
</code>```

Body:
I'm new to python. And I extracted some links from twitter and tried to use the Memento Aggregator to create a histogram. I've already used docker online playground to open the Memento Aggregator and how do I write a program to implement these links from a txt to the Memento Aggregator?

My current code is

import requests

host = 'https://www.katacoda.com/courses/docker/playground'
with open('Extracted links.txt', 'w') as f:
    for line in f:
    response = requests.get(host+"/timemap/json/"+line)

I used tweepy to extract some links. Here are some samples.

https://www.mytownneo.com/sports/20200215/no-comeback-this-time-barberton-crushes-tallmadge-boys-basketball
https://twitter.com/i/web/status/1228709479589404672
https://www.sctimes.com/story/sports/2020/02/14/albany-beats-no-1-sauk-centre-final-seconds/4768857002/
http://www.fiba.basketball/fiba-once-again-top-in-international-sports-federations-social-media-ranking-report-for-2019
https://twitter.com/i/web/status/1228709487600640000
How to write a python program to implement them in the docker containment and use the memogator to process these links?

I use this playground to run memogator.（https://www.katacoda.com/courses/docker/playground） I tried to let Memogator timemap to process these links but I got stuck at implementing these url links to the MemoGator.This is MemoGator which can process links. And here is the GitHub link. github.com/oduwsdl/memgator enter image description here

Body:
You can use wget package to download the file and read the file:

import wget

url="your URL"
filename = wget.download(url)
#Read csv/text
pdf = pd.read_csv(filename)
print ("Shape of dataset: ", pdf.shape)
print(pdf.head(5))


问:
I can't write a script for winning level in c# for my Unity game.I need help pls
In my game, to win a level, You need to get some items into a shopping cart and then you need to go into a trigger.But i have a problem cause i cannot write a script myself (I am learning).when i take one thing with tag Bread into the trigger it ends the level.But i need a script that makes all items with "Bread" tag finish the level and not one item with "Bread" tag.
This is the script that i wrote.PLS help me :)

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneSwitch : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        {
            GameObject[] objs;
            objs = GameObject.FindGameObjectsWithTag("Bread");

            {
                SceneManager.LoadScene(2);
            }

        }

    }
}
</code>```

There is a video to explain my problem https://www.youtube.com/watch?v=OIVGLUwHDA4

答:
Like BugFinder commented, it's would be best to make a simple script where you add item  to a list when they are placed in their cart.

Once you move the cart to the end game trigger, you check if it's 2 item of the type "Bread" in the cart, else you trigger another message to tell the player he's missing something.

It's like in your video, you check for the item before going to next level, now you just do it with by iterating through a list. Or if you really want to do it "easy" you could just have a counter for every type of item and do a ++ on that counter when that type is added to the cart ( or -- if removed from the cart) and check if  type >= 2 to verify the trigger to next level event

Body:
In my game, to win a level, You need to get some items into a shopping cart and then you need to go into a trigger.But i have a problem cause i cannot write a script myself (I am learning).when i take one thing with tag Bread into the trigger it ends the level.But i need a script that makes all items with "Bread" tag finish the level and not one item with "Bread" tag.
This is the script that i wrote.PLS help me :)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneSwitch : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        {
            GameObject[] objs;
            objs = GameObject.FindGameObjectsWithTag("Bread");

            {
                SceneManager.LoadScene(2);
            }

        }

    }
}

There is a video to explain my problem https://www.youtube.com/watch?v=OIVGLUwHDA4


问:
How can i convert this sql query in a eloquent laravel command?
in sql query this commando do exactly i wanted:

```<code>SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v
</code>```

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

```<code>class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

</code>```

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );
```

<p>Step 2/3 - then i used the array_map to organize my viagens ids</p>

<pre class="lang-php prettyprint-override"><code>$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );
</code>```

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();
```

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

答:
Try this.</p>

```<code>$status_id = Viagem::join('status','viagem.id','status_viagem.viagem_id')
             ->select('viagem.id','status_viagem.status_id')
             ->get();
</code>```

Body:
in sql query this commando do exactly i wanted:

SELECT
    v.id,
    (
        SELECT sv.status_id
        FROM status_viagem sv
        WHERE sv.viagem_id = v.id
        ORDER BY sv.created_at DESC LIMIT 1 ) AS status_id
FROM viagens v

Here is the sql results:

But i have no idea how can i do this using Laravel eloquent

Basically, a viagem entry can has a lot of status, but i need to get each viagem and their last status entry from status_viagem table (the pivot table)

by the way viagem/viagens means travel.

My class mapping:

class Viagem extends Model
{
  ...
  public function status()
  {
        return $this->belongsToMany('App\Status')->withTimestamps();
  }
  ...
}

class Status extends Model
{

    public function viagens()
    {
        return $this->belongsToMany('App\Viagem')->withTimestamps();
    }
}

The belongsToMany at both classes gets me a many-to-many:

can someone help me? thanks

---------- Temporary Solution -------

Thanks for all help  guys. In fact i can't find a nice solution using only eloquent.

Step 1/3 - To bypass this situation i first execute the above sql to grab only the viagens under the desired status_id (last status_viagem entry):

$viagens_ids = DB::select(
            "SELECT viagem_id FROM (
                SELECT
                    v.id AS viagem_id,
                    (
                        SELECT sv.status_id
                        FROM status_viagem sv
                        WHERE sv.viagem_id = v.id
                        ORDER BY sv.id DESC LIMIT 1 ) AS status_id
                FROM viagens v
            ) AS tt

            WHERE tt.status_id = {$status->id}"
        );

Step 2/3 - then i used the array_map to organize my viagens ids

$a = array_map(
                function($obj) { return $obj->viagem_id; },
                $viagens_ids
            );

Step 3/3 - And at last i used elequent whereIn to fetch my viagens:

 Viagem::with( 'status')->whereIn('id', $a)->get();

In fact i have solved the problem by a-old-sashion-way but i not happy with it because i wish i learn how to do it using eloquent. what bad to me.

Body:
Try this.

$status_id = Viagem::join('status','viagem.id','status_viagem.viagem_id')
             ->select('viagem.id','status_viagem.status_id')
             ->get();


问:
dc.js - Chart not rendering (single row bar chart - horizontal row), with the exception of legend, axes and tick marks/values (which do render)
Scenario

I want to see my dc.js horizontal row stacked bar chart (single row chart), but no chart appears, except for legend with names, axes with tick marks which do appear.

Screenshot

Data set below in code snippet

Question

How do I render the ensure chart rendering successfully using dc.js / d3.js?

Code Snippet

```<code>$scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12},
                    {"Project":"Expedition","Stage": "Active", "Days":14},
                    {"Project":"Expedition","Stage": "Closure", "Days":2}
    ];
    var ndx = crossfilter(data);

    data.forEach(function(x) {
      x.Days = 0;
    });

    var ndx = crossfilter(data)

    var xdim = ndx.dimension(function (d) {return d.Days;});

    function root_function(dim,stack_names) {
        return dim.group().reduce(
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function() {
        return {};
      });}

    var stages = ['Created', 'Active', 'Closure'];
    var ygroup = root_function(xdim,stages)

    function sel_stack(i) {
    return function(d) {
      return d.value[i];
    };}

    cycleChart = new dc.barChart("#risk-cycle-chart");

    var chart = document.getElementById('risk-cycle-chart');

    heightStatusChart =  200;
    widthStatusChart = Math.floor(parseFloat(window.getComputedStyle(chart, null).width))
     - 2*parseInt(window.getComputedStyle(chart, null).getPropertyValue('padding-top'));

    cycleChart
      .x(d3.scaleLinear().domain([0,7,14,21,28]))
      .dimension(xdim)
      .group(ygroup, data[0].Project, sel_stack(data[0].Project))
      .xUnits(dc.units.ordinal)
      .margins({left:75, top: 0, right: 0, bottom: 20})
      .width(widthStatusChart)
      .height(heightStatusChart)
      .legend(dc.legend());

    for(var i = 1; i<stages.length; ++i)
      cycleChart.stack(ygroup, stages[i], sel_stack(stages[i]));
</code>```

}

答:
I resorted to not using a vector graphics generator like d3/dc for this grid portion and instead created a table like so.

```<code> $scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12, "Color": "rgb(166, 206, 227)"},
                    {"Project":"Expedition","Stage": "Active", "Days":14, "Color": "rgb(253, 180, 98)"},
                    {"Project":"Expedition","Stage": "Closure", "Days":2, "Color": "rgb(179, 222, 105)"}
    ];

    var tbl = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // table row creation
    var row = document.createElement("tr");

    for (var i = 0; i <= 2; i++) {
      // create element <td> and text node
      //Make text node the contents of <td> element
      // put <td> at end of the table row
      var cell = document.createElement("td");
      cell.setAttribute('style', 'width: ' + data[i].Days * 100 + "px; background-color: " + data[i].Color);
      var cellText = document.createTextNode(data[i].Stage + " " + data[i].Days);

      cell.appendChild(cellText);
      row.appendChild(cell);
    }

    //row added to end of table body
    tblBody.appendChild(row);

      // append the <tbody> inside the <table>
      tbl.appendChild(tblBody);
      // put <table> in the <body>
      document.querySelector("#risk-cycle-chart").appendChild(tbl);

}
</code>```

Body:
Scenario

I want to see my dc.js horizontal row stacked bar chart (single row chart), but no chart appears, except for legend with names, axes with tick marks which do appear.

Screenshot

Data set below in code snippet

Question

How do I render the ensure chart rendering successfully using dc.js / d3.js?

Code Snippet

$scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12},
                    {"Project":"Expedition","Stage": "Active", "Days":14},
                    {"Project":"Expedition","Stage": "Closure", "Days":2}
    ];
    var ndx = crossfilter(data);

    data.forEach(function(x) {
      x.Days = 0;
    });

    var ndx = crossfilter(data)

    var xdim = ndx.dimension(function (d) {return d.Days;});

    function root_function(dim,stack_names) {
        return dim.group().reduce(
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function(p, v) {
        stack_names.forEach(stack_name => {
          if(v[stack_name] !== undefined)
              p[stack_name] = (p[v[stack_name]] || 0) + v[stack_name]
        });
        return p;},
      function() {
        return {};
      });}

    var stages = ['Created', 'Active', 'Closure'];
    var ygroup = root_function(xdim,stages)

    function sel_stack(i) {
    return function(d) {
      return d.value[i];
    };}

    cycleChart = new dc.barChart("#risk-cycle-chart");

    var chart = document.getElementById('risk-cycle-chart');

    heightStatusChart =  200;
    widthStatusChart = Math.floor(parseFloat(window.getComputedStyle(chart, null).width))
     - 2*parseInt(window.getComputedStyle(chart, null).getPropertyValue('padding-top'));

    cycleChart
      .x(d3.scaleLinear().domain([0,7,14,21,28]))
      .dimension(xdim)
      .group(ygroup, data[0].Project, sel_stack(data[0].Project))
      .xUnits(dc.units.ordinal)
      .margins({left:75, top: 0, right: 0, bottom: 20})
      .width(widthStatusChart)
      .height(heightStatusChart)
      .legend(dc.legend());

    for(var i = 1; i<stages.length; ++i)
      cycleChart.stack(ygroup, stages[i], sel_stack(stages[i]));

}

Body:
I resorted to not using a vector graphics generator like d3/dc for this grid portion and instead created a table like so.

 $scope.avgCycleTime = function(){

    var data = [
                    {"Project":"Expedition","Stage": "Created", "Days":12, "Color": "rgb(166, 206, 227)"},
                    {"Project":"Expedition","Stage": "Active", "Days":14, "Color": "rgb(253, 180, 98)"},
                    {"Project":"Expedition","Stage": "Closure", "Days":2, "Color": "rgb(179, 222, 105)"}
    ];

    var tbl = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // table row creation
    var row = document.createElement("tr");

    for (var i = 0; i <= 2; i++) {
      // create element <td> and text node
      //Make text node the contents of <td> element
      // put <td> at end of the table row
      var cell = document.createElement("td");
      cell.setAttribute('style', 'width: ' + data[i].Days * 100 + "px; background-color: " + data[i].Color);
      var cellText = document.createTextNode(data[i].Stage + " " + data[i].Days);

      cell.appendChild(cellText);
      row.appendChild(cell);
    }

    //row added to end of table body
    tblBody.appendChild(row);

      // append the <tbody> inside the <table>
      tbl.appendChild(tblBody);
      // put <table> in the <body>
      document.querySelector("#risk-cycle-chart").appendChild(tbl);

}


问:
How to only allow images to be accessed by logged in users
Currently using Codeigniter/PHP and IIS 7

I have currently looked at "hotlinking" but that only protects images from being put onto other web sites. It doesn't stop the end user from directly pasting the image URL into the address bar and accessing the image whilst not being logged in.

I am not too sure what the best way is to approach this problem. How can you protect images so that it can only be accessed by logged in users?

Thank you.

答:
There are perfomance issues in the above answer. You can rename the folder that containing images every hour / day ....
Ex

images/a8s7d5r7w9/33229.png to images/g2j3s3l1p2t/33229.png


问:
Line 103:9: Expected an assignment or function call and instead saw an expression no-unused-expressions

I keep getting this error but I don't know why code below

class AccountInfo extends Component {
  render() {
    const awards = <Tooltip id="view">View profile awards</Tooltip>;
    const channel = <Tooltip id="edit">Update channel page</Tooltip>;
    const verified = <Tooltip id="remove">Verified</Tooltip>;

      <OverlayTrigger placement="top" overlay={awards}>
        <Button simple bsStyle="info" bsSize="xs">

        </Button>
      </OverlayTrigger>
      <OverlayTrigger placement="top" overlay={channel}>
        <Button simple bsStyle="success" bsSize="xs">

        </Button>
      </OverlayTrigger>
      <OverlayTrigger placement="top" overlay={verified}>
        <Button simple bsStyle="danger" bsSize="xs">

        </Button>
      </OverlayTrigger>
    	;
  }
}
```

Line 103:9: Expected an assignment or function call and instead saw an expression no-unused-expressions

答:
First thing, you are not returning anything from your render function.

Try updating with.

class AccountInfo extends Component {
  render() {
    const awards = <Tooltip id="view">View profile awards</Tooltip>;
    const channel = <Tooltip id="edit">Update channel page</Tooltip>;
    const verified = <Tooltip id="remove">Verified</Tooltip>;
    return (

        <OverlayTrigger placement="top" overlay={awards}>
          <Button simple bsStyle="info" bsSize="xs">

          </Button>
        </OverlayTrigger>
        <OverlayTrigger placement="top" overlay={channel}>
          <Button simple bsStyle="success" bsSize="xs">

          </Button>
        </OverlayTrigger>
        <OverlayTrigger placement="top" overlay={verified}>
          <Button simple bsStyle="danger" bsSize="xs">

          </Button>
        </OverlayTrigger>

    );
  }
}
```

Body:
I keep getting this error but I don't know why code below

class AccountInfo extends Component {
  render() {
    const awards = <Tooltip id="view">View profile awards</Tooltip>;
    const channel = <Tooltip id="edit">Update channel page</Tooltip>;
    const verified = <Tooltip id="remove">Verified</Tooltip>;

      <OverlayTrigger placement="top" overlay={awards}>
        <Button simple bsStyle="info" bsSize="xs">

        </Button>
      </OverlayTrigger>
      <OverlayTrigger placement="top" overlay={channel}>
        <Button simple bsStyle="success" bsSize="xs">

        </Button>
      </OverlayTrigger>
      <OverlayTrigger placement="top" overlay={verified}>
        <Button simple bsStyle="danger" bsSize="xs">

        </Button>
      </OverlayTrigger>
    	;
  }
}

Line 103:9: Expected an assignment or function call and instead saw an expression no-unused-expressions

Body:
First thing, you are not returning anything from your render function.

Try updating with.

class AccountInfo extends Component {
  render() {
    const awards = <Tooltip id="view">View profile awards</Tooltip>;
    const channel = <Tooltip id="edit">Update channel page</Tooltip>;
    const verified = <Tooltip id="remove">Verified</Tooltip>;
    return (
      <td className="td-actions text-right">
        <OverlayTrigger placement="top" overlay={awards}>
          <Button simple bsStyle="info" bsSize="xs">
            <i className="fa fa-user" />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger placement="top" overlay={channel}>
          <Button simple bsStyle="success" bsSize="xs">
            <i className="fa fa-edit" />
          </Button>
        </OverlayTrigger>
        <OverlayTrigger placement="top" overlay={verified}>
          <Button simple bsStyle="danger" bsSize="xs">
            <i className="fa fa-times" />
          </Button>
        </OverlayTrigger>
      </td>
    );
  }
}


问:
Having an issue reading a string from a file of names in C
I am reading through a text file that has a line on each name. I need to generate a random number from 0-99 to determine the index of the name to choose. When I use the method fscanf() and then I try to display the string that I read, a blank string is outputted. I have tested it and I am entering the if statement to assign the string to the variable, there just seems to be an issue with assigning the name. </p>

```<code>int indexOfName = rand() % 100;
        printf("%d\n", indexOfName);

        FILE *fileOfNames;
        char str[30];
        char *filename = "theFilePath";

        fileOfNames = fopen(filename, "r");
        rewind(fileOfNames);
        if (fileOfNames == NULL)
        {
            printf("Could not open file %s", filename);
            return 1;
        }
        int i = 0;
        while (fgets(str, 30, fileOfNames) != NULL)
        {
            if (i == indexOfName)
            {
                fscanf(fileOfNames, "%s", str);
            }
            i++;
        }
        printf("%s\n", str);
        fclose(fileOfNames);
        return 0;
</code>```

答:
Your code has 2 problems:

1) It continues overwriting str after it finds the right entry.  You can avoid this by stopping after iterating up to indexOfName.

2) After it assigns the right value to str, it overwrites it again with the call to fscanf.

It also probably makes more sense to use a for loop for this, since you want a specific number of iterations.  You can make your code work correctly by replacing the while loop with this for loop:

```<code>for (int i = 0; i < indexOfName; i++) fgets(str, 30, fileOfNames);
</code>```

Body:
I am reading through a text file that has a line on each name. I need to generate a random number from 0-99 to determine the index of the name to choose. When I use the method fscanf() and then I try to display the string that I read, a blank string is outputted. I have tested it and I am entering the if statement to assign the string to the variable, there just seems to be an issue with assigning the name.

int indexOfName = rand() % 100;
        printf("%d\n", indexOfName);

        FILE *fileOfNames;
        char str[30];
        char *filename = "theFilePath";

        fileOfNames = fopen(filename, "r");
        rewind(fileOfNames);
        if (fileOfNames == NULL)
        {
            printf("Could not open file %s", filename);
            return 1;
        }
        int i = 0;
        while (fgets(str, 30, fileOfNames) != NULL)
        {
            if (i == indexOfName)
            {
                fscanf(fileOfNames, "%s", str);
            }
            i++;
        }
        printf("%s\n", str);
        fclose(fileOfNames);
        return 0;

Body:
Your code has 2 problems:

1) It continues overwriting str after it finds the right entry.  You can avoid this by stopping after iterating up to indexOfName.

2) After it assigns the right value to str, it overwrites it again with the call to fscanf.

It also probably makes more sense to use a for loop for this, since you want a specific number of iterations.  You can make your code work correctly by replacing the while loop with this for loop:

for (int i = 0; i < indexOfName; i++) fgets(str, 30, fileOfNames);


问:
switching views in iphone
i m making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help</p>

```<code>"clientserverprogram view.h"

#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end

"clientserverprogram view.m"

#import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);

}

- (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

-(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

答:
```<code>[self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""
</code>```

This line of code is responsible to present modal ViewController. In your case you only had a view. So either you create a controller for the second view like that:

```<code>SecondViewController *secondController=[[SecondViewController  alloc] initWithNibName:@"secondView" bundle:[NSBundle mainBundle]];
 [self presentModalViewController:secondController animated: YES ];
</code>```

or you can load you second view from nib file using outlet and you can add it as subview to your current view controller view:

```<code>[self.view addSubView:secondview];
</code>```

Update

As I can see on your code SecondView is your controller not the view, but you are try to present a controller that is not initialized. I also noticed that you have an outlet for your view on SecondView, when you create a  new sub class of UIViewController you can check the option that creates a .xib file as well.

Hope that helps,

Title: switching views in iphone

Body:
i m making a client server program in which i want to switch from one view to another but i am getting an error in "clientserverprogram view.m" plz help

"clientserverprogram view.h"

#import <UIKit/UIKit.h>

@class secondview;

@interface clientserverprogramViewController : UIViewController {

    IBOutlet UITextField *name;
    IBOutlet UITextView *filepath;
    IBOutlet UIButton *print;
    IBOutlet UIButton *settings;
    IBOutlet UIButton *cancel;
    IBOutlet UILabel *display;
    IBOutlet secondview *secondview;
}

-(IBAction) print;
-(IBAction) settings;
-(IBAction) cancel;

@property (nonatomic , retain) IBOutlet UITextField *name;
@property (nonatomic , retain) IBOutlet UITextView *filepath;

@property (nonatomic , retain) IBOutlet UILabel *display;
@end

"clientserverprogram view.m"

#import "clientserverprogramViewController.h"
#import "secondview.h"

@implementation clientserverprogramViewController

@synthesize  name ,filepath,display ;

-(IBAction) print {

    NSString *str = name.text;

    [display setText : str];

}

-(IBAction) settings {

    [self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

}

-(IBAction) cancel {

    exit(0);

}

- (void)dealloc {
    [super dealloc];
}

@end

"secondview.h"

#import <UIKit/UIKit.h>

@interface secondview : UIViewController {

    IBOutlet UIView *view;

    IBOutlet UIButton *back;

}

-(IBAction) back;

@end

""secondview.m""

#import "secondview.h"

@implementation secondview

-(IBAction) back {

    [self.parentViewController dismissModalViewControllerAnimated: YES];
}

- (void)dealloc {
    [super dealloc];
}

@end

Body:
[self presentModalViewController: secondview animated: YES ];

"" error: expected expression before 'secondview'""

This line of code is responsible to present modal ViewController. In your case you only had a view. So either you create a controller for the second view like that:

SecondViewController *secondController=[[SecondViewController  alloc] initWithNibName:@"secondView" bundle:[NSBundle mainBundle]];
 [self presentModalViewController:secondController animated: YES ];

or you can load you second view from nib file using outlet and you can add it as subview to your current view controller view:

[self.view addSubView:secondview];

Update

As I can see on your code SecondView is your controller not the view, but you are try to present a controller that is not initialized. I also noticed that you have an outlet for your view on SecondView, when you create a  new sub class of UIViewController you can check the option that creates a .xib file as well.

Hope that helps,


问:
Amount of properties per command/event in event sourcing
I'm learning cqrs/event sourcing, and recently I listen some speach and speaker told that you need pass as few parameters to event as possible, in other words to make events tiny as possible. The main reason for that is it's impossible to change events later as it will break the event history, and its easelly to design small events correctly. But what if for example in UI you need fill in for example form with 10 fields to create new aggregate, and same situation can be with updating the aggregate? How to be in such a case? And how to be if business later consider to change something, but we have huge event which updating 10 fields?</p>

答:
recently I listen some speach and speaker told that you need pass as few parameters to event as possible, in other words to make events tiny as possible.

I'm not convinced that holds up.  If you are looking for good ides about designing events, you should review Greg Young's e-book on versioning.

If you are event sourcing, then you are primarily concerned with ensuring that your stream of events allows you to recreate the state of your domain model.  The events themselves should be representations of changes that a domain expert will recognize.  If you find yourself trying to invent smaller events just to fit some artificial constraint like "no more than three properties per event" then you are going to end up with data that doesn't really match the way your domain experts think -- which is to say, technical debt.


问:
Hide place holder in ng-select when user enters text
I am trying to use ng-select with material design in my Angular 9 project for the autocomplete. By default, when the user entering the text ng-select shows the place holder at top of the autocomplete input field. However, I would like to hide the placeholder as soon as the user enters the text and show it when he clears the input field. Is there a way to achieve this using CSS? Project uploaded to StackBlitz for reference</p>

答:
I would recommend using the search event provided by the element.  It'll provided you with the value of the input and in your case you only care if it has a value.  There exists a css solution, but this just felt cleaner.

In the html

```<code><ng-select ...
   placeholder="{{myPlaceholder}}"
   (search)="onSearch($event)">
  </ng-select>
</code>```

In the TS.

```<code>.
.
myPlaceHolder = "Select Person"
.
.
onSearch($event) {

 this.myPlaceHolder = $event.term == '': 'Select Person': '';
}
</code>```

Body:
I would recommend using the search event provided by the element.  It'll provided you with the value of the input and in your case you only care if it has a value.  There exists a css solution, but this just felt cleaner.

In the html

<ng-select ...
   placeholder="{{myPlaceholder}}"
   (search)="onSearch($event)">
  </ng-select>

In the TS.

.
.
myPlaceHolder = "Select Person"
.
.
onSearch($event) {

 this.myPlaceHolder = $event.term == '': 'Select Person': '';
}


问:
How to run JPF in netbeans.?
I have completed all steps stated below

Download and install jpf-core, e.g. from the Mercurial repository

-------------- take a break ---------------

Download the gov-nasa-jpf-netbeans-runjpf.nbm file from here.

From within Netbeans go to Tools->Plugins (Alt+T followed by Alt+g)

Select the Downloaded tab

Click on Add Plugins... (Alt+A)

Select the gov-nasa-jpf-netbeans-runjpf.nbm file that was downloaded in step 3

Select install

Agree to the License agreement

Restart Netbeans

Now what i have to do to run  the project?

答:
```<code>1. Install netbeans-jpf (see: Installing the NetBeans JPF plugin)
2. Make sure the correct site.properties file is being used for JPF (The default is usually correct)
3. To see which site.properties file is being used:
4. From the NetBeans top menu go to "Tools"->"Options" (Alt+T followed by Alt+O)
5. Select "Miscellaneous" from the top of the Options Window
6. Select the "Java Pathfinder" tab
7. Make sure that "Path to site.properties" is defined properly, uncheck "Use default site.properties location" to change the path
8. From either the "Projects" or "Files" view (on the left of the main NetBeans screen by default,) select the JPF properties file (i.e., a file with a .jpf extension) you would like to run. Right click on this file and select the "Verify..." menu item to run JPF.
9. To view the results, make sure that the "Output" View is open (On the bottom of the main NetBeans screen by default)
</code>```

Title: How to run JPF in netbeans.?


问:
React Native - Promise returns undefined
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.</p>

```<code>import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;
</code>```

```<code>import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}
</code>```

答:
Your isConnected function is not a promise. If you wish to use async/await, isConnected must be a promise.

Try this:

```<code>const isConnected = function() {
  return new Promise((resolve, reject) => {
    NetInfo.fetch().then(state => {
      console.log("state.isConnected: ", state.isConnected)
      resolve(state.isConnected);
    })
    .catch(err => {
      reject(err)
    })
  })
}
</code>```

Body:
I have a js file that returns whether I have internet connection or not, and then in another js I have an if else statement that gets that value. The thing is im getting connection = undefined.

import React from 'react';
import NetInfo from "@react-native-community/netinfo";

const isConnected = function() {
  NetInfo.fetch().then(state => {
    console.log("state.isConnected: ", state.isConnected)
    return state.isConnected
  });
}

export default isConnected;

import isConnected from '../../src/utils/internetConnection';

async checking(){
   var connection = await isConnected()
   console.log("connection : ", connection)
   if (connection){
      return true
   }

   Alert.alert("There is no Internet connection")
   return
}

Body:
Your isConnected function is not a promise. If you wish to use async/await, isConnected must be a promise.

Try this:

const isConnected = function() {
  return new Promise((resolve, reject) => {
    NetInfo.fetch().then(state => {
      console.log("state.isConnected: ", state.isConnected)
      resolve(state.isConnected);
    })
    .catch(err => {
      reject(err)
    })
  })
}


问:
.NET core cannot find XmlDocument
I am trying to recreate the code in .NET Core and i am getting an errors and highlights which do not help to solve a problem.

Here is the code:

```<code>using System;
using System.IO;
using System.Xml;

public class Sample
{
    public static void Main()
    {
         string content = File.ReadAllText("input.xml");
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(content.Trim());
         XmlWriter writer = XmlWriter.Create("output.xml");
         doc.Save(writer);
    }

}
</code>```

I tried adding Referece "System.Xml" to dependencies but it generates new errors.

Errors in .NET Core which do not happen to be in .NET 4.0

Edit:

I just wanted to say this code works now.

.NET Core got updated.

答:
This code works now.

In .NET Core 3.1.

Title: .NET core cannot find XmlDocument

Body:
I am trying to recreate the code in .NET Core and i am getting an errors and highlights which do not help to solve a problem.

Here is the code:

using System;
using System.IO;
using System.Xml;

public class Sample
{
    public static void Main()
    {
         string content = File.ReadAllText("input.xml");
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(content.Trim());
         XmlWriter writer = XmlWriter.Create("output.xml");
         doc.Save(writer);
    }

}

I tried adding Referece "System.Xml" to dependencies but it generates new errors.

Errors in .NET Core which do not happen to be in .NET 4.0

Edit:

I just wanted to say this code works now.

.NET Core got updated.

Body:
This code works now.

In .NET Core 3.1.