问:
UIAutomation iPhone: Is it possible to segment the script into several files
I want to write UIAutomation (JavaScript based) tests for a rather complex iPhone App. I dont't want to use one single huge file, but to seperate the testing functions and helpers by using several files. Is that possible at all? How do you structure your UIAutomation tests?</p>

答:
UIAutomation cannot handle large script files that you might end up with bundling your tests, helper functions, etc. - using the #include directive. However, it is the only way you can manually run multiple tests, stored within separate files.

I have encountered this problem when building a small (600-700 lines or 25KB of code) JS framework that is able to run test sets and suites.

The test structure I came up with:

```<code>#import "test_scripts.js"
#import "test_data.js"
#import "helper_tools.js"

tools.runTestSet(TestContainer);
</code>```

Where TestContainer is the link to an object holding all my test cases as its fields/members.
And test_data.js encapsulates data within JSON container.

P.S. at first I thought that UIAutomation has a great potential, but in the course of time I got disappointed. You cannot run complete automation testing cycles using this tool. Also, keep in mind that it provides you with API to work with UI only: no access to the "back-end" processes.

ContentLicense: CC BY-SA 2.5

Body:
UIAutomation cannot handle large script files that you might end up with bundling your tests, helper functions, etc. - using the #include directive. However, it is the only way you can manually run multiple tests, stored within separate files.

I have encountered this problem when building a small (600-700 lines or 25KB of code) JS framework that is able to run test sets and suites.

The test structure I came up with:

#import "test_scripts.js"
#import "test_data.js"
#import "helper_tools.js"

tools.runTestSet(TestContainer);

Where TestContainer is the link to an object holding all my test cases as its fields/members.
And test_data.js encapsulates data within JSON container.

P.S. at first I thought that UIAutomation has a great potential, but in the course of time I got disappointed. You cannot run complete automation testing cycles using this tool. Also, keep in mind that it provides you with API to work with UI only: no access to the "back-end" processes.


来源: stackexchange

问:
How to flip Camera used by ZXing in Xamaring Forms
As part of the app i'm developing i want the ability to change between using the front or back camera, but from my searches and attempts i haven't been able to get it to work using the front camera.

The scanner view doing the scanning is the one from ZXing.Net.Mobile.Forms called ZXingScannerView, defined in my xaml like so, together with the button that should do the flipping of the camera.

<elements:AdvancedTabbedPage
...
xmlns:elements="clr-namespace:Wolf.Utility.Main.Xamarin.Elements;assembly=Wolf.Utility.Main"
xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
...

<ContentPage>
   <ContentPage.ToolbarItems>
       <ToolbarItem Text="{x:Static resources:AppResources.CameraFlipText}" x:Name="CameraFlipButton" Clicked="CameraFlipButton_OnClicked"/>
   </ContentPage.ToolbarItems>
   <ContentPage.Content>
...
       <forms:ZXingScannerView x:Name="ScannerView" HeightRequest="200" IsAnalyzing="False" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" IsVisible="False" IsScanning="True"/>
...
   </ContentPage.Content>
</ContentPage>
```

<p>The Button can be seen in the top right of the following image, while the Scanner View is only visible while scanning is On, which it is not on the image.</p>

<p>Image of the Page where Scannning is happening</p>

<p>Clicking the button should toggle between using the front and back camera, with the front one as the default. Clicking the button however, doesn't seem to do anything, other then write to my Log. Code for the Clicked event of the button can be seen below.</p>

<pre class="lang-cs prettyprint-override"><code>...
private void CameraFlipButton_OnClicked(object sender, EventArgs e)
        {
            Logging.Log(LogType.Information, "Flipping Camera...");

            Config.DefaultOptions.UseFrontCameraIfAvailable = !Config.DefaultOptions.UseFrontCameraIfAvailable;
            Config.CustomOptions.UseFrontCameraIfAvailable = !Config.CustomOptions.UseFrontCameraIfAvailable;

            if (!ScanningToggle.IsToggled) return;

            Logging.Log(LogType.Information, "Restarting Scanning...");
            ScanningToggle.IsToggled = false;
            ScanningToggle.IsToggled = true;
        }
</code>```

The options mentioned in the above code is defined as so, in my Config class. Additional values in the one called CustomOptions are set in my Init method of my Config class, but those are irrelevant to this question.

public class Config
{
...
public static MobileBarcodeScanningOptions CustomOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
public static MobileBarcodeScanningOptions DefaultOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
...
}
```

The options that my scanner will use, is always picked between these two, depending on a few user inputs in the settings.

Attempting to get it to work i have also tried to...

Invert the value UseFrontCameraIfAvailable, while scanning is running

Invert the value UseFrontCameraIfAvailable on the options used to start the scan with and then restarting the scan - The code shown above.

Change IsScanning of the ZXingScannerView from true to false, while restarting the scanning with changed options, but this just resulted in the camera freezing.

Found this one as i was about to submit the question. I'm going to attempt to follow that one tomorrow, but would still very much like input on mine.

Fell free to ask questions, or ask for additional code if i have left something out, that you think could help.

答:
I managed to figure out how to successfully flip the camera.

To do so i first remove the ZXingScannerView from my stack that contains it.

Then i create a new instance of the ZXingScannerView, copying over all the settings from the old one (layout positioning, ZXingScannerView specific values and so on).

Then i re-add the ZXingScannerView to the stack, and from there any changes to the UseFrontCameraIfAvailable property took effect.

The code it made to succeed, is as follows. First the generic method that copies over properties, then the method that recreates the ZXingScannerView, and lastly my method that enables the scanning.

public class GenericFactory
    {
        // Assistance with Setter Accessibility: https://stackoverflow.com/questions/3762456/how-to-check-if-property-setter-is-public
        public static T CopyProperties<T>(T newObject, T oldObject, bool ignoreDefaults = true,
            bool skipSelectedProperties = true, params string[] skippedProperties) where T : class
        {
            var type = typeof(T);
            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                if (ignoreDefaults && property.GetValue(oldObject) == default)
                    continue;
                if (skipSelectedProperties && skippedProperties.Contains(property.Name))
                    continue;
                if (!property.CanWrite)
                    continue;

                property.SetValue(newObject, property.GetValue(oldObject));
            }

            return newObject;
        }
    }
```

<pre class="lang-cs prettyprint-override"><code>private void RecreateScannerView()
        {
            if (Config.DebugMode) Logging.Log(LogType.Debug, $"{nam1eof(RecreateScannerView)} method called");
            ScannerStack.Children.Remove(ScannerView);

            if (Config.DebugMode)
                Logging.Log(LogType.Debug,
                    $"Coping properties from existing {nameof(ZXingScannerView)} into a new {nameof(ZXingScannerView)}");
            ScannerView = GenericFactory.CopyProperties(new ZXingScannerView() {IsScanning = false}, ScannerView,
                skippedProperties: new List<string>() {nameof(ScannerView.IsScanning)}.ToArray());
            ScannerView.OnScanResult += ScannerView_OnScanResult;

            ScannerStack.Children.Add(ScannerView);
        }
</code>```

private void EnableScan(MobileBarcodeScanningOptions imputedOptions = null)
        {
            if (Config.DebugMode) Logging.Log(LogType.Debug, $"{nameof(EnableScan)} Method is run in Thread named => {Thread.CurrentThread.Name}");

            var chosenOptions = imputedOptions ?? (Config.UseCustomOptions ? Config.CustomOptions : Config.DefaultOptions);
            if (Config.DebugMode)
                Logging.Log(LogType.Information,
                    $"Chose this option for Scanning => {(imputedOptions != null ? nameof(imputedOptions) : (Config.UseCustomOptions ? nameof(Config.CustomOptions) : nameof(Config.DefaultOptions)))}");
            ScannerView.Options = chosenOptions;

            RecreateScannerView();

            Logging.Log(LogType.Information, $"Starting the Scanning...");
            ScannerView.IsScanning = true;
            ScannerView.IsAnalyzing = true;
            ScannerView.IsVisible = true;

            if (Config.DebugMode)
                Logging.Log(LogType.Debug,
                    $"{nameof(EnableScan)} Called and Finished; ScannerView.IsAnalyzing => {ScannerView.IsAnalyzing}; ScannerView.IsVisible => {ScannerView.IsVisible}");
        }
```

My method to flip the value of UseFrontCameraIfAvailable is the one shown in the question above.

Hope to this ends up helping others who might stumble upon a likewise issue.

ContentLicense: CC BY-SA 4.0

Body:
As part of the app i'm developing i want the ability to change between using the front or back camera, but from my searches and attempts i haven't been able to get it to work using the front camera.

The scanner view doing the scanning is the one from ZXing.Net.Mobile.Forms called ZXingScannerView, defined in my xaml like so, together with the button that should do the flipping of the camera.

<elements:AdvancedTabbedPage
...
xmlns:elements="clr-namespace:Wolf.Utility.Main.Xamarin.Elements;assembly=Wolf.Utility.Main"
xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms">
...

<ContentPage>
   <ContentPage.ToolbarItems>
       <ToolbarItem Text="{x:Static resources:AppResources.CameraFlipText}" x:Name="CameraFlipButton" Clicked="CameraFlipButton_OnClicked"/>
   </ContentPage.ToolbarItems>
   <ContentPage.Content>
...
       <forms:ZXingScannerView x:Name="ScannerView" HeightRequest="200" IsAnalyzing="False" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" IsVisible="False" IsScanning="True"/>
...
   </ContentPage.Content>
</ContentPage>

The Button can be seen in the top right of the following image, while the Scanner View is only visible while scanning is On, which it is not on the image.

Image of the Page where Scannning is happening

