问:
AndroidXMapFragment returns null when initializing from fragment
SupportMapFragment is deprecated in here sdk and when i start the navigation, on screen rotation it crashing.

I updated to last version of sdk and followed instruction from official documentation:
https://github.com/heremaps/here-android-sdk-examples/tree/master/turn-by-turn-navigation/app/src/main/java/com/here/android/example/guidance

I implemented on my project in activity but i need this to work on fragment as before.

i replace everything to AndroidX:

from Activity works

```<code>import androidx.appcompat.app.AppCompatActivity;
</code>```

```<code>public MapFragmentView(AppCompatActivity activity) {
   m_activity = activity;
   initMapFragment();
   initNaviControlButton();
}
</code>```

```<code>private AndroidXMapFragment getMapFragment() {
    return (AndroidXMapFragment) m_activity.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}
</code>```

Calling this from Activity works

```<code>MapFragmentView mapFragmentView = new MapFragmentView (this);
</code>```

When i call this from Fragment

```<code>MapFragmentView mapFragmentView = new MapFragmentView (getActivity ());

This does not accept getActivity() because is not compatible.
androidx.appcompat.app.AppCompatActivity in MapFragmentView can not be applied to androidx.fragment.app.ragmentActivity
</code>```

I try to cast it and it accepts

```<code>AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity ();
MapFragmentView mapFragmentView = new MapFragmentView (appCompatActivity);
</code>```

But now the method getMapFragment() return null

```<code>private AndroidXMapFragment getMapFragment() {
    /* this returns null */ return (AndroidXMapFragment) m_activity.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}
</code>```

Here is fragment class, i removed other code to just simplify

```<code>package com.example.Fragments;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.drivosity.drivosity.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

public class FragmentHome extends Fragment {

    private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
    private static final String[] RUNTIME_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE
    };
    private final String TAG = "FragmentHome";
    private View view;
    // Directions

    public FragmentHome() {
        // Required empty public constructor
    }

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate (R.layout.fragment_home, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated (view, savedInstanceState);

        if (hasPermissions(getActivity (), RUNTIME_PERMISSIONS)) {
            setupMapFragmentView();
        } else {
            ActivityCompat
                    .requestPermissions(getActivity (), RUNTIME_PERMISSIONS, REQUEST_CODE_ASK_PERMISSIONS);
        }
    }

    /**
     * Only when the app's target SDK is 23 or higher, it requests each dangerous permissions it
     * needs when the app is running.
     */
    private static boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS: {
                for (int index = 0; index < permissions.length; index++) {
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {

                        /*
                         * If the user turned down the permission request in the past and chose the
                         * Don't ask again option in the permission request system dialog.
                         */
                        if (!ActivityCompat
                                .shouldShowRequestPermissionRationale(getActivity (), permissions[index])) {
//                            Toast.makeText(this, "Required permission " + permissions[index]
//                                            + " not granted. "
//                                            + "Please go to settings and turn on for sample app",
//                                    Toast.LENGTH_LONG).show();
                        } else {
//                            Toast.makeText(this, "Required permission " + permissions[index]
//                                    + " not granted", Toast.LENGTH_LONG).show();
                        }
                    }
                }

                setupMapFragmentView();
                break;
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void setupMapFragmentView() {
        // All permission requests are being handled. Create map fragment view. Please note
        // the HERE Mobile SDK requires all permissions defined above to operate properly.
        AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity ();
        MapFragmentView mapFragmentView = new MapFragmentView (appCompatActivity);

    }

    public interface OnFragmentInteractionListener {
    }
}

</code>```

Layout of Framgnet

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/homeToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/AppTheme"
        app:popupTheme="@style/AppTheme"
        android:visibility="gone">

        <RelativeLayout
            android:id="@+id/homeToolbarItems"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible">

            <TextView
                android:id="@+id/appTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Home"
                android:textAlignment="center"
                android:textColor="@color/color_white"
                android:textSize="20sp"
                android:textStyle="bold" />

        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>

    <!-- Map Fragment embedded with the map object -->
    <fragment
        class="com.here.android.mpa.mapping.AndroidXMapFragment"
        android:id="@+id/mapfragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
</code>```

答:
I figured it out. Here is if anyone have troubles implementing it from Fragment.

But this is with SupportMapFragment, also works with AndroidXMapFragment

```<code>public class FragmentHome extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate (R.layout.fragment_home, container, false);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager ().findFragmentById (R.id.mapFragment);
        MapFragmentView fragmentMap = new MapFragmentView ((AppCompatActivity) getActivity (), mapFragment);

        return view;
    }
}