Clicking the button should toggle between using the front and back camera, with the front one as the default. Clicking the button however, doesn't seem to do anything, other then write to my Log. Code for the Clicked event of the button can be seen below.

...
private void CameraFlipButton_OnClicked(object sender, EventArgs e)
        {
            Logging.Log(LogType.Information, "Flipping Camera...");

            Config.DefaultOptions.UseFrontCameraIfAvailable = !Config.DefaultOptions.UseFrontCameraIfAvailable;
            Config.CustomOptions.UseFrontCameraIfAvailable = !Config.CustomOptions.UseFrontCameraIfAvailable;

            if (!ScanningToggle.IsToggled) return;

            Logging.Log(LogType.Information, "Restarting Scanning...");
            ScanningToggle.IsToggled = false;
            ScanningToggle.IsToggled = true;
        }

The options mentioned in the above code is defined as so, in my Config class. Additional values in the one called CustomOptions are set in my Init method of my Config class, but those are irrelevant to this question.

public class Config
{
...
public static MobileBarcodeScanningOptions CustomOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
public static MobileBarcodeScanningOptions DefaultOptions = new MobileBarcodeScanningOptions() { UseFrontCameraIfAvailable = true };
...
}

The options that my scanner will use, is always picked between these two, depending on a few user inputs in the settings.

Attempting to get it to work i have also tried to...

Invert the value UseFrontCameraIfAvailable, while scanning is running

Invert the value UseFrontCameraIfAvailable on the options used to start the scan with and then restarting the scan - The code shown above.

Change IsScanning of the ZXingScannerView from true to false, while restarting the scanning with changed options, but this just resulted in the camera freezing.

Found this one as i was about to submit the question. I'm going to attempt to follow that one tomorrow, but would still very much like input on mine.

Fell free to ask questions, or ask for additional code if i have left something out, that you think could help.

Body:
I managed to figure out how to successfully flip the camera.

To do so i first remove the ZXingScannerView from my stack that contains it.

Then i create a new instance of the ZXingScannerView, copying over all the settings from the old one (layout positioning, ZXingScannerView specific values and so on).

Then i re-add the ZXingScannerView to the stack, and from there any changes to the UseFrontCameraIfAvailable property took effect.

The code it made to succeed, is as follows. First the generic method that copies over properties, then the method that recreates the ZXingScannerView, and lastly my method that enables the scanning.

public class GenericFactory
    {
        // Assistance with Setter Accessibility: https://stackoverflow.com/questions/3762456/how-to-check-if-property-setter-is-public
        public static T CopyProperties<T>(T newObject, T oldObject, bool ignoreDefaults = true,
            bool skipSelectedProperties = true, params string[] skippedProperties) where T : class
        {
            var type = typeof(T);
            var properties = type.GetProperties();

            foreach (var property in properties)
            {
                if (ignoreDefaults && property.GetValue(oldObject) == default)
                    continue;
                if (skipSelectedProperties && skippedProperties.Contains(property.Name))
                    continue;
                if (!property.CanWrite)
                    continue;

                property.SetValue(newObject, property.GetValue(oldObject));
            }

            return newObject;
        }
    }

private void RecreateScannerView()
        {
            if (Config.DebugMode) Logging.Log(LogType.Debug, $"{nam1eof(RecreateScannerView)} method called");
            ScannerStack.Children.Remove(ScannerView);

            if (Config.DebugMode)
                Logging.Log(LogType.Debug,
                    $"Coping properties from existing {nameof(ZXingScannerView)} into a new {nameof(ZXingScannerView)}");
            ScannerView = GenericFactory.CopyProperties(new ZXingScannerView() {IsScanning = false}, ScannerView,
                skippedProperties: new List<string>() {nameof(ScannerView.IsScanning)}.ToArray());
            ScannerView.OnScanResult += ScannerView_OnScanResult;

            ScannerStack.Children.Add(ScannerView);
        }

private void EnableScan(MobileBarcodeScanningOptions imputedOptions = null)
        {
            if (Config.DebugMode) Logging.Log(LogType.Debug, $"{nameof(EnableScan)} Method is run in Thread named => {Thread.CurrentThread.Name}");

            var chosenOptions = imputedOptions ?? (Config.UseCustomOptions ? Config.CustomOptions : Config.DefaultOptions);
            if (Config.DebugMode)
                Logging.Log(LogType.Information,
                    $"Chose this option for Scanning => {(imputedOptions != null ? nameof(imputedOptions) : (Config.UseCustomOptions ? nameof(Config.CustomOptions) : nameof(Config.DefaultOptions)))}");
            ScannerView.Options = chosenOptions;

            RecreateScannerView();

            Logging.Log(LogType.Information, $"Starting the Scanning...");
            ScannerView.IsScanning = true;
            ScannerView.IsAnalyzing = true;
            ScannerView.IsVisible = true;

            if (Config.DebugMode)
                Logging.Log(LogType.Debug,
                    $"{nameof(EnableScan)} Called and Finished; ScannerView.IsAnalyzing => {ScannerView.IsAnalyzing}; ScannerView.IsVisible => {ScannerView.IsVisible}");
        }

My method to flip the value of UseFrontCameraIfAvailable is the one shown in the question above.

Hope to this ends up helping others who might stumble upon a likewise issue.


问:
data modeling & security rules advice firebase
I am trying to model 2 concepts in firestore and also associate

```<code>collection: users
key/document_id: email
document: profile info

collection: topics
key/document_id: random
document: metadata with a field indicating email of user (to use for lookups)
</code>```

My goal is to

"reference" topics in users for easy lookups, but not sure how to do
it other than a sub collection.

Based on email which will be passed as part of auth, I want to have security rule to allow writes in collection only on path, field
based on email

Are both of above feasible in Firebase. Appreciate any pointers!

答:
Preamble: There isn't ONE and only ONE correct approach in NoSQL data modelling

Your approach seems valid, however I  would suggest the following adaptations:

"Reference topics in users for easy lookups":

To "reference topics in users for easy lookups" you could duplicate the list of topics in an array in the user profile. You will then be able to use array-contains (and other array membership methods) for your queries. (Note however the limitation of the in operator).

Advantage of this approach: you only need to query one document to get all the topics of a user. Possible drawback: there is a limit on the size for a document (and for a single field value) which is maximum 1 MiB (1,048,576 bytes), see the doc.

You can easily keep in sync the topics array and the topics sub-collection by combining a batched write and the arrayUnion() and arrayRemove() methods.

Use the user ID instead of the email for doc Ids and Security Rules:

Instead of using the email as the users collection document ID and using it in Security Rules, use the user ID. See the examples in the doc.

Body:
I am trying to model 2 concepts in firestore and also associate

collection: users
key/document_id: email
document: profile info

collection: topics
key/document_id: random
document: metadata with a field indicating email of user (to use for lookups)

My goal is to

"reference" topics in users for easy lookups, but not sure how to do
it other than a sub collection.

Based on email which will be passed as part of auth, I want to have security rule to allow writes in collection only on path, field
based on email

Are both of above feasible in Firebase. Appreciate any pointers!


问:
Parcelable object is Null on receiving activity and good in other
Thanks to those who will try to help me!

First time I sent a message. I'm stuck with my parcel.
I try to send an object Neighbour in a recyclerView for a class DetailedNeighbour. After I send my variable to DetailedActivity.putExtra("DNeighbour", neighbour); is well equal to what I want and after in DetailedNeighbourActivity is equal to null.

Neighbour:

package com.openclassrooms.entrevoisins.model;

```<code>/**
 * Model object representing a Neighbour
 */
public class Neighbour implements Parcelable {

    /** Identifier */
    private long id;

    /** Full name */
    private String name;

    /** Avatar */
    private String avatarUrl;

    /** Adress */
    private String address;

    /** Phone number */
    private String phoneNumber;

    /** About me */
    private String aboutMe;

    /**
     * Constructor
     * @param id
     * @param name
     * @param avatarUrl
     */
    public Neighbour(long id, String name, String avatarUrl, String address,
                     String phoneNumber, String aboutMe) {
        this.id = id;
        this.name = name;
        this.avatarUrl = avatarUrl;
        this.address = address;
        this.phoneNumber = phoneNumber;
        this.aboutMe = aboutMe;
    }

        public  Neighbour (Parcel in){   //constructor  //Protected ?
        id =in.readLong();                  //read and set saved values from parcel
        name=in.readString();
        avatarUrl=in.readString();
        address=in.readString();
        phoneNumber=in.readString();
        aboutMe=in.readString();
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getAboutMe() {
        return aboutMe;
    }

    public void setAboutMe(String aboutMe) {
        this.aboutMe = aboutMe;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Neighbour neighbour = (Neighbour) o;
        return Objects.equals(id, neighbour.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) { // In this method you add all your class properties to the parcel which are needed to transfer.
        parcel.writeString(name);
        parcel.writeString(phoneNumber);
        parcel.writeString(avatarUrl);
        parcel.writeString(aboutMe);
        parcel.writeString(address);
        parcel.writeLong(id);  /// for favoris ?

    }

    public static final Parcelable.Creator<Neighbour> CREATOR = new Parcelable.Creator<Neighbour>() {   ///This is the method which is used to bind everything together. Nothing much is done here.
        @Override
        public Neighbour createFromParcel(Parcel in) {
            return new Neighbour(in);
        }

        @Override
        public Neighbour[] newArray(int size) {
            return new Neighbour[size];
        }
    };
    public static Creator<Neighbour> getCREATOR() {
        return CREATOR;
    }
    @Override
    public int describeContents() {
        return 0;
    }
}
</code>```

RecyclerViewAdapter:

package com.openclassrooms.entrevoisins.ui.neighbour_list;