</code>```

In MapFragmentView constructor i have added one more parameter for SupportMapFragment

```<code>public class MapFragmentView {

    private AppCompatActivity m_activity;
    private SupportMapFragment mapFragment;

    public MapFragmentView(AppCompatActivity activity, SupportMapFragment mapFragment) {
        m_activity = activity;
        this.mapFragment = mapFragment;
        initialize (); // This is init map
    }
}
</code>```

Body:
SupportMapFragment is deprecated in here sdk and when i start the navigation, on screen rotation it crashing.

I updated to last version of sdk and followed instruction from official documentation:
https://github.com/heremaps/here-android-sdk-examples/tree/master/turn-by-turn-navigation/app/src/main/java/com/here/android/example/guidance

I implemented on my project in activity but i need this to work on fragment as before.

i replace everything to AndroidX:

from Activity works

import androidx.appcompat.app.AppCompatActivity;

public MapFragmentView(AppCompatActivity activity) {
   m_activity = activity;
   initMapFragment();
   initNaviControlButton();
}

private AndroidXMapFragment getMapFragment() {
    return (AndroidXMapFragment) m_activity.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}

Calling this from Activity works

MapFragmentView mapFragmentView = new MapFragmentView (this);

When i call this from Fragment

MapFragmentView mapFragmentView = new MapFragmentView (getActivity ());

This does not accept getActivity() because is not compatible.
androidx.appcompat.app.AppCompatActivity in MapFragmentView can not be applied to androidx.fragment.app.ragmentActivity

I try to cast it and it accepts

AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity ();
MapFragmentView mapFragmentView = new MapFragmentView (appCompatActivity);

But now the method getMapFragment() return null

private AndroidXMapFragment getMapFragment() {
    /* this returns null */ return (AndroidXMapFragment) m_activity.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
}

Here is fragment class, i removed other code to just simplify

package com.example.Fragments;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.drivosity.drivosity.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

public class FragmentHome extends Fragment {

    private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
    private static final String[] RUNTIME_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE
    };
    private final String TAG = "FragmentHome";
    private View view;
    // Directions

    public FragmentHome() {
        // Required empty public constructor
    }

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate (R.layout.fragment_home, container, false);

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated (view, savedInstanceState);

        if (hasPermissions(getActivity (), RUNTIME_PERMISSIONS)) {
            setupMapFragmentView();
        } else {
            ActivityCompat
                    .requestPermissions(getActivity (), RUNTIME_PERMISSIONS, REQUEST_CODE_ASK_PERMISSIONS);
        }
    }

    /**
     * Only when the app's target SDK is 23 or higher, it requests each dangerous permissions it
     * needs when the app is running.
     */
    private static boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS: {
                for (int index = 0; index < permissions.length; index++) {
                    if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {

                        /*
                         * If the user turned down the permission request in the past and chose the
                         * Don't ask again option in the permission request system dialog.
                         */
                        if (!ActivityCompat
                                .shouldShowRequestPermissionRationale(getActivity (), permissions[index])) {
//                            Toast.makeText(this, "Required permission " + permissions[index]
//                                            + " not granted. "
//                                            + "Please go to settings and turn on for sample app",
//                                    Toast.LENGTH_LONG).show();
                        } else {
//                            Toast.makeText(this, "Required permission " + permissions[index]
//                                    + " not granted", Toast.LENGTH_LONG).show();
                        }
                    }
                }

                setupMapFragmentView();
                break;
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    private void setupMapFragmentView() {
        // All permission requests are being handled. Create map fragment view. Please note
        // the HERE Mobile SDK requires all permissions defined above to operate properly.
        AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity ();
        MapFragmentView mapFragmentView = new MapFragmentView (appCompatActivity);

    }

    public interface OnFragmentInteractionListener {
    }
}

Layout of Framgnet

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:mapbox="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/homeToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/AppTheme"
        app:popupTheme="@style/AppTheme"
        android:visibility="gone">

        <RelativeLayout
            android:id="@+id/homeToolbarItems"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible">

            <TextView
                android:id="@+id/appTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Home"
                android:textAlignment="center"
                android:textColor="@color/color_white"
                android:textSize="20sp"
                android:textStyle="bold" />

        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>

    <fragment
        class="com.here.android.mpa.mapping.AndroidXMapFragment"
        android:id="@+id/mapfragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Body:
I figured it out. Here is if anyone have troubles implementing it from Fragment.

But this is with SupportMapFragment, also works with AndroidXMapFragment

public class FragmentHome extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate (R.layout.fragment_home, container, false);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager ().findFragmentById (R.id.mapFragment);
        MapFragmentView fragmentMap = new MapFragmentView ((AppCompatActivity) getActivity (), mapFragment);

        return view;
    }
}

In MapFragmentView constructor i have added one more parameter for SupportMapFragment

public class MapFragmentView {

    private AppCompatActivity m_activity;
    private SupportMapFragment mapFragment;

    public MapFragmentView(AppCompatActivity activity, SupportMapFragment mapFragment) {
        m_activity = activity;
        this.mapFragment = mapFragment;
        initialize (); // This is init map
    }
}


来源: stackexchange

问:
Vuetify: Hide a skeleton loader after a element loads
I've been trying to create a simple skeleton loader in Vuetify that is shown while the document's resources (like images) are being loaded and then hidden (replaced with a <v-card>) when everything is fully loaded.

Currently, I have this <v-skeleton-loader>:

```<code><v-skeleton-loader v-if="loading == true" :loading="loading" transition="fade-transition" type="card">
</v-skeleton-loader>
</code>```

My v-card element uses v-show like this:

```<code><v-card max-width="344" v-show="loaded">
</code>```

For reactive properties, I have:

```<code>data: () => ({
    loading: true,
    loaded: false
})
</code>```

I am trying to update the values of those properties using the updated lifecycle hook of Vue.js:

```<code>updated: function() {
    if (document.readyState == 'complete') {
        this.loading = false;
        this.loaded = true;
    }

}
</code>```

Currently, Vue Devtools tells me that the properties are not being updated with their new values, defined in the updated hook. How can I change that so the values are properly updated when the readyState of the DOM has changed to complete?

答:
updated hook is called only when a component is updated. Vue lifecycle isn't tied to DOM events. If there were no updates after page load, updated won't be triggered.

This can be done with regular DOM event listener:

```<code>created() {
  const readyHandler = () => {
    if (document.readyState == 'complete') {
        this.loading = false;
        this.loaded = true;
        document.removeEventListener('readystatechange', readyHandler);
    }
  };

  document.addEventListener('readystatechange', readyHandler);

  readyHandler(); // in case the component has been instantiated lately after loading
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to create a simple skeleton loader in Vuetify that is shown while the document's resources (like images) are being loaded and then hidden (replaced with a <v-card>) when everything is fully loaded.

Currently, I have this <v-skeleton-loader>:

<v-skeleton-loader v-if="loading == true" :loading="loading" transition="fade-transition" type="card">
</v-skeleton-loader>

My v-card element uses v-show like this:

<v-card max-width="344" v-show="loaded">

For reactive properties, I have:

data: () => ({
    loading: true,
    loaded: false
})

I am trying to update the values of those properties using the updated lifecycle hook of Vue.js:

updated: function() {
    if (document.readyState == 'complete') {
        this.loading = false;
        this.loaded = true;
    }

}

Currently, Vue Devtools tells me that the properties are not being updated with their new values, defined in the updated hook. How can I change that so the values are properly updated when the readyState of the DOM has changed to complete?

Body:
updated hook is called only when a component is updated. Vue lifecycle isn't tied to DOM events. If there were no updates after page load, updated won't be triggered.

This can be done with regular DOM event listener:

created() {
  const readyHandler = () => {
    if (document.readyState == 'complete') {
        this.loading = false;
        this.loaded = true;
        document.removeEventListener('readystatechange', readyHandler);
    }
  };

  document.addEventListener('readystatechange', readyHandler);

  readyHandler(); // in case the component has been instantiated lately after loading
}


问:
Facing issue in handling date picker in iOS App while automation of ios application

Facing issue in handling date picker in iOS App while automation of ios application.

Date picker is always showing current date. So, It changes everday.

Date format is MMM DD, YYYY

As it change on daily basis its hard to automate it with rolling measurement.

Code

```<code>List<WebElement> dateValue = driver.findElementsByClassName("XCUIElementTypePickerWheel");

for (int i = 0; i < dateValue.size(); i++) {
    System.out.println(dateValue.get(i).getText());
}

dateValue.get(0).sendKeys("23");
dateValue.get(0).sendKeys(Keys.TAB);

dateValue.get(1).sendKeys("December");
dateValue.get(1).sendKeys(Keys.TAB);

dateValue.get(2).sendKeys("2000");
dateValue.get(2).sendKeys(Keys.TAB);
</code>```

答:
Appium provides mobile: method called selectPickerWheelValue that can be used for navigating a picker wheel using forward-and-back gestures:

```<code>HashMap<String, Object> params = new HashMap<>();
params.put("order", "next");
params.put("offset", 0.15);
params.put("element", ((RemoteWebElement) pickerWheelElement).getId());
driver.executeScript("mobile: selectPickerWheelValue", params);
</code>```

This approach is more robust to select values. You can check the full example here

Body:
Facing issue in handling date picker in iOS App while automation of ios application.

Date picker is always showing current date. So, It changes everday.

Date format is MMM DD, YYYY

As it change on daily basis its hard to automate it with rolling measurement.

Code

List<WebElement> dateValue = driver.findElementsByClassName("XCUIElementTypePickerWheel");

for (int i = 0; i < dateValue.size(); i++) {
    System.out.println(dateValue.get(i).getText());
}

dateValue.get(0).sendKeys("23");
dateValue.get(0).sendKeys(Keys.TAB);

dateValue.get(1).sendKeys("December");
dateValue.get(1).sendKeys(Keys.TAB);

dateValue.get(2).sendKeys("2000");
dateValue.get(2).sendKeys(Keys.TAB);

Body:
Appium provides mobile: method called selectPickerWheelValue that can be used for navigating a picker wheel using forward-and-back gestures:

HashMap<String, Object> params = new HashMap<>();
params.put("order", "next");
params.put("offset", 0.15);
params.put("element", ((RemoteWebElement) pickerWheelElement).getId());
driver.executeScript("mobile: selectPickerWheelValue", params);

This approach is more robust to select values. You can check the full example here


问:
Autoindent in vim always empty the line if there are only whitespace in it, can I change that?
For example I usually type paired braces first then move the cursor inside the block, what I expect should be like this:

```<code>....{
....█
....}
</code>```

But vim automatically empty the second line since there are only whitespace characters in it, so the result coming out is like this:

```<code>....{
█
....}
</code>```

How do I fix this?

(The dots are for space characters, and █ shows the location of my cursor.)

答:
Don't worry about the fact that Vim strips spaces from an otherwise empty line when you leave insert mode. As others here have commented, this is a good thing. Instead, look for a way to automatically restore the indentation level when you invoke insert mode on that line.

The i, I, a and A commands all preserve the cursor position when putting you into insert mode. But check the documentation for :help cc:

```<code>["x]cc    Delete [count] lines [into register x] and start
          insert linewise. If 'autoindent' is on, preserve
          the indent of the first line.
</code>```

If the autoindent option is on, then running cc on the blank line will switch to insert mode and restore the appropriate level of indentation, setting you up just as you want:

```<code>....{
    |
....}
</code>```

Note that the S key is a synonym for cc (:help S).

ContentLicense: CC BY-SA 3.0

Body:
For example I usually type paired braces first then move the cursor inside the block, what I expect should be like this:

....{
....█
....}

But vim automatically empty the second line since there are only whitespace characters in it, so the result coming out is like this:

....{
█
....}

How do I fix this?

(The dots are for space characters, and █ shows the location of my cursor.)

Body:
Don't worry about the fact that Vim strips spaces from an otherwise empty line when you leave insert mode. As others here have commented, this is a good thing. Instead, look for a way to automatically restore the indentation level when you invoke insert mode on that line.

The i, I, a and A commands all preserve the cursor position when putting you into insert mode. But check the documentation for :help cc:

["x]cc    Delete [count] lines [into register x] and start
          insert linewise. If 'autoindent' is on, preserve
          the indent of the first line.

If the autoindent option is on, then running cc on the blank line will switch to insert mode and restore the appropriate level of indentation, setting you up just as you want:

....{
    |
....}

Note that the S key is a synonym for cc (:help S).


问:
How to randomly pick number of 2 numbers. p5js
I think it is a very simple question, but I can't find an answer. How to randomly pick one number out of 2 numbers. In my situation, I need to pick numbers {-2, 2}. Just one out of these two numbers.</p>

答:
You can pass an array of items into random() if you need to randomly choose from a predetermined set.

In your case, the following code will always pick (-2 or 2), nothing else or anything in-between.

```<code>random([-2, 2]);
</code>```

You can read more about the random function here https://p5js.org/reference/#/p5/random

Body:
You can pass an array of items into random() if you need to randomly choose from a predetermined set.

In your case, the following code will always pick (-2 or 2), nothing else or anything in-between.

random([-2, 2]);

You can read more about the random function here https://p5js.org/reference/#/p5/random


问:
Reload carousel after AJAX call in Vue.js
I have a carousel component in my page in which data is loaded via AJAX call to server. this part is OKAY but when the carousel items append to carousel, it wrecks. So I need to re-render the carousel after AJAX success. Does anybody have any idea? I have searched a lot but couldn't find anything for vue.js.

My code:

```<code><carousel class="original-carousel" :dots="false" :nav="false">
                            <router-link class="product-item" to="/product" v-for="product in originalGames">
                                <div class="image-holder">
                                    <img v-bind:src="product.thumbnail_url" v-bind:alt="product.name">
                                    <div class="product-info">
                                        <div class="product-platform">
                                            origin
                                            <img src="/src/assets/imgs/platform/origin-color.svg" >
                                        </div>
                                        <div class="product-region">
                                            US
                                        </div>
                                    </div>
                                </div>
                                <h2 class="product-title">{{product.name}}</h2>
                                <div class="product-bottom">
                                    <div class="product-card-price">
                                        <div class="original-price__holder" >
                                            <span class="sale-range" v-if="product.sale_percent !== false">%{{product.sale_percent}}</span>
                                            <span class="original-price" v-if="product.sale_percent !== false"> {{product.regular_price}}</span>
                                        </div>
                                        <span class="sale-price">{{product.price}}</span>
                                    </div>
                                    <button class="add-to-cart btn btn--circle btn--transparent">+</button>
                                </div>
                            </router-link>
                        </carousel>

export default {
    name: "homePage",
    components: {searchBar, topNav, siteFooter, carousel},
    data(){
        return {
            sliderProducts: [],
            originalGames: [],
            todayHots: [],
        }
    },
    created: function () {
        let th = this;
        axios.get('myAPIUrl').then((response) => {
            th.originalGames = response.data[2].items;
            th.todayHots = response.data[2].items_hot;
        })
    }

}
</code>```

答:
Simply add a key attribute to your carousel component and then change its value after each AJAX call - this will make Vue to re-render the component:

```<code><carousel :key="refresh" ...>
...
</carousel>

<script>
export default
{
  data()
  {
    return {
      refresh: 0,
      ...
    };
  },
  created()
  {
    axios.get('myAPIUrl').then((response) => {
            this.originalGames = response.data[2].items;
            this.todayHots = response.data[2].items_hot;
            this.refresh++;
        });
  }
</code>```

Body:
I have a carousel component in my page in which data is loaded via AJAX call to server. this part is OKAY but when the carousel items append to carousel, it wrecks. So I need to re-render the carousel after AJAX success. Does anybody have any idea? I have searched a lot but couldn't find anything for vue.js.

My code:

<carousel class="original-carousel" :dots="false" :nav="false">
                            <router-link class="product-item" to="/product" v-for="product in originalGames">

                                            origin

                                            US

{{product.name}}

                                            %{{product.sale_percent}}
                                             {{product.regular_price}}

                                        {{product.price}}

                                    <button class="add-to-cart btn btn--circle btn--transparent">+</button>

                            </router-link>
                        </carousel>

export default {
    name: "homePage",
    components: {searchBar, topNav, siteFooter, carousel},
    data(){
        return {
            sliderProducts: [],
            originalGames: [],
            todayHots: [],
        }
    },
    created: function () {
        let th = this;
        axios.get('myAPIUrl').then((response) => {
            th.originalGames = response.data[2].items;
            th.todayHots = response.data[2].items_hot;
        })
    }

}

Body:
Simply add a key attribute to your carousel component and then change its value after each AJAX call - this will make Vue to re-render the component:

<carousel :key="refresh" ...>
...
</carousel>

<script>
export default
{
  data()
  {
    return {
      refresh: 0,
      ...
    };
  },
  created()
  {
    axios.get('myAPIUrl').then((response) => {
            this.originalGames = response.data[2].items;
            this.todayHots = response.data[2].items_hot;
            this.refresh++;
        });
  }


问:
How to handle Empty 'DataFrame': no numeric data to plot error to take string on the graphs
                                          I am working on something like below for my project;

```<code>df =pd.DataFrame ({City: ['London', ‘Jakarta’, 'Newyork', 'Mumbai'],
‘Staff’: ['1000','2000','3000','4000']})
print (df.head())
df.plot(kind='line',x=’City’,y=’Staff’,color='red')
plt.show()
</code>```

for this code I am getting an error as
TypeError: Empty 'DataFrame': no numeric data to plot.

Then I add below snippet:

```<code>df.Staff=pd.to_numeric(df.Staff)
</code>```

but getting same error.
Is there no way to take string on graph?
OR do I need to redefine as;

```<code>x = ['London', ‘Jakarta’, 'Newyork', 'Mumbai']
y = ['1000','2000','3000','4000']
</code>```

I checked for previous solutions but it is not looking something

答:
Your error is due to incorrect data format you're entering. See an example below (note the Staff column, numeric, not a string as you enter):

```<code>df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': [1000,2000,3000,4000]})
df.plot(kind='line',x='City', y='Staff', color= 'red')
</code>```

Should you still want to enter your numeric data as strings the following will help you:

```<code>df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = df['Staff'].astype("int") # astype("float")
df.plot(kind='line',x='City', y='Staff', color= 'red')
</code>```

or even:

```<code>df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = pd.to_numeric(df['Staff'])
df.plot(kind='line',x='City', y='Staff', color= 'red')
</code>```

Body:
                                          I am working on something like below for my project;

df =pd.DataFrame ({City: ['London', ‘Jakarta’, 'Newyork', 'Mumbai'],
‘Staff’: ['1000','2000','3000','4000']})
print (df.head())
df.plot(kind='line',x=’City’,y=’Staff’,color='red')
plt.show()

for this code I am getting an error as
TypeError: Empty 'DataFrame': no numeric data to plot.

Then I add below snippet:

df.Staff=pd.to_numeric(df.Staff)

but getting same error.
Is there no way to take string on graph?
OR do I need to redefine as;

x = ['London', ‘Jakarta’, 'Newyork', 'Mumbai']
y = ['1000','2000','3000','4000']

I checked for previous solutions but it is not looking something

Body:
Your error is due to incorrect data format you're entering. See an example below (note the Staff column, numeric, not a string as you enter):

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': [1000,2000,3000,4000]})
df.plot(kind='line',x='City', y='Staff', color= 'red')

Should you still want to enter your numeric data as strings the following will help you:

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = df['Staff'].astype("int") # astype("float")
df.plot(kind='line',x='City', y='Staff', color= 'red')

or even:

df =pd.DataFrame ({'City': ['London', 'Jakarta', 'Newyork', 'Mumbai'],
                   'Staff': ['1000','2000','3000','4000']})

df['Staff'] = pd.to_numeric(df['Staff'])
df.plot(kind='line',x='City', y='Staff', color= 'red')


问:
Compiling gcc with debug flags
I am trying to build gcc version 10.00.1 from source with debugging flags to enable some functions such as methods from the STL to be able to print in GDB. Right now GDB will say things such as "cannot find method std::stringstream::str" even when I have the -g3 flag on when compiling my program.

The documentation of gcc says to configure the application using the --enable-libstdcxx-debug flag to be able to enable this support. I decided to build the application with the same flags my distro configured gcc with which are

-v --with-pkgversion='Debian 9.2.1-28' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,c++,go,brig,d,fortran,objc,obj-c++ --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-mutex

after a successful make and make install I still have the same problem with GDB not finding the methods. I decided to build libstdc++ by itself with just the --enable-libstdc++-debug flag. But I cannot find where the libstdc++.so.6 file anywhere in the build. I have not ran a make install yet either as I do not want to break my system. Where should the libstdc++.so.6 be located in the build? Thanks

答:
I have not ran a make install yet either as I do not want to break my system.

Use --prefix option to configure to specify an alternative install location to avoid replacing your system gcc.

I decided to build libstdc++ by itself with just the --enable-libstdc++-debug flag.

Make sure you make clean after re-configure, so that make rebuilds it with the new compiler and linker flags.

Title: Compiling gcc with debug flags


问:
CSS - IE7 ignoring margin on first list item?
If you go to the first blog item (Mona) and expand it using the '+' icon. The image thumbnails are aligned 24px from the left using a margin. This works in every browser but IE7 which ignores the margin on the first list item.

http://www.dririser.co.uk/index.php

CSS

```<code>.artistMeta li {
float: left;
margin: 0 0 24px 24px;
position: relative;
width: 160px;
}
</code>```

There is a similar question on here but the there was no real answer and I can't use their solution.

Why is ie7 ignoring the left-margin on my first list item (only)?

Any ideas?

答:
just a quick test.. not sure if it will work.. but try adding a display:block on your li and don't use the shorthand for the margin, instead use margin-left and margin-bottom...
it seems to me that IE is not refreshing the style of the elements, because when i inspect the elements, the navigator adds the correct margins...

If that doesn't work.. you might want to put the style inside the tag (since you're using JS to add the images), i know it's not elegant, but i guess that could force the navigator to set the style on the li

and if that doesn't work.. then i've no idea what could be wrong =P. I hope this helps...

Good Luck!

Body:
If you go to the first blog item (Mona) and expand it using the '+' icon. The image thumbnails are aligned 24px from the left using a margin. This works in every browser but IE7 which ignores the margin on the first list item.

http://www.dririser.co.uk/index.php

CSS

.artistMeta li {
float: left;
margin: 0 0 24px 24px;
position: relative;
width: 160px;
}

There is a similar question on here but the there was no real answer and I can't use their solution.

Why is ie7 ignoring the left-margin on my first list item (only)?

Any ideas?


答:
Perhaps dateutil.rrule fits your needs. You can define a rule to generate all the datetimes you need, for example:

```<code>dstart=datetime.datetime(2001,1,1)
for a in rrule(YEARLY, dtstart=dstart, interval=5, count=5):
    print(a)
</code>```

Grouping datetimes in pairs is left as an exercise to the reader ;-)

Title: From two dates and frequency get daterange list

Body:
I have two dates:

'1990-01-01'

'2020-02-18'

I would want to convert them in a date range list of as maximum, 25 years:

[ ['1990-01-01', '2015-01-01'], ['2015-01-01', '2020-02-18'] ]

Or as maximun, 5 years:

[ ['1990-01-01', 1995-01-01'], [1995-01-01', '2000-01-01'], ['2000-01-01', '2005-01-01'], ['2005-01-01', '2010-01-01'], ['2010-01-01', '2015-01-01'], ['2015-01-01', '2020-01-01'], ['2020-01-01', '2020-02-18'] ]

I tried with pandas.interval_range with no success.

Body:
Perhaps dateutil.rrule fits your needs. You can define a rule to generate all the datetimes you need, for example:

dstart=datetime.datetime(2001,1,1)
for a in rrule(YEARLY, dtstart=dstart, interval=5, count=5):
    print(a)

Grouping datetimes in pairs is left as an exercise to the reader ;-)