```<code>public class MyNeighbourRecyclerViewAdapter extends RecyclerView.Adapter<MyNeighbourRecyclerViewAdapter.ViewHolder> {

    private final List<Neighbour> mNeighbours;

    public MyNeighbourRecyclerViewAdapter(List<Neighbour> items) {
        mNeighbours = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_neighbour, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Neighbour neighbour = mNeighbours.get(position);
        holder.mNeighbourName.setText(neighbour.getName());
        Glide.with(holder.mNeighbourAvatar.getContext())
                .load(neighbour.getAvatarUrl())
                .apply(RequestOptions.circleCropTransform())
                .into(holder.mNeighbourAvatar);
        holder.mNeighbourName.setOnClickListener(new View.OnClickListener() { ///   Observe le clic sur bouton name
            @Override
            public void onClick(View view) {
                Intent DetailedActivity = new Intent(view.getContext(), DetailedNeighbourActivity.class);       //
                DetailedActivity.putExtra("DNeighbour", neighbour);
                view.getContext().startActivity(DetailedActivity);//
                EventBus.getDefault();//
                Log.i("DEBUG","l'utilisateur essaye d'ouvrir le détaille");
            }
        });
        holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new DeleteNeighbourEvent(neighbour));
            }
        });
    }

    @Override
    public int getItemCount() {
        return mNeighbours.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.item_list_avatar)
        public ImageView mNeighbourAvatar;
        @BindView(R.id.item_list_name)
        public TextView mNeighbourName;
        @BindView(R.id.item_list_delete_button)
        public ImageButton mDeleteButton;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

</code>```

DetailedNeighboursActivity:

```<code>
public class DetailedNeighbourActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_neighbour);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        Neighbour neighbour = (Neighbour) getIntent().getParcelableExtra("DNeighbour");
        String name = neighbour.getName();

        EventBus.getDefault();
        Log.i("DEBUG", "Le détaille "+ name);
    }
}
</code>```

答:
I'm not really smart ! Sorry for you time .
parcel and writeparcel constructor need the same order for variables. it's ok my code work.</p>

Body:
Thanks to those who will try to help me!

First time I sent a message. I'm stuck with my parcel.
I try to send an object Neighbour in a recyclerView for a class DetailedNeighbour. After I send my variable to DetailedActivity.putExtra("DNeighbour", neighbour); is well equal to what I want and after in DetailedNeighbourActivity is equal to null.

Neighbour:

package com.openclassrooms.entrevoisins.model;

/**
 * Model object representing a Neighbour
 */
public class Neighbour implements Parcelable {

    /** Identifier */
    private long id;

    /** Full name */
    private String name;

    /** Avatar */
    private String avatarUrl;

    /** Adress */
    private String address;

    /** Phone number */
    private String phoneNumber;

    /** About me */
    private String aboutMe;

    /**
     * Constructor
     * @param id
     * @param name
     * @param avatarUrl
     */
    public Neighbour(long id, String name, String avatarUrl, String address,
                     String phoneNumber, String aboutMe) {
        this.id = id;
        this.name = name;
        this.avatarUrl = avatarUrl;
        this.address = address;
        this.phoneNumber = phoneNumber;
        this.aboutMe = aboutMe;
    }

        public  Neighbour (Parcel in){   //constructor  //Protected ?
        id =in.readLong();                  //read and set saved values from parcel
        name=in.readString();
        avatarUrl=in.readString();
        address=in.readString();
        phoneNumber=in.readString();
        aboutMe=in.readString();
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getAboutMe() {
        return aboutMe;
    }

    public void setAboutMe(String aboutMe) {
        this.aboutMe = aboutMe;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Neighbour neighbour = (Neighbour) o;
        return Objects.equals(id, neighbour.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) { // In this method you add all your class properties to the parcel which are needed to transfer.
        parcel.writeString(name);
        parcel.writeString(phoneNumber);
        parcel.writeString(avatarUrl);
        parcel.writeString(aboutMe);
        parcel.writeString(address);
        parcel.writeLong(id);  /// for favoris ?

    }

    public static final Parcelable.Creator<Neighbour> CREATOR = new Parcelable.Creator<Neighbour>() {   ///This is the method which is used to bind everything together. Nothing much is done here.
        @Override
        public Neighbour createFromParcel(Parcel in) {
            return new Neighbour(in);
        }

        @Override
        public Neighbour[] newArray(int size) {
            return new Neighbour[size];
        }
    };
    public static Creator<Neighbour> getCREATOR() {
        return CREATOR;
    }
    @Override
    public int describeContents() {
        return 0;
    }
}

RecyclerViewAdapter:

package com.openclassrooms.entrevoisins.ui.neighbour_list;

public class MyNeighbourRecyclerViewAdapter extends RecyclerView.Adapter<MyNeighbourRecyclerViewAdapter.ViewHolder> {

    private final List<Neighbour> mNeighbours;

    public MyNeighbourRecyclerViewAdapter(List<Neighbour> items) {
        mNeighbours = items;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_neighbour, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Neighbour neighbour = mNeighbours.get(position);
        holder.mNeighbourName.setText(neighbour.getName());
        Glide.with(holder.mNeighbourAvatar.getContext())
                .load(neighbour.getAvatarUrl())
                .apply(RequestOptions.circleCropTransform())
                .into(holder.mNeighbourAvatar);
        holder.mNeighbourName.setOnClickListener(new View.OnClickListener() { ///   Observe le clic sur bouton name
            @Override
            public void onClick(View view) {
                Intent DetailedActivity = new Intent(view.getContext(), DetailedNeighbourActivity.class);       //
                DetailedActivity.putExtra("DNeighbour", neighbour);
                view.getContext().startActivity(DetailedActivity);//
                EventBus.getDefault();//
                Log.i("DEBUG","l'utilisateur essaye d'ouvrir le détaille");
            }
        });
        holder.mDeleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new DeleteNeighbourEvent(neighbour));
            }
        });
    }

    @Override
    public int getItemCount() {
        return mNeighbours.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.item_list_avatar)
        public ImageView mNeighbourAvatar;
        @BindView(R.id.item_list_name)
        public TextView mNeighbourName;
        @BindView(R.id.item_list_delete_button)
        public ImageButton mDeleteButton;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

DetailedNeighboursActivity:

public class DetailedNeighbourActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_neighbour);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        Neighbour neighbour = (Neighbour) getIntent().getParcelableExtra("DNeighbour");
        String name = neighbour.getName();

        EventBus.getDefault();
        Log.i("DEBUG", "Le détaille "+ name);
    }
}


问:
Remove rows which nothing in more than one columns
```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)
</code>```

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

```<code>data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)
</code>```

答:
We can use rowSums

```<code>df[rowSums(df == '') < 2, ]
</code>```

Body:
data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where",""), stringsAsFactors = FALSE)

How is it possible to check for text1, text2, text3 column if all of them have cells with nothing written how to remove it?

Example of expected output

data.frame(id = c(1,2,3), text1 = c("sth","","another"), text2 = c("more","another","add"), text3 = c("final","and","where"), stringsAsFactors = FALSE)

Body:
We can use rowSums

df[rowSums(df == '') < 2, ]


问:
Trigger not working on custom control image button wpf
I have created one custom cotrol

Generic.xaml code is below -

```<code><BitmapImage x:Key="RightImaGE" x:Name="imgD" UriSource="/XYZ.UI_Test;components/Resources/Pfad55-1.png"/>

    <Style TargetType="{x:Type local1:CustomButton}" >
        <Setter Property="Template">
             <Setter.Value>
                <ControlTemplate TargetType="{x:Type local1:CustomButton}">
                    <!--<Image Name="imgDefault" Source="{TemplateBinding Image}"  Stretch="UniformToFill" />-->
                    <ControlTemplate.Triggers>

                        <DataTrigger Binding="{Binding Path=ContentOff, RelativeSource={RelativeSource  AncestorType=local1:CustomButton}}" Value="SETTINGS">
                            <Setter Property="Background" Value="Red"/>
                            <Setter  Property="Image.Source" Value="{DynamicResource RightImaGE}" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

CustomButton.cs codebehind is below

```<code>public string ContentOff
        {
            get { return (string)GetValue(ContentOffProperty); }
            set { SetValue(ContentOffProperty, value); }
        }
        public static readonly DependencyProperty ContentOffProperty =
            DependencyProperty.Register("ContentOff",
            typeof(string), typeof(CustomButton), new PropertyMetadata(null));

        public ImageSource Image
        {
            get { return (ImageSource)GetValue(ImageProperty); }
            set { SetValue(ImageProperty, value); }
        }

        public static readonly DependencyProperty ImageProperty =
            DependencyProperty.Register("Image", typeof(ImageSource), typeof(CustomButton), new PropertyMetadata(default(ImageSource)));
</code>```

I have defined one common style in app.xaml code is below

```<code><Application.Resources>
        <Style x:Key="BigButtonStyle" TargetType="local:CustomButton" >
            <Setter Property="Control.Background" Value="Transparent"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="Margin" Value="1"/>
            <Setter Property="FontSize" Value="27"/>
            <Setter Property="FontWeight" Value="Bold"/>
            <Setter Property="Foreground" Value="#1d5560"/>
            <Setter Property="Width" Value="170"/>
            <Setter Property="MaxHeight" Value="50"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomButton}">
                        <Canvas Margin="1">
                            <Image x:Name="img" Source="Resources/Pfad55.png"  Stretch="UniformToFill" >
                                <Image.Style>
                                    <Style TargetType="{x:Type Image}">
                                        <Setter Property="Source" Value="Resources/Pfad55.png" />
                                        <!--<Style.Triggers>
                                            --><!--<Trigger Property="ContentOff" Value="SETTINGS">
                                                <Setter Property="Opacity" Value="0.5" />
                                            </Trigger>--><!--
                                        </Style.Triggers>-->
                                    </Style>
                                </Image.Style>
                            </Image>
                            <ContentPresenter HorizontalAlignment="Center" Content="{TemplateBinding ContentOff}" Canvas.Top="14" Canvas.Left="47"
                                      VerticalAlignment="Center"/>
                        </Canvas>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