问:
DataGridView sorting on column header click when sort mode set to not sortable
I have a DataGridView that has all columns sort mode set to not sortable. However, when I click on the column header. It changes the order? How can I prevent this? My DGV is unbound and virtual mode is set to true if that makes any difference?</p>

答:
You may overwrite:

```<code>private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
</code>```

more You can find here:

Body:
You may overwrite:

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)

more You can find here:


问:
I have the alias of my keystore, but not the password
I've started working on an app after another developer which left.
When i try to build the app i'm facing

```<code>> Task :app:packageReleaseBundle FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:packageReleaseBundle'.
> java.util.concurrent.ExecutionException: java.lang.RuntimeException: jarsignerfailed with     exit code 1 :
  jarsigner error: java.lang.RuntimeException: keystore load: Keystore was tampered with, or password was incorrect
</code>```

I have the keystore file, i have the alias, but i don't have the storePassword and keyPassword, even if i've been told they're the same

Do i have any way to fix this or is it a lost cause ?

Louis

答:
Password makes sure you're the app owner, not any other who has keystore to prevent harming the app.

If you cannot correct the storePassword & keyPassword, you won't able to sign it and upload with the same package name on Play Store.

Body:
I've started working on an app after another developer which left.
When i try to build the app i'm facing

> Task :app:packageReleaseBundle FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:packageReleaseBundle'.
> java.util.concurrent.ExecutionException: java.lang.RuntimeException: jarsignerfailed with     exit code 1 :
  jarsigner error: java.lang.RuntimeException: keystore load: Keystore was tampered with, or password was incorrect