Now I have Mainwindows.xaml where I am using Custombutton and if button content is Settings it should change different image through trigger than common image which is defined in bigbuttonstyle .

```<code><Controls:CustomButton  Grid.Row="8" Grid.Column="2" Style="{StaticResource BigButtonStyle}"
                               ContentOff="SETTINGS"
                               Image="Resources/Pfad55-1.png"/>
</code>```

I tried to use data trigger here but not working and tried property trigger too. But image not changing somehow.

答:
You can use two different style with style inheritance -

```<code> <Style x:Key="SmallButtonStyle" TargetType="local:CustomButton" BasedOn="{StaticResource BigButtonStyle}">
           <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomButton}">
                        <Canvas Margin="1">
                            <Image Source="Resources/Pfad55-1.png"  Stretch="UniformToFill"  ></Image>
                            <ContentPresenter HorizontalAlignment="Center" Content="{TemplateBinding ContentOff}" Canvas.Top="14" Canvas.Left="85"
                                      VerticalAlignment="Center"/>
                        </Canvas>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

then use it

```<code>    <Controls:CustomButton  Grid.Row="8" Grid.Column="2" Style="{StaticResource SmallButtonStyle}"
                       ContentOff="SETTINGS"
                       Image="Resources/Pfad55-1.png"/>
</code>```

It'll be working but without trigger.

Another solution I have added based on your requirement.
Change your Generic.Xaml code like below.

```<code><Style TargetType="{x:Type local1:CustomButton}" >
    <Setter Property="FontSize" Value="27"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Foreground" Value="#1d5560"/>
    <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="{x:Type local1:CustomButton}">
                <Grid>
                    <Image  Stretch="Fill" >
                        <Image.Style>
                            <Style TargetType="{x:Type Image}">
                                <Setter Property="Source" Value="Resources/Pfad55.png" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local1:CustomButton},Path=ContentOff}"
                                        Value="SETTINGS">
                                        <Setter Property="Source"
                                                Value="Resources/Pfad55-1.png" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Image.Style>
                    </Image>
                    <ContentPresenter HorizontalAlignment="Left" Margin="50,0,0,0" Content="{TemplateBinding ContentOff}"
                                  VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>

        </Setter.Value>
    </Setter>
</Style>
</code>```

And Chnage your MainWindow.xaml implementation with this

```<code><Controls:CustomButton  Grid.Row="8" Grid.Column="2" ContentOff="SETTINGS"/>
</code>```

You were using App.xaml style with BigButtonStyle , that's why custom control styles and trigger was not firing. Your App.xaml style was locally overriding custom control style and trigger from Generic.xaml.

Body:
I have created one custom cotrol

Generic.xaml code is below -

<BitmapImage x:Key="RightImaGE" x:Name="imgD" UriSource="/XYZ.UI_Test;components/Resources/Pfad55-1.png"/>

CustomButton.cs codebehind is below

public string ContentOff
        {
            get { return (string)GetValue(ContentOffProperty); }
            set { SetValue(ContentOffProperty, value); }
        }
        public static readonly DependencyProperty ContentOffProperty =
            DependencyProperty.Register("ContentOff",
            typeof(string), typeof(CustomButton), new PropertyMetadata(null));

        public ImageSource Image
        {
            get { return (ImageSource)GetValue(ImageProperty); }
            set { SetValue(ImageProperty, value); }
        }

        public static readonly DependencyProperty ImageProperty =
            DependencyProperty.Register("Image", typeof(ImageSource), typeof(CustomButton), new PropertyMetadata(default(ImageSource)));

I have defined one common style in app.xaml code is below

<Application.Resources>
        -->
                                    </Style>
                                </Image.Style>
                            </Image>
                            <ContentPresenter HorizontalAlignment="Center" Content="{TemplateBinding ContentOff}" Canvas.Top="14" Canvas.Left="47"
                                      VerticalAlignment="Center"/>
                        </Canvas>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Now I have Mainwindows.xaml where I am using Custombutton and if button content is Settings it should change different image through trigger than common image which is defined in bigbuttonstyle .

<Controls:CustomButton  Grid.Row="8" Grid.Column="2" Style="{StaticResource BigButtonStyle}"
                               ContentOff="SETTINGS"
                               Image="Resources/Pfad55-1.png"/>

I tried to use data trigger here but not working and tried property trigger too. But image not changing somehow.

Body:
You can use two different style with style inheritance -

 <Style x:Key="SmallButtonStyle" TargetType="local:CustomButton" BasedOn="{StaticResource BigButtonStyle}">
           <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomButton}">
                        <Canvas Margin="1">
                            <Image Source="Resources/Pfad55-1.png"  Stretch="UniformToFill"  ></Image>
                            <ContentPresenter HorizontalAlignment="Center" Content="{TemplateBinding ContentOff}" Canvas.Top="14" Canvas.Left="85"
                                      VerticalAlignment="Center"/>
                        </Canvas>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

then use it

    <Controls:CustomButton  Grid.Row="8" Grid.Column="2" Style="{StaticResource SmallButtonStyle}"
                       ContentOff="SETTINGS"
                       Image="Resources/Pfad55-1.png"/>

It'll be working but without trigger.

Another solution I have added based on your requirement.
Change your Generic.Xaml code like below.

<Style TargetType="{x:Type local1:CustomButton}" >
    <Setter Property="FontSize" Value="27"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Foreground" Value="#1d5560"/>
    <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="{x:Type local1:CustomButton}">
                <Grid>
                    <Image  Stretch="Fill" >
                        <Image.Style>
                            <Style TargetType="{x:Type Image}">
                                <Setter Property="Source" Value="Resources/Pfad55.png" />
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local1:CustomButton},Path=ContentOff}"
                                        Value="SETTINGS">
                                        <Setter Property="Source"
                                                Value="Resources/Pfad55-1.png" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Image.Style>
                    </Image>
                    <ContentPresenter HorizontalAlignment="Left" Margin="50,0,0,0" Content="{TemplateBinding ContentOff}"
                                  VerticalAlignment="Center"/>
                </Grid>
            </ControlTemplate>

        </Setter.Value>
    </Setter>
</Style>

And Chnage your MainWindow.xaml implementation with this

<Controls:CustomButton  Grid.Row="8" Grid.Column="2" ContentOff="SETTINGS"/>

You were using App.xaml style with BigButtonStyle , that's why custom control styles and trigger was not firing. Your App.xaml style was locally overriding custom control style and trigger from Generic.xaml.


答:
You could do:</p>

```<code>cols <- paste0("text", 1:3)
df[rowSums(df[cols] == "") < length(cols), ]
</code>```

Title: Remove rows which nothing in more than one columns

Body:
You could do:

cols <- paste0("text", 1:3)
df[rowSums(df[cols] == "") < length(cols), ]


问:
Create nested json file
I want to create a json file that can be used as a configuration file. I have different files from multiple companies that report the same information with different column names.

I want to use the information provided in the json file to run a python script to consolidate all the information from all files and companies in one master file.

The structure looks like follows:

```<code>{"companies":
    {"company1": [
        {"path": "C:/USER/Path/Company1/",
         "files": [
            {
                {"_CO": {"ID": "ID", "Report Number": "Report_Number"}},
                {"_TR": {"ID": "Trade_Ident", "Report Number": "Number of Report"}},
            },
         ],
        },
    ],
    },

    {"company2": [
        {"path": "C:/USER/Path/Company2/",
         "files": [
            {
                {"_CO": {"ID": "Identification", "Report Number": "Report-Number"}},
                {"_TR": {"ID": "Ident", "Report Number": "NumberReport"}},
            },
         ],
        },
    ],
    },
},
</code>```

However, I receive the following error when trying to read the .json in python.

json.decoder.JSONDecodeError: Expecting property name enclosed in
  double quotes: line 6 column 5 (char 90)

To read the file I use:

```<code>import json

path = "/user_folder/USER/Desktop/Data/"

file = "ConfigFile.json"

with open(path+file) as f:
    my_test = json.load(f)