I have the keystore file, i have the alias, but i don't have the storePassword and keyPassword, even if i've been told they're the same

Do i have any way to fix this or is it a lost cause ?

Louis


Title: How can I get my time strings in a right format?

Body:
I am stuck with converting strings to times. I am aware that there are many topics on Stack regarding converting strings-to-times, however I couldn't fix this problem with the solutions.

Situation
I have a file with times like this:

> dput(df$Time[1:50])
c("1744.3", "2327.54", "1718.51", "2312.3200000000002", "1414.16",
"2046.15", "1442.5", "1912.22", "2303.2199999999998", "2146.3200000000002",
"1459.02", "1930.15", "1856.23", "2319.15", "1451.05", "25.460000000000036",
"1453.25", "2309.02", "2342.48", "2322.5300000000002", "2101.5",
"2026.07", "1245.04", "1945.15", "5.4099999999998545", "1039.5",
"1731.37", "2058.41", "2030.36", "1814.31", "1338.18", "1858.33",
"1731.36", "2343.38", "1733.27", "2304.59", "1309.47", "1916.11",
"1958.3", "1929.54", "1756.4", "1744.23", "1731.26", "1844.47",
"1353.25", "1958.3", "1746.44", "1857.53", "2047.15", "2327.2199999999998", "1915"
)

In this example, the times should be like this:

"1744.3"   = 17:44:30
"2327.54"  = 23:27:54
"1718.51"  = 17:18:51
"2312.3200000000002" = 23:12:32
...
"25.460000000000036" = 00:25:46 # as you can see, the first two 00 are missing.

"1915" = 19:15:00

However, I tried multiple things (and now I am even stuck with str_replace()). Hopefully some one knows how I can transform this.

What have I tried?

format(df$Time, "%H%M.%S") # Yes I know...

# So therefore I thought, lets replace the strings to get them in a proper format
# like HH:MM:SS. First step was to replace the "." for a ":"

str_replace("." , ":", df$Time) # this was leading to "." (don't know why)

And that was the point that I was so frustrated that I posted it on Stack. Hope that you guys can help me.

Many thanks in advance!

Body:
a data.table way

First, convert your strings in your vector to numeric, multiply by 100 (to get the relevant part of HMS before the decimal separator) and set to integer. Then use sprintf() to add leading zero's to get a 6-digit string. Finally, convert to time.

data.table::as.ITime( sprintf( "%06d",
                               as.integer( as.numeric(time) * 100 ) ),
                      format = "%H%M%S" )

# [1] "17:44:30" "23:27:54" "17:18:51" "23:12:32" "14:14:16" "20:46:15" "14:42:50" "19:12:22" "23:03:21" "21:46:32" "14:59:02" "19:30:15"
# [13] "18:56:23" "23:19:15" "14:51:05" "00:25:46" "14:53:25" "23:09:02" "23:42:48" "23:22:53" "21:01:50" "20:26:07" "12:45:04" "19:45:15"
# [25] "00:05:40" "10:39:50" "17:31:37" "20:58:41" "20:30:36" "18:14:31" "13:38:18" "18:58:33" "17:31:36" "23:43:38" "17:33:27" "23:04:59"
# [37] "13:09:47" "19:16:11" "19:58:30" "19:29:54" "17:56:40" "17:44:23" "17:31:26" "18:44:47" "13:53:25" "19:58:30" "17:46:44" "18:57:53"
# [49] "20:47:15" "23:27:21"


问:
Regex for positive float numbers
For example:

10

0.1

1.23234

123.123

0.000001

1.000

.3

And wrong examples:

0001.2

-12

-1.01

+2.3

EDIT: standart JavaScript regex.

答:
Try this here

```<code>^(?:[1-9]\d*|0)?(?:\.\d+)?$
</code>```

See it here online on Regexr

If matching the empty string is not wanted, then you can add a length check to your regex like

```<code>^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$
</code>```

The positive lookahead (?=.+) ensures that there is at least 1 character

Title: Regex for positive float numbers

Body:
Try this here

^(?:[1-9]\d*|0)?(?:\.\d+)?$

See it here online on Regexr

If matching the empty string is not wanted, then you can add a length check to your regex like

^(?=.+)(?:[1-9]\d*|0)?(?:\.\d+)?$

The positive lookahead (?=.+) ensures that there is at least 1 character


问:
How do I return to previous state in reactjs?
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written</p>

```<code>class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (
      <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" />
      <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
        <span onClick={this.hideMenu} className="float-right font-weight-bold hide-big close">X</span>
      </div>
      </span>

    </div>

    <div className="co">
    {/* <a href=""><Logo className="logo" /></a> */}
    <a href=""><img className="img-fluid logo" src={Logo} alt="losode logo"/></a>
    </div>

    <div className="co pt-4">
    <span className="hide-small"><SearchInput /></span>
    <div className="icon-mobile hide-big">
      <ul className="flex-icon sub-flex-container">
        <li><ion-icon name="search-outline"></ion-icon></li>
        <li><ion-icon name="person-outline"></ion-icon></li>
      <li><ion-icon name="basket-outline"></ion-icon></li>
      </ul>
    </div>
    </div>

    </div>
    );
  }
};

export default SubMainNavbar
</code>```

答:
You didn't close your tags properly. update your code as per below:

```<code>  <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" /></span>
      <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
        <span onClick={this.hideMenu} className="float-right font-weight-bold hide-big close">X</span>
      </div>
      </div>

    <div className="co">
...
</code>```

Body:
I have created a sidebar component and set its state to false to hide the block until a user clicks on the hanmburger icon, then the state is shown. However I am trying to return(or close the sidebar menu) when the user clicks on the close 'X' icon. I have written a hideMenu method to return the state to false however it doesnt work, and there are no errors.
 Here is what I have written

class SubMainNavbar extends React.Component{
  constructor(){
    super();
    this.state = {isShown:false}
    this.showMenu = this.showMenu.bind(this)
    this.hideMenu = this.hideMenu.bind(this)
  }

  showMenu(){
    this.setState({isShown: true})
  }

  hideMenu(){
   this.setState({isShown: false})
  }
  render() {
    return (

women

mens

health & beauty

      <Icon type="menu" />

        X

    {/* <Logo className="logo" /> */}

    <SearchInput />

<ion-icon name="search-outline"></ion-icon>

<ion-icon name="person-outline"></ion-icon>

<ion-icon name="basket-outline"></ion-icon>

    );
  }
};

export default SubMainNavbar

Body:
You didn't close your tags properly. update your code as per below:

  <div className="sub-flex-container">
        <div className="co pt-4">
      <ul className="flex-container sub-list">
        <li>women</li>
        <li>mens</li>
        <li>health & beauty</li>
      </ul>
      <span onClick={this.showMenu} className="pl-3 hamburger hide-big pb-4"><Icon type="menu" /></span>
      <div className="mobile-menu-display" id="mySidebar" style={{display: this.state.isShown ? 'block' : 'none' }}>
        <span onClick={this.hideMenu} className="float-right font-weight-bold hide-big close">X</span>
      </div>
      </div>

    <div className="co">
...


问:
Powershell Set-MpPreference -DisableRealtimeMonitoring $true not working
To disable the Windows Defender, I am using the PowerShell (as an administrator) in Windows 10 to run the following command:
 Set-MpPreference -DisableRealtimeMonitoring $true

But the real time protection is not getting disabled.

Can anyone have any idea about how to disable the real time protection programmatically?

答: Tamper Protection (when enabled) prevents "Set-MpPreference -DisableRealtimeMonitoring $true" from doing anything.</p>


问:
How to prevent events from acting in nested divs when using React Hooks
I have nested div elements. Outside there should be events to move and to click. I want to enable a nested element to act as a button and to prevent the event from outside to act. In the example when we click on the red part, both events are happening. How can I stop the event from the green part when we click on the red part? stopPropagation() did not do the job. I am using React and my structure is more complex than in the example. But I wanted to reduce for reasons of clarity.

I would be happy if someone can help.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <div id="bigCircle">
    <div id="smallCircle"></div>
  </div>

  <script>
  document.getElementById("bigCircle").addEventListener("click",myBigCircle);

    document.getElementById("smallCircle").addEventListener("click",mySmallCircle);

  function myBigCircle(){
  console.log("Hello");}

    function mySmallCircle(){
  console.log("Bye");}
  </script>
</body>

</html></code>```

I think it is related to React Hooks. Here you see the example with stopPropagation not working:

```<code>import React, { useState } from 'react';

function Test() {
    let [test, setTest] = useState(false);

    return (
        <div id="wrapper"
            style={styleBigCircle}
            onMouseUp={() => {
                setTest(false);
                console.log("Hello", test)
            }
            }>

            <div id="center"
                style={styleSmallCircle}
                onClick={(e) => {
                    e.stopPropagation();
                    setTest(!test);
                    console.log("Bye", test)
                }}
            >

            </div>

        </div>

    );
}

const styleBigCircle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "180px",
    height: "180px",
    borderRadius: "50%",
    backgroundColor: "green"
}

const styleSmallCircle = {
    width: "40px",
    height: "40px",
    borderRadius: "50%",
    backgroundColor: "red"
}

export default Test;
</code>```

I would be happy if someone knows how to fix this.

答:
Use event.stopPropagation() to prevent parent trigger.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <div id="bigCircle">
    <div id="smallCircle"></div>
  </div>

  <script>
  document.getElementById("bigCircle").addEventListener("click",myBigCircle);

    document.getElementById("smallCircle").addEventListener("click",mySmallCircle);

  function myBigCircle(){
  console.log("Hello");}

    function mySmallCircle(event){
     event.stopPropagation()
     console.log("Bye");
   }
  </script>
</body>

</html></code>```

Body:
I have nested div elements. Outside there should be events to move and to click. I want to enable a nested element to act as a button and to prevent the event from outside to act. In the example when we click on the red part, both events are happening. How can I stop the event from the green part when we click on the red part? stopPropagation() did not do the job. I am using React and my structure is more complex than in the example. But I wanted to reduce for reasons of clarity.

I would be happy if someone can help.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}

<!DOCTYPE html>

I think it is related to React Hooks. Here you see the example with stopPropagation not working:

import React, { useState } from 'react';

function Test() {
    let [test, setTest] = useState(false);

    return (

 {
                setTest(false);
                console.log("Hello", test)
            }
            }>

 {
                    e.stopPropagation();
                    setTest(!test);
                    console.log("Bye", test)
                }}
            >

    );
}

const styleBigCircle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: "180px",
    height: "180px",
    borderRadius: "50%",
    backgroundColor: "green"
}

const styleSmallCircle = {
    width: "40px",
    height: "40px",
    borderRadius: "50%",
    backgroundColor: "red"
}

export default Test;

I would be happy if someone knows how to fix this.

Body:
Use event.stopPropagation() to prevent parent trigger.

#bigCircle {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 180px;
  height: 180px;
  border-radius: 50%;
  background-color: green;
}

#smallCircle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
}

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
  <div id="bigCircle">
    <div id="smallCircle"></div>
  </div>

  <script>
  document.getElementById("bigCircle").addEventListener("click",myBigCircle);

    document.getElementById("smallCircle").addEventListener("click",mySmallCircle);

  function myBigCircle(){
  console.log("Hello");}

    function mySmallCircle(event){
     event.stopPropagation()
     console.log("Bye");
   }
  </script>
</body>

</html>


问:
Entity Framework - Filtering rows with where() after include
If I have two objects or models as below:

```<code>   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }
</code>```

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

```<code>var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();
</code>```

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.

答:
It does work, but you will need third party libraries - Filtered includes are NOT supported by EntityFramework and i think EF Core (thoug hthere they are iirc on the todo list).

The where clause can filter, but it can only filter out full objects top level, then the includes expand to sub elements.

What you want is include filtered or global query filters (filter out all students that are deleted unless I tell you not to).

https://entityframework-classic.net/ does that (free, a fork of ef)

Body:
If I have two objects or models as below:

   class School
    {
        ICollection<Student> students { get; set; }
    }

    class Student
    {
        string Name { get; set; }
        School school { get; set; }
        bool Deleted { get; set; }
    }

Howcome when trying to get a school with only students that are not deleted doesn't work properly using the where clause?

var school = DatabaseContext.Schools
             .Include(x => x.Students)
             .Where(y => !y.Deleted).FirstOrDefault();

Shouldn't the where clause filter the students that are not deleted? Using where clause inside the include is not allowed too without using any third party libs.


问:
Using Filter and ValidatorAttribute causes System.ArgumentNullException in ctor of ValidationContext
I got an asp webapi project and I want to use a custom validatorattribute to do some special validation in my api. For that purpose I added a filter into my api (nothing special currently):

```<code>public class LogFilter : ActionFilterAttribute
{
    public LogFilter()
    {

    }

    public override void OnActionExecuting(HttpActionContext ActionContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        if (ActionContext.ModelState.IsValid == false)
        {
            ActionContext.Response = ActionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, ActionContext.ModelState);
        }
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
}
</code>```

Next step I did is to create a new ValidatorAttribute called GroupValidatorAttribute (There is currently NO special implementation, it is just a minimal working example for demonstrating my problem):

```<code>[AttributeUsage(AttributeTargets.Class)]
public class GroupValidatorAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            return new ValidationResult("" + validationContext.DisplayName + " cant be null");
        }

        return ValidationResult.Success;
    }
}
</code>```

So and finaly, we need a model-class using the GroupValidator attribute:

```<code>[GroupValidator]
public class Student
{
    public int? Age { get; set; }
    public string name { get; set; }
}
</code>```

For sure there is also a controller, which has an endpoint with type post, which should get an object of class student (my model) from the body:

```<code>    [HttpPost]
    [Route("Body")]
    public HttpResponseMessage BodyTest(int id, [FromBody] Student student)
    {
        return Request.CreateResponse(HttpStatusCode.OK,
            "Suc");
    }
</code>```

Okay, so far so good. It nearly works as expected, but one case is driving me into madness. If I send (post) an empty body to my endpoint in the api, there occures an System.ArgumentNullException.

This is the full exception:

"ExceptionMessage": "Der Wert darf nicht NULL sein.\r\nParametername: instance",
    "ExceptionType": "System.ArgumentNullException",
    "StackTrace": "   bei System.ComponentModel.DataAnnotations.ValidationContext..ctor(Object instance, IServiceProvider serviceProvider, IDictionary2 items)\r\n   bei System.Web.Http.Validation.Validators.DataAnnotationsModelValidator.Validate(ModelMetadata metadata, Object container)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.ShallowValidate(ModelMetadata metadata, BodyModelValidatorContext validationContext, Object container, IEnumerable1 validators)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, BodyModelValidatorContext validationContext, Object container, IEnumerable`1 validators)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.Validate(Object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, String keyPrefix)\r\n   bei System.Web.Http.ModelBinding.FormatterParameterBinding.d__18.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Controllers.HttpActionBinding.d__12.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()"

In my debugger I can see that the methods in my filter and the methods in my validator are NOT hit. Is anybody who can help me?

答:
The ArgumentNullException("instance") exception is generated from constructor of ValidationContextbecause instance is null in your case.

The code-snippet of constructor of ValidationContext: Source code