</code>```

Any help appreciated, as I can't figure out my mistake in the file structure.

答:
You're getting error because your json file is incorrectly formatted and thus calling json.load() will raise an JSONDecodeError.

Your json structure should look like,

```<code>{
    "companies": {
        "company1": [
            {
                "path": "C:/USER/Path/Company1/",
                "files": [
                    {
                        "_CO": {
                            "ID": "ID",
                            "Report Number": "Report_Number"
                        }
                    },
                    {
                        "_TR": {
                            "ID": "Trade_Ident",
                            "Report Number": "Number of Report"
                        }
                    }
                ]
            }
        ],
        "company2": [
            {
                "path": "C:/USER/Path/Company2/",
                "files": [
                    {
                        "_CO": {
                            "ID": "Identification",
                            "Report Number": "Report-Number"
                        }
                    },
                    {
                        "_TR": {
                            "ID": "Ident",
                            "Report Number": "NumberReport"
                        }
                    }
                ]
            }
        ]
    }
}
</code>```

Hope it helps you!

Title: Create nested json file

Body:
I want to create a json file that can be used as a configuration file. I have different files from multiple companies that report the same information with different column names.

I want to use the information provided in the json file to run a python script to consolidate all the information from all files and companies in one master file.

The structure looks like follows:

{"companies":
    {"company1": [
        {"path": "C:/USER/Path/Company1/",
         "files": [
            {
                {"_CO": {"ID": "ID", "Report Number": "Report_Number"}},
                {"_TR": {"ID": "Trade_Ident", "Report Number": "Number of Report"}},
            },
         ],
        },
    ],
    },

    {"company2": [
        {"path": "C:/USER/Path/Company2/",
         "files": [
            {
                {"_CO": {"ID": "Identification", "Report Number": "Report-Number"}},
                {"_TR": {"ID": "Ident", "Report Number": "NumberReport"}},
            },
         ],
        },
    ],
    },
},

However, I receive the following error when trying to read the .json in python.

json.decoder.JSONDecodeError: Expecting property name enclosed in
  double quotes: line 6 column 5 (char 90)

To read the file I use:

import json

path = "/user_folder/USER/Desktop/Data/"

file = "ConfigFile.json"

with open(path+file) as f:
    my_test = json.load(f)

Any help appreciated, as I can't figure out my mistake in the file structure.

Body:
You're getting error because your json file is incorrectly formatted and thus calling json.load() will raise an JSONDecodeError.

Your json structure should look like,

{
    "companies": {
        "company1": [
            {
                "path": "C:/USER/Path/Company1/",
                "files": [
                    {
                        "_CO": {
                            "ID": "ID",
                            "Report Number": "Report_Number"
                        }
                    },
                    {
                        "_TR": {
                            "ID": "Trade_Ident",
                            "Report Number": "Number of Report"
                        }
                    }
                ]
            }
        ],
        "company2": [
            {
                "path": "C:/USER/Path/Company2/",
                "files": [
                    {
                        "_CO": {
                            "ID": "Identification",
                            "Report Number": "Report-Number"
                        }
                    },
                    {
                        "_TR": {
                            "ID": "Ident",
                            "Report Number": "NumberReport"
                        }
                    }
                ]
            }
        ]
    }
}

Hope it helps you!


问:
How to convert a directory to a ZIP?
I wanted to know how to convert a file (x) directly to a ZIP (x.zip), and convert it back into a normal file, using python (3.7)

答:
I use shutil

```<code>import shutil
#creating archive
shutil.make_archive(output_filename, 'zip', dir_name)
#unpacking archive
shutil.unpack_archive(input_filename, extract_dir, 'zip')
</code>```

you can also do with zipfile

```<code>import os
import zipfile
#creating zip file
zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()
#extracting zip file
with zipfile.ZipFile("myzipfile.zip", 'r') as zip:
    zip.extractall()
</code>```

Title: How to convert a directory to a ZIP?

Body:
I use shutil

import shutil
#creating archive
shutil.make_archive(output_filename, 'zip', dir_name)
#unpacking archive
shutil.unpack_archive(input_filename, extract_dir, 'zip')

you can also do with zipfile

import os
import zipfile
#creating zip file
zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()
#extracting zip file
with zipfile.ZipFile("myzipfile.zip", 'r') as zip:
    zip.extractall()


问:
Bitmap appearance is not looking good, dithering is not working, in Android
I want to use coverflow view in my app. To get the reflection image part i have used the following code - http://www.androidsnippets.com/create-image-with-reflection

I have seen lot of forums/discussions about dithering and tileMode, I have tried all that discussed but nothing works for me.

FYI - I am creating a bitmap dynamically not using any bitmap in layouts. And I have attached the image to show how bad it is:

I have listed below what I have tried to solve this issue.

```<code>   1. getWindow().setFlags(WindowManager.LayoutParams.FLAG_DITHER, WindowManager.LayoutParams.FLAG_DITHER);

   2. getWindow().setFormat(PixelFormat.RGBA_8888);

   3. BitmapDrawable baseImageDawable = new BitmapDrawable(getResources().openRawResource(imageId));
      baseImageDawable.setDither(true);
      baseImageDawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);

      Bitmap originalImage = baseImageDawable.getBitmap();
      int width = originalImage.getWidth();
      int height = originalImage.getHeight();

      Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, 0, width, height, matrix, true);
</code>```

But still the reflection image is very ugly.

How can I solve this?

答: I found the location where should I set the config. While creating the reflection bitmap set the config as ARGB_8888. Its working now.</p>

Body:
I want to use coverflow view in my app. To get the reflection image part i have used the following code - http://www.androidsnippets.com/create-image-with-reflection

I have seen lot of forums/discussions about dithering and tileMode, I have tried all that discussed but nothing works for me.

FYI - I am creating a bitmap dynamically not using any bitmap in layouts. And I have attached the image to show how bad it is:

I have listed below what I have tried to solve this issue.

   1. getWindow().setFlags(WindowManager.LayoutParams.FLAG_DITHER, WindowManager.LayoutParams.FLAG_DITHER);

   2. getWindow().setFormat(PixelFormat.RGBA_8888);

   3. BitmapDrawable baseImageDawable = new BitmapDrawable(getResources().openRawResource(imageId));
      baseImageDawable.setDither(true);
      baseImageDawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);

      Bitmap originalImage = baseImageDawable.getBitmap();
      int width = originalImage.getWidth();
      int height = originalImage.getHeight();

      Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, 0, width, height, matrix, true);

But still the reflection image is very ugly.

How can I solve this?

ContentLicense: CC BY-SA 3.0


问:
is there a way to remove UndefinedError in this code?
I am trying to display results of the most trending topics from twitter to my webpage but when i run the application it return jinja2.exceptions.UndefinedError: 'trends' is undefined. I suspect that i am not using  try/except how its supposed to.

```<code>@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')
</code>```

I also think there is an issue in my template code.

```<code><div class="column">
        <form  method="GET" action="{{url_for('index')}}">
            <div class="form-group">
                <p>See whats tending in your area.</p>
                <label for="">Enter location name</label>
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">
            </div>
        </form>
    </div>

    <div class="column">
        <h4>Top Trending</h4>
        <ul class="list-group">
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
          </ul>
    </div>
</code>```

答:
If tweepy.error.TweepError is raised you return render_template('index.html') which leaves trends undefined when this line {% for trend in trends[0]["trends"]%} is rendered.

You should change

```<code>return render_template('index.html')
</code>```

to

```<code>return render_template('index.html', trends=None)
</code>```

then check if trends was passed in the template:

```<code><div class="column">
    <h4>Top Trending</h4>
    <ul class="list-group">
        {% if trends is not None %}
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
        {% endif %}
    </ul>
</div>
</code>```

Body:
I am trying to display results of the most trending topics from twitter to my webpage but when i run the application it return jinja2.exceptions.UndefinedError: 'trends' is undefined. I suspect that i am not using  try/except how its supposed to.

@app.route('/')
def index():
    try:
        location = request.args.get('location')
        loc_id = client.fetch_woeid(str(location))
        trends = api.trends_place(int(loc_id))
        return render_template('index.html',trends=trends)
    except tweepy.error.TweepError:
        return render_template('index.html')

I also think there is an issue in my template code.

        <form  method="GET" action="{{url_for('index')}}">

See whats tending in your area.

                Enter location name
                <input type="text" name="location" class="form-control" id="exampleInput" placeholder="example london " required>
                <input type="submit" value="Search" class="btn btn-primary">

        </form>

Top Trending

            {% for trend in trends[0]["trends"]%}
                {{trend.name}}
            {% endfor %}

Body:
If tweepy.error.TweepError is raised you return render_template('index.html') which leaves trends undefined when this line {% for trend in trends[0]["trends"]%} is rendered.

You should change

return render_template('index.html')

to

return render_template('index.html', trends=None)

then check if trends was passed in the template:

<div class="column">
    <h4>Top Trending</h4>
    <ul class="list-group">
        {% if trends is not None %}
            {% for trend in trends[0]["trends"]%}
                <a class="list-group-item list-group-item-action" href="{{trend.url}}">{{trend.name}}</a>
            {% endfor %}
        {% endif %}
    </ul>
</div>


问:
I had this error while writing a code on motion planning. How to get rif of it?
```<code>import time, timeit, random, pygame, sys
from math import *
import numpy as np

XDIM = 1000 #window length
YDIM = 1200 #window breadth

WINSIZE = [XDIM, YDIM]
EPSILON = 7.0 #threshold
NUMNODES = 10000
GOAL_RADIUS = 10
MIN_DISTANCE_TO_ADD = 1.0 #incremental distance
GAME_LEVEL = 1

RANDOM_COUNT = 10000

pygame.init()
fpsClock = pygame.time.Clock()

#screen parameters and variable
screen = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('Q-learning')
white = 255, 240, 200
black = 20, 20, 40
red = 255, 0, 0
blue = 0, 255, 0
green = 0, 0, 255
cyan = 0,255,255

class Node:

    def __init__(self):
        self.x = x
        self.y = y
        self.cost = 0.0
        self.parent = None
        self.children = set()