```<code>public ValidationContext(object instance, IServiceProvider serviceProvider,
                         IDictionary<object, object> items)
{
    if (instance == null) {
       throw new ArgumentNullException("instance");
    }
    ....
</code>```

Now, to your question : In my debugger I can see that the methods in
  my filter and the methods in my validator are NOT hit.

The call stack is something like

```<code>DataAnnotationsModelValidator.Validate() ->
            DataAnnotations.ValidationAttribute.GetValidationResult() ->
            GroupValidatorAttribute.IsValid()
</code>```

The constructor of ValidationContext is created at Validate() stage (where null exception is raised) but your implementation of IsValid() is called later only after null checking is already performed. Hence, IsValid() is never hit your case.

Body:
I got an asp webapi project and I want to use a custom validatorattribute to do some special validation in my api. For that purpose I added a filter into my api (nothing special currently):

public class LogFilter : ActionFilterAttribute
{
    public LogFilter()
    {

    }

    public override void OnActionExecuting(HttpActionContext ActionContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        if (ActionContext.ModelState.IsValid == false)
        {
            ActionContext.Response = ActionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, ActionContext.ModelState);
        }
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
}

Next step I did is to create a new ValidatorAttribute called GroupValidatorAttribute (There is currently NO special implementation, it is just a minimal working example for demonstrating my problem):

[AttributeUsage(AttributeTargets.Class)]
public class GroupValidatorAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null)
        {
            return new ValidationResult("" + validationContext.DisplayName + " cant be null");
        }

        return ValidationResult.Success;
    }
}

So and finaly, we need a model-class using the GroupValidator attribute:

[GroupValidator]
public class Student
{
    public int? Age { get; set; }
    public string name { get; set; }
}

For sure there is also a controller, which has an endpoint with type post, which should get an object of class student (my model) from the body:

    [HttpPost]
    [Route("Body")]
    public HttpResponseMessage BodyTest(int id, [FromBody] Student student)
    {
        return Request.CreateResponse(HttpStatusCode.OK,
            "Suc");
    }

Okay, so far so good. It nearly works as expected, but one case is driving me into madness. If I send (post) an empty body to my endpoint in the api, there occures an System.ArgumentNullException.

This is the full exception:

"ExceptionMessage": "Der Wert darf nicht NULL sein.\r\nParametername: instance",
    "ExceptionType": "System.ArgumentNullException",
    "StackTrace": "   bei System.ComponentModel.DataAnnotations.ValidationContext..ctor(Object instance, IServiceProvider serviceProvider, IDictionary2 items)\r\n   bei System.Web.Http.Validation.Validators.DataAnnotationsModelValidator.Validate(ModelMetadata metadata, Object container)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.ShallowValidate(ModelMetadata metadata, BodyModelValidatorContext validationContext, Object container, IEnumerable1 validators)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, BodyModelValidatorContext validationContext, Object container, IEnumerable`1 validators)\r\n   bei System.Web.Http.Validation.DefaultBodyModelValidator.Validate(Object model, Type type, ModelMetadataProvider metadataProvider, HttpActionContext actionContext, String keyPrefix)\r\n   bei System.Web.Http.ModelBinding.FormatterParameterBinding.d__18.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Controllers.HttpActionBinding.d__12.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext()\r\n--- Ende der Stapelüberwachung vom vorhergehenden Ort, an dem die Ausnahme ausgelöst wurde ---\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   bei System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()"

In my debugger I can see that the methods in my filter and the methods in my validator are NOT hit. Is anybody who can help me?

Body:
The ArgumentNullException("instance") exception is generated from constructor of ValidationContextbecause instance is null in your case.

The code-snippet of constructor of ValidationContext: Source code

public ValidationContext(object instance, IServiceProvider serviceProvider,
                         IDictionary<object, object> items)
{
    if (instance == null) {
       throw new ArgumentNullException("instance");
    }
    ....

Now, to your question : In my debugger I can see that the methods in
  my filter and the methods in my validator are NOT hit.

The call stack is something like

DataAnnotationsModelValidator.Validate() ->
            DataAnnotations.ValidationAttribute.GetValidationResult() ->
            GroupValidatorAttribute.IsValid()

The constructor of ValidationContext is created at Validate() stage (where null exception is raised) but your implementation of IsValid() is called later only after null checking is already performed. Hence, IsValid() is never hit your case.


问:
XML Element Value Writing as A String Giving IO Error C#
I am trying to hold a log XML file. Code sample at below.

```<code>private class LogFunctionInfo
{
    private string logName;
    public string FunctionName;
    public Type FunctionClassType;
    public int Displayed;
    public int Offset;
    public int Multiplier;

    public string LogName { get => logName; set => logName = value; }
    public override string ToString()
    {
        return logName;
    }
}

private LogFunctionInfo[] LoggingFunctions = {bla bla bla};
loggingNames = LoggingFunctions.Select(a => a.ToString().Replace(" ", "").Clone().ToString()).ToArray();
do
{
    try
    {
        XElement xml = XElement.Load(xmlLogFileName);

        for (int LineCounter = 0; LineCounter < LogBufferCounter; LineCounter++)
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            for (int count = 0; count < LogNumber; count++)
            {
                //dictionary.Add("Value" + count, LogBuffer[LineCounter][count]); // If I use this, its working like a charm.
                dictionary.Add(loggingNames[count], LogBuffer[LineCounter][count]); // If I use this, giving XmlException at System.Xml.dll error
                minute = count == 22 ? LogBuffer[LineCounter][count] : minute;
            }
            xml.Add(new XElement("GraphValues",
                new XAttribute("Time", minute),
                new XElement("Values",
                dictionary.Select(element => new XElement(element.Key, element.Value)))));
            dictionary.Clear();
        }
        xml.Save(xmlLogFileName);
        Flushed = true;
        LogBufferCounter = 0;
    }
    catch
    {
        Flushed = false;
    }
} while (Flushed == false);
</code>```

Its giving System.Xml.Exception when I use a string array that values are coming from an object. What is the difference between fill by hand("Value" + count) with using an filled array?

答:
I removed the try catch block for to take details of exception.
Thanks for asking details to @Cee McSharpface and @Marc Gravell♦

It was about my array you guys are right.
In my array one string is starting with number and it was giving XML error.

Problem solved thanks again.

Body:
I am trying to hold a log XML file. Code sample at below.

private class LogFunctionInfo
{
    private string logName;
    public string FunctionName;
    public Type FunctionClassType;
    public int Displayed;
    public int Offset;
    public int Multiplier;

    public string LogName { get => logName; set => logName = value; }
    public override string ToString()
    {
        return logName;
    }
}

private LogFunctionInfo[] LoggingFunctions = {bla bla bla};
loggingNames = LoggingFunctions.Select(a => a.ToString().Replace(" ", "").Clone().ToString()).ToArray();
do
{
    try
    {
        XElement xml = XElement.Load(xmlLogFileName);

        for (int LineCounter = 0; LineCounter < LogBufferCounter; LineCounter++)
        {
            Dictionary<string, int> dictionary = new Dictionary<string, int>();

            for (int count = 0; count < LogNumber; count++)
            {
                //dictionary.Add("Value" + count, LogBuffer[LineCounter][count]); // If I use this, its working like a charm.
                dictionary.Add(loggingNames[count], LogBuffer[LineCounter][count]); // If I use this, giving XmlException at System.Xml.dll error
                minute = count == 22 ? LogBuffer[LineCounter][count] : minute;
            }
            xml.Add(new XElement("GraphValues",
                new XAttribute("Time", minute),
                new XElement("Values",
                dictionary.Select(element => new XElement(element.Key, element.Value)))));
            dictionary.Clear();
        }
        xml.Save(xmlLogFileName);
        Flushed = true;
        LogBufferCounter = 0;
    }
    catch
    {
        Flushed = false;
    }
} while (Flushed == false);

Its giving System.Xml.Exception when I use a string array that values are coming from an object. What is the difference between fill by hand("Value" + count) with using an filled array?


问:
Interface implementation array and calling extra functions
I have some concept of services in my application
Services interface is defined as follows

```<code>type Service interface {
    // Init and Start the Service
    Start() error
    // Start the Service
    // Stops the Service
    Stop() error
}
</code>```

Implemented couple of type using this interface

```<code>type Service1 struct {
}
func NewService1() *Service1 {
    return &MediaService{}
}
func (m *Service1) Start() error {
}
func (m *Service1) Stop() error {
}
func (m *Service1) Fn1() error {
}
</code>```

and

```<code>type Service2 struct {
    }
    func NewService2() *Service2 {
        return &MediaService{}
    }
    func (m *Service2) Start() error {
    }
    func (m *Service2) Stop() error {
    }
    func (m *Service2) Fn2() error {
    }
</code>```

Storing all the instance in a array

```<code>Services = make([]Service, 2)

    Services[0] = NewService1()
    Services[1] = NewService2()
</code>```

But I cannot call extra function defined in services.

Services[0].Fn1 or Services[1].Fn2

答:
Services = make([]Service, 2) means that you have an array of the interface Service

It doesn't really matter which Service implementations you add as long the implementation fulfills the Service contract, namingly Start() error and Stop() error

When you get a service from that array with:

Services[0]

at compile time this if of the type Service and therefor you can only access all functions of Service.

At runtime, the actual type behind Services[0] is NewService1 or maybe another one  but this doesn't really matter because you specified the Services Array to be of type Service and therefor can only access those functions.

If you really want to call Fn1, you have to make assumptions which actual type is behind the single array fields and cast them:

Services[0].(*Service1).Fn1()

If you want do avoid panics at runtime because of invalid casts (when a different type if actually available as you expect), please have a look here how you make type assertions https://golang.org/ref/spec#Type_assertions

Body:
I have some concept of services in my application
Services interface is defined as follows

type Service interface {
    // Init and Start the Service
    Start() error
    // Start the Service
    // Stops the Service
    Stop() error
}

Implemented couple of type using this interface

type Service1 struct {
}
func NewService1() *Service1 {
    return &MediaService{}
}
func (m *Service1) Start() error {
}
func (m *Service1) Stop() error {
}
func (m *Service1) Fn1() error {
}

and

type Service2 struct {
    }
    func NewService2() *Service2 {
        return &MediaService{}
    }
    func (m *Service2) Start() error {
    }
    func (m *Service2) Stop() error {
    }
    func (m *Service2) Fn2() error {
    }

Storing all the instance in a array

Services = make([]Service, 2)

    Services[0] = NewService1()
    Services[1] = NewService2()

But I cannot call extra function defined in services.

Services[0].Fn1 or Services[1].Fn2


问:
What does a lock statement do under the hood?
I see that for using objects which are not thread safe we wrap the code with a lock like this:

```<code>private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}
</code>```

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

答:
No, they are not queued, they are sleeping

A lock statement of the form

```<code>lock (x) ...
</code>```

where x is an expression of a reference-type, is precisely equivalent to

```<code>var temp = x;
System.Threading.Monitor.Enter(temp);
try { ... }
finally { System.Threading.Monitor.Exit(temp); }
</code>```

You just need to know that they are waiting to each other, and only one thread will enter to lock block, the others will wait...

Monitor is written fully in .net so it is enough fast, also look at  class Monitor with reflector for more details

Body:
I see that for using objects which are not thread safe we wrap the code with a lock like this:

private static readonly Object obj = new Object();

lock (obj)
{
    // thread unsafe code
}

So, what happens when multiple threads access the same code (let's assume that it is running in a ASP.NET web application). Are they queued? If so how long will they wait?

What is the performance impact because of using locks?

Body:
No, they are not queued, they are sleeping

A lock statement of the form

lock (x) ...

where x is an expression of a reference-type, is precisely equivalent to

var temp = x;
System.Threading.Monitor.Enter(temp);
try { ... }
finally { System.Threading.Monitor.Exit(temp); }

You just need to know that they are waiting to each other, and only one thread will enter to lock block, the others will wait...

Monitor is written fully in .net so it is enough fast, also look at  class Monitor with reflector for more details


问:
Brew doctor: dyld: Library not loaded & Error: No available formula for zlib
When I brew doctor I get the following errors:

```<code>dyld: Library not loaded: /usr/lib/libltdl.7.dylib
  Referenced from: /usr/local/bin/php
  Reason: image not found
Error: No available formula for zlib
</code>```

The file libltdl.7.dylib is not in my /usr/lib directory, but there are several other .dylib files.

I'm running 10.8.1 with the latest version of Xcode (4.4.1) and its Command Line Tools installed.

Any idea how to solve these errors?

答:
None of them work I personally reinstalled Watchman like so:</p>

```<code>brew uninstall watchman
brew reinstall watchman
</code>```

Body:
When I brew doctor I get the following errors:

dyld: Library not loaded: /usr/lib/libltdl.7.dylib
  Referenced from: /usr/local/bin/php
  Reason: image not found
Error: No available formula for zlib

The file libltdl.7.dylib is not in my /usr/lib directory, but there are several other .dylib files.

I'm running 10.8.1 with the latest version of Xcode (4.4.1) and its Command Line Tools installed.

Any idea how to solve these errors?

Body:
None of them work I personally reinstalled Watchman like so:

brew uninstall watchman
brew reinstall watchman


问:
How to define custom text theme in flutter?
How to make my own text theme style?
I only find the default text theme like this but it's not enough.

```<code>textTheme: TextTheme(
  body1: TextStyle(),
  body2: TextStyle(),
  button: TextStyle(),
  caption: TextStyle(),
  display1: TextStyle(),
  display2: TextStyle(),
  display3: TextStyle(),
  display4: TextStyle(),
  headline: TextStyle(),
  overline: TextStyle(),
  subhead: TextStyle(),
  subtitle: TextStyle(),
  title: TextStyle(),
),
</code>```

I want for example have a text with line through then some other have underline etc
I was thinking to override the body2 for underline style then how to define another style for line through?

Kind Regards

答:
Since the release of dart 2.7, you can also use an extension method:

```<code>extension CustomStyles on TextTheme {
  TextStyle get error {
    return TextStyle(
      fontSize: 18.0,
      color: Colors.red,
      fontWeight: FontWeight.bold,
    );
  }
}
</code>```

Then you can use it like this:

```<code>Text(error, style: Theme.of(context).textTheme.error)
</code>```

Body:
How to make my own text theme style?
I only find the default text theme like this but it's not enough.

textTheme: TextTheme(
  body1: TextStyle(),
  body2: TextStyle(),
  button: TextStyle(),
  caption: TextStyle(),
  display1: TextStyle(),
  display2: TextStyle(),
  display3: TextStyle(),
  display4: TextStyle(),
  headline: TextStyle(),
  overline: TextStyle(),
  subhead: TextStyle(),
  subtitle: TextStyle(),
  title: TextStyle(),
),

I want for example have a text with line through then some other have underline etc
I was thinking to override the body2 for underline style then how to define another style for line through?

Kind Regards

Body:
Since the release of dart 2.7, you can also use an extension method:

extension CustomStyles on TextTheme {
  TextStyle get error {
    return TextStyle(
      fontSize: 18.0,
      color: Colors.red,
      fontWeight: FontWeight.bold,
    );
  }
}

Then you can use it like this:

Text(error, style: Theme.of(context).textTheme.error)


问:
Get root domain from location.host
There are a lot of SO questions that seem to address variations of this question. But they tend to be complex regex answers and I am hoping I can find something simpler.

Given location.host values of

```<code>foo.mysite.com
app.foo.mysite.com
mysite.com
</code>```

How can I get the root domain mysite.com?

I could do something like finding the second to last ., but this seems ugly and wouldn't work for any TLD's like .co.uk. If jQuery has an object that contains this information I am happy to use it.

My goal is to create cookies that exist across all subdomains. To do this I need to find .mysite.com. I'd prefer not to hardcode it.

答:
I've been using this:

```<code>const rootDomain = s => {
    const r =  /.*\.([^.]*[^0-9][^.]*\.[^.]*[^.0-9][^.]*$)/;
    return s.replace(r, '$1');
};
</code>```

Which is similar in output to the above method using split, reverse etc., but it doesn't modify straight IP addresses.

Title: Get root domain from location.host

Body:
There are a lot of SO questions that seem to address variations of this question. But they tend to be complex regex answers and I am hoping I can find something simpler.

Given location.host values of

foo.mysite.com
app.foo.mysite.com
mysite.com

How can I get the root domain mysite.com?

I could do something like finding the second to last ., but this seems ugly and wouldn't work for any TLD's like .co.uk. If jQuery has an object that contains this information I am happy to use it.

My goal is to create cookies that exist across all subdomains. To do this I need to find .mysite.com. I'd prefer not to hardcode it.

Body:
I've been using this:

const rootDomain = s => {
    const r =  /.*\.([^.]*[^0-9][^.]*\.[^.]*[^.0-9][^.]*$)/;
    return s.replace(r, '$1');
};

Which is similar in output to the above method using split, reverse etc., but it doesn't modify straight IP addresses.


问:
URL join of two URIs
I am trying to join these two URIs

```<code>from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)
</code>```

I am getting

```<code>https:///videofaq
</code>```

How can I get

```<code>https:/\\corrlinks.blob.core.windows.net/videofaq
</code>```

This one would be Ok too:

```<code>https://corrlinks.blob.core.windows.net/videofaq
</code>```

Note. Browsers handle the link above just fine.

答:
I have ended up with </p>

```<code>url = url.replace("\\" , "/").replace("///", "//")
</code>```

Title: URL join of two URIs

Body:
I am trying to join these two URIs

from urllib.parse import urljoin
# baskslash is not a mistake
r = urljoin(r"https:/\\corrlinks.blob.core.windows.net", r"videofaq")
print(r)

I am getting

https:///videofaq

How can I get

https:/\\corrlinks.blob.core.windows.net/videofaq

This one would be Ok too:

https://corrlinks.blob.core.windows.net/videofaq

Note. Browsers handle the link above just fine.

Body:
I have ended up with

url = url.replace("\\" , "/").replace("///", "//")


问:
How can I create a button with image in SwiftUI?
I created a button in SwiftUI with these line of codes:

```<code>Button(action: {
    print("button pressed")
}) {
    Image("marker")
}
</code>```

but marker image automatically changes to blue color.

I want to use original image in button.

this is original marker.png:

but SwiftUI changes it to this:

I remember we have tintColor or something like this in UIButton, but I can't find it in SwiftUI.

答:
SwiftUI

```<code>var body: some View {
      HStack {
           Image(uiImage: UIImage(named: "Login")!)
                .renderingMode(.original)
                .font(.title)
                .foregroundColor(.blue)

           Text("Login")
                .font(.title)
                .foregroundColor(.white)
      }
}
</code>```

Body:
I created a button in SwiftUI with these line of codes:

Button(action: {
    print("button pressed")
}) {
    Image("marker")
}

but marker image automatically changes to blue color.

I want to use original image in button.

this is original marker.png:

but SwiftUI changes it to this:

I remember we have tintColor or something like this in UIButton, but I can't find it in SwiftUI.

Body:
SwiftUI

var body: some View {
      HStack {
           Image(uiImage: UIImage(named: "Login")!)
                .renderingMode(.original)
                .font(.title)
                .foregroundColor(.blue)

           Text("Login")
                .font(.title)
                .foregroundColor(.white)
      }
}


问:
For loop with steps OPL Cplex
I need to write matrices of different dimensions in OPL CPLEX.

Currently, I wrote this for loop :

```<code>{int} row=...;
{int} col=...;
int y[row][col];

execute
{
 for (var i=1; i<=row.size; i+=10){
   for (var j in col){
     y[i][j]=i;
   }
 }
 writeln("y= ",y,
 "/ row = ", row.size,
 "/ col = ", col.size,
 "/ time = ", cplex.getCplexTime());
}
</code>```

Currently, in the scripting log, I obtain as a solution all the matrices (from 1x2 to 100x2).

I would like to compute (and print) only the matrices 1x2, 10x2, 20x2, ..., 90x2 and 100x2.

Essentially I would like to print a matrix every 10 rows (so in total 11 matrices and not 100).

I tried to multiply the row.size per 10 (or divide it per 10 when the row value is 100).

How can I do that ?

UPDATE :

main.mod :

```<code>{int} set1={};
{int} set2={};
int ar[1..100][1..100];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for(var i=1;i<=30;i++) if (i % 10 == 0) {
    for (var j=1; j<=30; j++) if (j % 10 == 0) {
        var opl = new IloOplModel(def,cplex);
        var data2= new IloOplDataElements();
        data2.row=thisOplModel.set1;
        data2.row.add(i);
        data2.col=thisOplModel.set2;
        data2.col.add(j);
    }
  opl.addDataSource(data2);
  opl.generate();
}
if (cplex.solve()) {
writeln("Solution = " + cplex.getObjValue(),
"/ time = ", cplex.getCplexTime());
} else {
    writeln("No solution");
}
data2.end();
opl.end();
}
</code>```

sub.mod :

```<code>{int} row=...;
{int} col=...;
int y[row][col];

execute {

 for (var i in row) {
     for (var j in col) {
        y[i][j]=i;
    }
 }
    writeln("y= ",y,
//    " / i= ", i,
//  "/ row = ", row,
    "/ col = ", col,
    "/ time = ", cplex.getCplexTime());
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}
</code>```

Now, I obtain the right values in row = {10, 20, 30} and col = {10, 20, 30} in the main.mod.

In sub.mod row and col are sets. I need to use those values as matrices dimensions. So the first matrix is 10x10, the second 20x20 etc..

How can I access the values inside the set so that I can create those matrices ?

Sorry for the multiple questions but I am really new to CPLEX.

答:
You can slightly rewrite your sub.mod to get this going:

```<code>{int} rowSet = ...;
{int} colSet = ...;

range row = 1..last(rowSet);
range col = 1..last(colSet);

int y[row][col];

execute {
  for (var i in row) {
    for (var j in col) {
      y[i][j] = i;
    }
  }
  writeln(y);
}
</code>```

The last function will return the last element from the respective set. So in the first iteration you get 10, in the second 20 and in the third 30. Then row and col are constructed as range with the desired number of elements. These can then be used to initialize the array.

Note that in main.mod you must replace data2.row by data2.rowSet and data2.col by data2.colSet.

Title: For loop with steps OPL Cplex

Body:
I need to write matrices of different dimensions in OPL CPLEX.

Currently, I wrote this for loop :

{int} row=...;
{int} col=...;
int y[row][col];

execute
{
 for (var i=1; i<=row.size; i+=10){
   for (var j in col){
     y[i][j]=i;
   }
 }
 writeln("y= ",y,
 "/ row = ", row.size,
 "/ col = ", col.size,
 "/ time = ", cplex.getCplexTime());
}

Currently, in the scripting log, I obtain as a solution all the matrices (from 1x2 to 100x2).

I would like to compute (and print) only the matrices 1x2, 10x2, 20x2, ..., 90x2 and 100x2.

Essentially I would like to print a matrix every 10 rows (so in total 11 matrices and not 100).

I tried to multiply the row.size per 10 (or divide it per 10 when the row value is 100).

How can I do that ?

UPDATE :

main.mod :

{int} set1={};
{int} set2={};
int ar[1..100][1..100];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for(var i=1;i<=30;i++) if (i % 10 == 0) {
    for (var j=1; j<=30; j++) if (j % 10 == 0) {
        var opl = new IloOplModel(def,cplex);
        var data2= new IloOplDataElements();
        data2.row=thisOplModel.set1;
        data2.row.add(i);
        data2.col=thisOplModel.set2;
        data2.col.add(j);
    }
  opl.addDataSource(data2);
  opl.generate();
}
if (cplex.solve()) {
writeln("Solution = " + cplex.getObjValue(),
"/ time = ", cplex.getCplexTime());
} else {
    writeln("No solution");
}
data2.end();
opl.end();
}

sub.mod :

{int} row=...;
{int} col=...;
int y[row][col];

execute {

 for (var i in row) {
     for (var j in col) {
        y[i][j]=i;
    }
 }
    writeln("y= ",y,
//    " / i= ", i,
//  "/ row = ", row,
    "/ col = ", col,
    "/ time = ", cplex.getCplexTime());
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}

Now, I obtain the right values in row = {10, 20, 30} and col = {10, 20, 30} in the main.mod.

In sub.mod row and col are sets. I need to use those values as matrices dimensions. So the first matrix is 10x10, the second 20x20 etc..

How can I access the values inside the set so that I can create those matrices ?

Sorry for the multiple questions but I am really new to CPLEX.

Body:
You can slightly rewrite your sub.mod to get this going:

{int} rowSet = ...;
{int} colSet = ...;

range row = 1..last(rowSet);
range col = 1..last(colSet);

int y[row][col];

execute {
  for (var i in row) {
    for (var j in col) {
      y[i][j] = i;
    }
  }
  writeln(y);
}

The last function will return the last element from the respective set. So in the first iteration you get 10, in the second 20 and in the third 30. Then row and col are constructed as range with the desired number of elements. These can then be used to initialize the array.

Note that in main.mod you must replace data2.row by data2.rowSet and data2.col by data2.colSet.


问:
Is it possible to define a 'move-and-swap idiom' equivalent in C++03
I'm bound to C++03 and I have a non-copyable object (e.g. holding a resource).

I need to use move-and-swap semantics to be able to do something similar and avoid copies:

```<code>MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test;
    test = returnMyClass(); // need to avoid copies
}
</code>```

Is it possible to respect all these requirements in C++03?

It is basically the same case of this, but for C++03.

To put the question in other words:

Given a non-copyable class MyClass, is it somehow possible in C++03 to do MyClass test = returnMyClass();?

I'm afraid the answer is simply no, but maybe I'm missing some trick.

答:
If you can initialize your object test at declaration you will be able to avoid copying because copy elision will be performed.

```<code>class MyClass
{
  public:
    MyClass(){std::cout << "Default Constructor" << std::endl;}
    MyClass(const MyClass &){std::cout << "CPYConstructor" << std::endl;}
    ~MyClass() {std::cout << "Destructor" << std::endl;}

};

MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test = returnMyClass(); // need to avoid copies
}
</code>```

Output:

```<code>Default Constructor
Destructor
</code>```

Body:
I'm bound to C++03 and I have a non-copyable object (e.g. holding a resource).

I need to use move-and-swap semantics to be able to do something similar and avoid copies:

MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test;
    test = returnMyClass(); // need to avoid copies
}

Is it possible to respect all these requirements in C++03?

It is basically the same case of this, but for C++03.

To put the question in other words:

Given a non-copyable class MyClass, is it somehow possible in C++03 to do MyClass test = returnMyClass();?

I'm afraid the answer is simply no, but maybe I'm missing some trick.

Body:
If you can initialize your object test at declaration you will be able to avoid copying because copy elision will be performed.

class MyClass
{
  public:
    MyClass(){std::cout << "Default Constructor" << std::endl;}
    MyClass(const MyClass &){std::cout << "CPYConstructor" << std::endl;}
    ~MyClass() {std::cout << "Destructor" << std::endl;}

};

MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test = returnMyClass(); // need to avoid copies
}

Output:

Default Constructor
Destructor