class RRT(__Q_table):

    def __init__(self, start, goal,
                 obstacleList,  incremental_dist = 15.0,
                 learning_rate=20, max_iterations = 2000, randArea= None):

        self.start = Node(start[0], start[1])
        self.end   = Node(goal[0], goal[1])
        self.Xrand = randArea[0]
        self.Yrand = randArea[1]
        self.margin = incremental_distance
        self.learning_rate = learning_rate
        self.obstacleList = obstacleList
        self.max_iterations = max_iterations

    def planning(self, animation = True):

        self.NodeList = {0 : self.start}
        i=0

        while True:
            print(i)
        if set(self.start).intersection(obstacleList) == None:
            self.NodeList.append(self.start)

            print(self.NodeList)

        rnd = self.get_random_point()
        nearest_index = self.GetNearestListIndex(rnd)
        new_node = self.steer(rnd, nearest_index)

        if self.Collision_check(new_node, self.obstacleList):

            near_indices = self.find_near_nodes(new_node, 5)
            new_node     = self.choose_parent(new_node, near_indices)
            self.nodeList[i+100] = new_node
            self.rewire(i+100, new_node, near_indices)
            self.nodeList[new_node.parent].children.add(i+100)

            if len(self.NodeList) > self.max_iterations:
                leaves = [keys for key, node in self.NodeList.items]
                if len(leaves) > 1:
                    index = leaves[random.randint(0, len(leaves)-1)]
                    self.NodeList[self.NodeList[index].paresnt].children.discard(index)
                    self.NodeList.pop(index)
                else:
                    leaves = [key for key, node in self.NodeList.items() if len(node.children)==0]
                    index = leaves[random.randint(0, len(leaves) -1)]
                    self.NodeList[self.NodeList[index].parent].children.discard(index)
                    self.NodeList.pop(index)

            if animation == True:
                self.DrawGraph(rnd)

            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        self.obstacleList.append((event.pos[0], event.pos[1], 30, 30))
                        self.path_validation()
                    elif event.button == 3:
                        self.end.x = event.pos[0]
                        self.end.y = event.pos[1]
                        self.path_validation()

    def path_validation(self):

        lastIndex = self.get_the_best_last_index()
        if lastIndex and set(lastIndex).intersection(obstacleList) == None:
            while self.NodeList[lastIndex].parent is not None:
                nodeIndex = lastIndex
                lastIndex = self.NodeList[lastIndex].parent

                dx = self.NodeList[nodeIndex].x - self.NodeList[lastIndex].x
                dy = self.NodeList[nodeIndex].y - self.NodeList[lastIndex].y
                d = math.sqrt.atan2(dx**2 + dy**2)
                theta = math.atan2(dy, dx)
                if not self.check_collision_extend(self.NodeList[lastIndex].x,self.NodeList[lastIndex].y, theta, d):
                    self.NodeList[lastIndex].children.discard(nodeIndex)
                    self.eliminate_branch(nodeIndex)

    def eliminate_brach(self, nodeIndex):
        safenodesList = []
        if set(nodeIndex).intersection(obstacleList) == None:
            safenodesList.append(nodeIndex)
        for not_safe in safenodesList[nodeIndex].children:
            self.eliminate_branch(not_safe)
        self.NodeList.pop(nodeIndex)

    def choose_parent(self,new_node,nearest_index):
        if len(nearest_index) == 0:
            return new_node

        if Current_point == nearest_index and self.CollisionCheck(new_node, obstacleList):

            Current_point = new_node
            return Current_point

        distanceList = []
        for i in near_indices:
            dx = new_node.x - self.NodeList[i].x
            dy = new_node.y - self.NodeList[i].y
            d = math.sqrt(dx **2 + dy **2)
            theta = math.atan2(dy, dx)
            if self.check_collision_extend(self.NodeList[i].x, self.NodeList[i].y, theta, d):
                distanceList.append(self.NodeList[i].cost + d)
            else:
                distanceList.append(float("inf"))

        minimum_cost = min(distanceList)
        minimum_index = near_indices[distacelist.index(minimum_cost)]

        if minimum_cost == float("inf"):
            print("minimum_cost is INFINITE")
            return Current_point

        Current_point.cost = minimum_cost
        Current_point.parent = minimum_index

        Current_point_with_maximum_Q_value = self.max_Q_nextvalue(Current_point)

        return Current_point.cost, Current_point.parent, Current_point_with_maximum_Q_value

    def steer(self, rnd, nearest_index):

        nearest_node = self.NodeList[nearest_index]
        theta = math.atan2(rnd[1] - nearest_node.y, rnd[0] - nearest_node.x)
        new_node = Node(nearest_node.x , nearest_node.y)
        new_node.x += incremental_distance * math.cos(theta)
        new_node.y += incremental_distance * math.sin(theta)

        new_node.cost = nearest_node.cost + incremental_distance
        new_node.parent = nearest_index
        return new_node

    def get_random_point(self, Current_point=None):

        self.Current_point = Current_point
        if random.randint(0, 100) > self.learning_rate:
            rnd = [random.uniform(0, Xrand), random.uniform(0, yrand)]

        elif random.randint(0, 100) <= RANDOM_COUNT:
            Current_point = max_Q_action(Current_point)
            rnd = random_action(Current_point)
        else:
            rnd = [self.end.x, self.end.y]
        return rnd

    def get_best_last_index(self):

        disglist = [(key, self.calc_dist_to_goal(node.x, node.y)) for key, node in self.NodeList.items()]
        goal_indices = [key for key, distance in disglist if distance <= self.margin]

        if len(goal_indices) == 0:
            return None

        minimum_cost = min([self.NodeList[key].cost for key in goal_indices])
        for i in goal_indices:
            if self.NodeList[i].cost == minimum_cost:
                return i

        return None

    def gen_final_course(self, goal_indices):
        path = [[self.end.x, self.end.y]]
        while self.NodeList[goal_indices].parent is not None:
            node = self.NodeList[goal_indices]
            path.append([node.x, node.y])
            goal_indices = node.parent
        path.append([self.start.x, self.start.y])
        return path

    def calc_dist_to_goal(self, x, y):
        return np.linalg.norm([x - self.end.x, y - self.end.y])

    def find_near_nodes(self, new_node, value):
        r = self.margin * value

        distanceList = np.subtract( np.array([ (node.x, node.y) for node in self.NodeList.values() ]), (new_node.x,new_node.y))**2
        distanceList = np.sum(distanceList, axis=1)
        near_indices = np.where(distanceList <= r ** 2)
        near_indices = np.array(list(self.NodeList.keys()))[near_indices]

        return nearinds

    def rewire(self, newNodeInd, new_node, near):
        nnode = len(self.NodeList)
        for i in nearinds:
            nearNode = self.nodeList[i]

            dx = new_node.x - nearNode.x
            dy = new_node.y - nearNode.y
            d = math.sqrt(dx ** 2 + dy ** 2)

            scost = new_node.cost + d

            if near_node.cost > scost:
                theta = math.atan2(dy, dx)
                if self.check_collision_extend(nearNode.x, nearNode.y, theta, d):
                    self.NodeList[nearNode.parent].children.discard(i)
                    nearNode.parent = newNodeInd
                    nearNode.cost = scost
                    new_node.children.add(i)

    def check_collision_extend(self, nix, niy, theta, d):

        tmpNode = Node(nix,niy)

        for i in range(int(d/5)):
            tmpNode.x += 5 * math.cos(theta)
            tmpNode.y += 5 * math.sin(theta)
            if not self.CollisionCheck(tmpNode, self.obstacleList):
                return False

        return True

    def DrawGraph(self, rnd=None):

        screen.fill((255, 255, 255))
        for node in self.NodeList.values():
            if node.parent is not None:
                pygame.draw.line(screen,(0,255,0),[self.NodeList[node.parent].x,self.NodeList[node.parent].y],[node.x,node.y])

        for node in self.NodeList.values():
            if len(node.children) == 0:
                pygame.draw.circle(screen, (255,0,255), [int(node.x),int(node.y)], 2)

        for(sx,sy,ex,ey) in self.obstacleList:
            pygame.draw.rect(screen,(0,0,0), [(sx,sy),(ex,ey)])

        pygame.draw.circle(screen, (255,0,0), [self.start.x, self.start.y], 10)
        pygame.draw.circle(screen, (0,0,255), [self.end.x, self.end.y], 10)

        lastIndex = self.get_best_last_index()
        if lastIndex is not None:
            path = self.gen_final_course(lastIndex)

            ind = len(path)
            while ind > 1:
                pygame.draw.line(screen,(255,0,0),path[ind-2],path[ind-1])
                ind-=1

        pygame.display.update()

    def Get_nearest_list_index(self, rnd):
        distanceList = np.subtract( np.array([ (node.x, node.y) for node in self.NodeList.values() ]), (rnd[0],rnd[1]))**2
        distanceList = np.sum(distanceList, axis=1)
        minimum_index = list(self.NodeList.keys())[np.argmin(distancelist)]
        return minimum_index

    def Collision_check(self, node, obstacleList):
        for(sx,sy,ex,ey) in obstacleList:
            sx,sy,ex,ey = sx+2,sy+2,ex+2,ey+2
            if node.x > sx and node.x < sx+ex:
                if node.y > sy and node.y < sy+ey:
                    return False

        return True

def main():
    print("start RRT path planning")

    obstacleList = [
        (400, 380, 400, 20),
        (400, 220, 20, 180),
        (500, 280, 150, 20),
        (0, 500, 100, 20),
        (500, 450, 20, 150),
        (400, 100, 20, 80),
        (100, 100, 100, 20)
    ]

    rrt = RRT(obstacleList = obstacleList, start =[10, 580], goal = [540, 150],
              randArea = [XDIM, YDIM])
    path = rrt.Planning(animation=show_animation)

if __name__ == '__main__':
    main()
</code>```

The error is -

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-1-6e62c6da9819> in <module>
    531
    532 if __name__ == '__main__':
--> 533     main()
    534

<ipython-input-1-6e62c6da9819> in main()
    525
    526     rrt = RRT(obstacleList = obstacleList, start =[10, 580], goal = [540, 150],
--> 527               randArea = [XDIM, YDIM])
    528
    529     path = rrt.planning(animation=show_animation)

<ipython-input-1-6e62c6da9819> in __init__(self, start, goal, obstacleList, incremental_dist, learning_rate, max_iterations, randArea)
    249                  learning_rate=20, max_iterations = 2000, randArea= None):
    250
--> 251         self.start = Node(start[0], start[1])
    252         self.end   = Node(goal[0], goal[1])
    253         self.Xrand = randArea[0]
</code>```

TypeError: init() takes 1 positional argument but 3 were given

I am trying to write a code for motion planning in python using pygame module. I encountered this error given above. I even tried reducing the parameters into the constructor init() but it did not work out.

Please note that here I am not trying to do inheritance.

Thanks

答:
Replace

```<code>path = rrt.Planning(animation=show_animation)
</code>```

With

```<code>path = rrt.planning(animation=show_animation)
</code>```

Edit: after the addition of the tracelog

Your error is that you provided two arguments to create a Node:

```<code>self.start = Node(start[0], start[1])
</code>```

But its __init__ method expects none to be passed:

```<code>class Node:

    def __init__(self):
</code>```

Body:
import time, timeit, random, pygame, sys
from math import *
import numpy as np

XDIM = 1000 #window length
YDIM = 1200 #window breadth

WINSIZE = [XDIM, YDIM]
EPSILON = 7.0 #threshold
NUMNODES = 10000
GOAL_RADIUS = 10
MIN_DISTANCE_TO_ADD = 1.0 #incremental distance
GAME_LEVEL = 1

RANDOM_COUNT = 10000

pygame.init()
fpsClock = pygame.time.Clock()

#screen parameters and variable
screen = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('Q-learning')
white = 255, 240, 200
black = 20, 20, 40
red = 255, 0, 0
blue = 0, 255, 0
green = 0, 0, 255
cyan = 0,255,255

class Node:

    def __init__(self):
        self.x = x
        self.y = y
        self.cost = 0.0
        self.parent = None
        self.children = set()

class RRT(__Q_table):

    def __init__(self, start, goal,
                 obstacleList,  incremental_dist = 15.0,
                 learning_rate=20, max_iterations = 2000, randArea= None):

        self.start = Node(start[0], start[1])
        self.end   = Node(goal[0], goal[1])
        self.Xrand = randArea[0]
        self.Yrand = randArea[1]
        self.margin = incremental_distance
        self.learning_rate = learning_rate
        self.obstacleList = obstacleList
        self.max_iterations = max_iterations

    def planning(self, animation = True):

        self.NodeList = {0 : self.start}
        i=0

        while True:
            print(i)
        if set(self.start).intersection(obstacleList) == None:
            self.NodeList.append(self.start)

            print(self.NodeList)

        rnd = self.get_random_point()
        nearest_index = self.GetNearestListIndex(rnd)
        new_node = self.steer(rnd, nearest_index)

        if self.Collision_check(new_node, self.obstacleList):

            near_indices = self.find_near_nodes(new_node, 5)
            new_node     = self.choose_parent(new_node, near_indices)
            self.nodeList[i+100] = new_node
            self.rewire(i+100, new_node, near_indices)
            self.nodeList[new_node.parent].children.add(i+100)

            if len(self.NodeList) > self.max_iterations:
                leaves = [keys for key, node in self.NodeList.items]
                if len(leaves) > 1:
                    index = leaves[random.randint(0, len(leaves)-1)]
                    self.NodeList[self.NodeList[index].paresnt].children.discard(index)
                    self.NodeList.pop(index)
                else:
                    leaves = [key for key, node in self.NodeList.items() if len(node.children)==0]
                    index = leaves[random.randint(0, len(leaves) -1)]
                    self.NodeList[self.NodeList[index].parent].children.discard(index)
                    self.NodeList.pop(index)

            if animation == True:
                self.DrawGraph(rnd)

            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        self.obstacleList.append((event.pos[0], event.pos[1], 30, 30))
                        self.path_validation()
                    elif event.button == 3:
                        self.end.x = event.pos[0]
                        self.end.y = event.pos[1]
                        self.path_validation()

    def path_validation(self):

        lastIndex = self.get_the_best_last_index()
        if lastIndex and set(lastIndex).intersection(obstacleList) == None:
            while self.NodeList[lastIndex].parent is not None:
                nodeIndex = lastIndex
                lastIndex = self.NodeList[lastIndex].parent

                dx = self.NodeList[nodeIndex].x - self.NodeList[lastIndex].x
                dy = self.NodeList[nodeIndex].y - self.NodeList[lastIndex].y
                d = math.sqrt.atan2(dx**2 + dy**2)
                theta = math.atan2(dy, dx)
                if not self.check_collision_extend(self.NodeList[lastIndex].x,self.NodeList[lastIndex].y, theta, d):
                    self.NodeList[lastIndex].children.discard(nodeIndex)
                    self.eliminate_branch(nodeIndex)

    def eliminate_brach(self, nodeIndex):
        safenodesList = []
        if set(nodeIndex).intersection(obstacleList) == None:
            safenodesList.append(nodeIndex)
        for not_safe in safenodesList[nodeIndex].children:
            self.eliminate_branch(not_safe)
        self.NodeList.pop(nodeIndex)

    def choose_parent(self,new_node,nearest_index):
        if len(nearest_index) == 0:
            return new_node

        if Current_point == nearest_index and self.CollisionCheck(new_node, obstacleList):

            Current_point = new_node
            return Current_point

        distanceList = []
        for i in near_indices:
            dx = new_node.x - self.NodeList[i].x
            dy = new_node.y - self.NodeList[i].y
            d = math.sqrt(dx **2 + dy **2)
            theta = math.atan2(dy, dx)
            if self.check_collision_extend(self.NodeList[i].x, self.NodeList[i].y, theta, d):
                distanceList.append(self.NodeList[i].cost + d)
            else:
                distanceList.append(float("inf"))

        minimum_cost = min(distanceList)
        minimum_index = near_indices[distacelist.index(minimum_cost)]

        if minimum_cost == float("inf"):
            print("minimum_cost is INFINITE")
            return Current_point

        Current_point.cost = minimum_cost
        Current_point.parent = minimum_index

        Current_point_with_maximum_Q_value = self.max_Q_nextvalue(Current_point)

        return Current_point.cost, Current_point.parent, Current_point_with_maximum_Q_value

    def steer(self, rnd, nearest_index):

        nearest_node = self.NodeList[nearest_index]
        theta = math.atan2(rnd[1] - nearest_node.y, rnd[0] - nearest_node.x)
        new_node = Node(nearest_node.x , nearest_node.y)
        new_node.x += incremental_distance * math.cos(theta)
        new_node.y += incremental_distance * math.sin(theta)

        new_node.cost = nearest_node.cost + incremental_distance
        new_node.parent = nearest_index
        return new_node

    def get_random_point(self, Current_point=None):

        self.Current_point = Current_point
        if random.randint(0, 100) > self.learning_rate:
            rnd = [random.uniform(0, Xrand), random.uniform(0, yrand)]

        elif random.randint(0, 100) <= RANDOM_COUNT:
            Current_point = max_Q_action(Current_point)
            rnd = random_action(Current_point)
        else:
            rnd = [self.end.x, self.end.y]
        return rnd

    def get_best_last_index(self):

        disglist = [(key, self.calc_dist_to_goal(node.x, node.y)) for key, node in self.NodeList.items()]
        goal_indices = [key for key, distance in disglist if distance <= self.margin]

        if len(goal_indices) == 0:
            return None

        minimum_cost = min([self.NodeList[key].cost for key in goal_indices])
        for i in goal_indices:
            if self.NodeList[i].cost == minimum_cost:
                return i

        return None

    def gen_final_course(self, goal_indices):
        path = [[self.end.x, self.end.y]]
        while self.NodeList[goal_indices].parent is not None:
            node = self.NodeList[goal_indices]
            path.append([node.x, node.y])
            goal_indices = node.parent
        path.append([self.start.x, self.start.y])
        return path

    def calc_dist_to_goal(self, x, y):
        return np.linalg.norm([x - self.end.x, y - self.end.y])

    def find_near_nodes(self, new_node, value):
        r = self.margin * value

        distanceList = np.subtract( np.array([ (node.x, node.y) for node in self.NodeList.values() ]), (new_node.x,new_node.y))**2
        distanceList = np.sum(distanceList, axis=1)
        near_indices = np.where(distanceList <= r ** 2)
        near_indices = np.array(list(self.NodeList.keys()))[near_indices]

        return nearinds

    def rewire(self, newNodeInd, new_node, near):
        nnode = len(self.NodeList)
        for i in nearinds:
            nearNode = self.nodeList[i]

            dx = new_node.x - nearNode.x
            dy = new_node.y - nearNode.y
            d = math.sqrt(dx ** 2 + dy ** 2)

            scost = new_node.cost + d

            if near_node.cost > scost:
                theta = math.atan2(dy, dx)
                if self.check_collision_extend(nearNode.x, nearNode.y, theta, d):
                    self.NodeList[nearNode.parent].children.discard(i)
                    nearNode.parent = newNodeInd
                    nearNode.cost = scost
                    new_node.children.add(i)

    def check_collision_extend(self, nix, niy, theta, d):

        tmpNode = Node(nix,niy)

        for i in range(int(d/5)):
            tmpNode.x += 5 * math.cos(theta)
            tmpNode.y += 5 * math.sin(theta)
            if not self.CollisionCheck(tmpNode, self.obstacleList):
                return False

        return True

    def DrawGraph(self, rnd=None):

        screen.fill((255, 255, 255))
        for node in self.NodeList.values():
            if node.parent is not None:
                pygame.draw.line(screen,(0,255,0),[self.NodeList[node.parent].x,self.NodeList[node.parent].y],[node.x,node.y])

        for node in self.NodeList.values():
            if len(node.children) == 0:
                pygame.draw.circle(screen, (255,0,255), [int(node.x),int(node.y)], 2)

        for(sx,sy,ex,ey) in self.obstacleList:
            pygame.draw.rect(screen,(0,0,0), [(sx,sy),(ex,ey)])

        pygame.draw.circle(screen, (255,0,0), [self.start.x, self.start.y], 10)
        pygame.draw.circle(screen, (0,0,255), [self.end.x, self.end.y], 10)

        lastIndex = self.get_best_last_index()
        if lastIndex is not None:
            path = self.gen_final_course(lastIndex)

            ind = len(path)
            while ind > 1:
                pygame.draw.line(screen,(255,0,0),path[ind-2],path[ind-1])
                ind-=1

        pygame.display.update()

    def Get_nearest_list_index(self, rnd):
        distanceList = np.subtract( np.array([ (node.x, node.y) for node in self.NodeList.values() ]), (rnd[0],rnd[1]))**2
        distanceList = np.sum(distanceList, axis=1)
        minimum_index = list(self.NodeList.keys())[np.argmin(distancelist)]
        return minimum_index

    def Collision_check(self, node, obstacleList):
        for(sx,sy,ex,ey) in obstacleList:
            sx,sy,ex,ey = sx+2,sy+2,ex+2,ey+2
            if node.x > sx and node.x < sx+ex:
                if node.y > sy and node.y < sy+ey:
                    return False

        return True

def main():
    print("start RRT path planning")

    obstacleList = [
        (400, 380, 400, 20),
        (400, 220, 20, 180),
        (500, 280, 150, 20),
        (0, 500, 100, 20),
        (500, 450, 20, 150),
        (400, 100, 20, 80),
        (100, 100, 100, 20)
    ]

    rrt = RRT(obstacleList = obstacleList, start =[10, 580], goal = [540, 150],
              randArea = [XDIM, YDIM])
    path = rrt.Planning(animation=show_animation)

if __name__ == '__main__':
    main()

The error is -

TypeError                                 Traceback (most recent call last)
<ipython-input-1-6e62c6da9819> in <module>
    531
    532 if __name__ == '__main__':
--> 533     main()
    534

<ipython-input-1-6e62c6da9819> in main()
    525
    526     rrt = RRT(obstacleList = obstacleList, start =[10, 580], goal = [540, 150],
--> 527               randArea = [XDIM, YDIM])
    528
    529     path = rrt.planning(animation=show_animation)

<ipython-input-1-6e62c6da9819> in __init__(self, start, goal, obstacleList, incremental_dist, learning_rate, max_iterations, randArea)
    249                  learning_rate=20, max_iterations = 2000, randArea= None):
    250
--> 251         self.start = Node(start[0], start[1])
    252         self.end   = Node(goal[0], goal[1])
    253         self.Xrand = randArea[0]

TypeError: init() takes 1 positional argument but 3 were given

I am trying to write a code for motion planning in python using pygame module. I encountered this error given above. I even tried reducing the parameters into the constructor init() but it did not work out.

Please note that here I am not trying to do inheritance.

Thanks

Body:
Replace

path = rrt.Planning(animation=show_animation)

With

path = rrt.planning(animation=show_animation)

Edit: after the addition of the tracelog

Your error is that you provided two arguments to create a Node:

self.start = Node(start[0], start[1])

But its __init__ method expects none to be passed:

class Node:

    def __init__(self):


问:
Write custom string value into SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall with Inno Setup
During installation, I'd like to write a custom string value into the automatically created registry key HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyApp.2020_is1

I tried to do this in the [Registry] section of my iss script but it seems to be ignored.

```<code>Root: HKLM; Subkey: "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#MyAppName}.{#MyAppVersion}_is1"; ValueData: "some tag"; Flags: uninsdeletekey; ValueType: string; ValueName: "CustomTag"
</code>```

Is this generally discouraged or am I missing something particular?
I do have PrivilegesRequired=admin in the [Setup] section.

With the possibility to install multiple builds of my app side-by-side, I want to give the user the possibility to add a descriptive tag so that they can identify the build not only via build number but also the tag.

As I'm searching the registry for previous builds anyways, I was trying to add a custom value into the uninstall key instead of having to reference another key to find the custom tag.

答:
The Uninstall entry is created as one of the last steps of the installation. So also after the [Registry] section is processed. Check the Installation order. And when the entry is created, its previous contents is completely removed, including your some tag value.

As @Bill_Stewart already commented, the correct way is to use SetPreviousData/GetPreviousData.

If you really wanted to use your own custom code to write the entry, you will have to do it from Pascal Script in CurStepChanged(ssPostInstall) event (triggered after the Uninstall entry is created).

If you want to allow users to distinguish the installation, the tag must go to AppName or AppVerName or UninstallDisplayName.

If you need to allow parallel installations, the installations must have different AppId – which is a part of the uninstaller key name, so no additional tag should be needed.

Body:
During installation, I'd like to write a custom string value into the automatically created registry key HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyApp.2020_is1

I tried to do this in the [Registry] section of my iss script but it seems to be ignored.

Root: HKLM; Subkey: "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{#MyAppName}.{#MyAppVersion}_is1"; ValueData: "some tag"; Flags: uninsdeletekey; ValueType: string; ValueName: "CustomTag"

Is this generally discouraged or am I missing something particular?
I do have PrivilegesRequired=admin in the [Setup] section.

With the possibility to install multiple builds of my app side-by-side, I want to give the user the possibility to add a descriptive tag so that they can identify the build not only via build number but also the tag.

As I'm searching the registry for previous builds anyways, I was trying to add a custom value into the uninstall key instead of having to reference another key to find the custom tag.


问:
Powershell script for
I have Windows Server 2016 Datacenter (64 bit) as a File Server (contains several Shared folder & subfolders).

I want to make a list OR export user Folder Structure along with permissions ( Read, Modify, Full .. etc..)

I tried with below PS script but I am getting an error message with I have mentioned after the script.

Powershell

```<code>$FolderPath = dir -Directory -Path "E:\Project Folders\#Folder_Name" -Recurse -Force
$Report = @()
Foreach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    foreach ($Access in $acl.Access)
    {
        $Properties = [ordered]@{'FolderName'=$Folder.FullName;'AD Group or User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
        $Report += New-Object -TypeName PSObject -Property $Properties
    }
}
$Report | Export-Csv -path "C:\Folder Permissions\Folder Name.csv"
</code>```

Error:

dir : Access to the path 'E:\Project Folders**Folder Path**\New folder' is denied. At C:\Users\Administrator\Documents\PS Script**File Name**.ps1:1 char:15 + ... olderPath = dir -Directory -Path "E:\Project Folders**Folder Name**" -Re ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : PermissionDenied: (E:\Project Fold...ngar\New folder:String) [Get-Child    Item], UnauthorizedAccessException     + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Please help me out!

Thanks in Advance

答:
As noted by the other comments.

This is not a PowerShell error/issue, it is a permissions one. The same thing can/will happen if you say you did this use case on the Windows folder tree.

Since you know this will happen, either fix the permissions on the tree you are working on or do this.

```<code>Get-ChildItem -Directory -Path 'C:\Windows\System32' -Recurse -ErrorAction SilentlyContinue
</code>```

or if you want to just stop when a path fails.

```<code># Treat non-terminating erros as terminating
$RootFolderUnc = 'C:\Windows\System32'

Try {Get-ChildItem -Directory -Path $RootFolderUnc -Recurse -ErrorAction Stop}
Catch [System.UnauthorizedAccessException]
{
    Write-Warning -Message "$env:USERNAME. You do not have permissions to view this path."
    $_.Exception.Message
}
</code>```

Title: Powershell script for

Body:
I have Windows Server 2016 Datacenter (64 bit) as a File Server (contains several Shared folder & subfolders).

I want to make a list OR export user Folder Structure along with permissions ( Read, Modify, Full .. etc..)

I tried with below PS script but I am getting an error message with I have mentioned after the script.

Powershell

$FolderPath = dir -Directory -Path "E:\Project Folders\#Folder_Name" -Recurse -Force
$Report = @()
Foreach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    foreach ($Access in $acl.Access)
    {
        $Properties = [ordered]@{'FolderName'=$Folder.FullName;'AD Group or User'=$Access.IdentityReference;'Permissions'=$Access.FileSystemRights;'Inherited'=$Access.IsInherited}
        $Report += New-Object -TypeName PSObject -Property $Properties
    }
}
$Report | Export-Csv -path "C:\Folder Permissions\Folder Name.csv"

Error:

dir : Access to the path 'E:\Project Folders**Folder Path**\New folder' is denied. At C:\Users\Administrator\Documents\PS Script**File Name**.ps1:1 char:15 + ... olderPath = dir -Directory -Path "E:\Project Folders**Folder Name**" -Re ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : PermissionDenied: (E:\Project Fold...ngar\New folder:String) [Get-Child    Item], UnauthorizedAccessException     + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

Please help me out!

Thanks in Advance

Body:
As noted by the other comments.

This is not a PowerShell error/issue, it is a permissions one. The same thing can/will happen if you say you did this use case on the Windows folder tree.

Since you know this will happen, either fix the permissions on the tree you are working on or do this.

Get-ChildItem -Directory -Path 'C:\Windows\System32' -Recurse -ErrorAction SilentlyContinue

or if you want to just stop when a path fails.

# Treat non-terminating erros as terminating
$RootFolderUnc = 'C:\Windows\System32'

Try {Get-ChildItem -Directory -Path $RootFolderUnc -Recurse -ErrorAction Stop}
Catch [System.UnauthorizedAccessException]
{
    Write-Warning -Message "$env:USERNAME. You do not have permissions to view this path."
    $_.Exception.Message
}