问:
Lodash _forEach breaks typeguard in TypeScript

Background

Creating a variable notifications that I want to be false when I have no data, otherwise an array of objects. So I did a union type: let notifications: object[] | boolean = []; Fine except when I do notifications.push(notification); I got

```<code>Property 'push' does not exist on type 'boolean | object[]'.
  Property 'push' does not exist on type 'true'.
</code>```

Right, TS isn't sure that it's an array. I'll let it know. notifications = []; Same error. Bunch more digging, realize the guard is working fine, it's only when I have my .push inside lodash's _forEach that I get the error.

Current state:

```<code>let notifications: object[] | boolean;

if (noNotifications) {
  notifications = false;
} else {
  notifications = [];
  _forEach(notificationsObj, function (notification, type) { // Culprit
    notification['type'] = type;
    notifications.push(notification); // <-- TS error on push
  });
}
return notifications;
</code>```

What I've tried

A bunch of different ways of type guarding. Don't understand the reason _forEach is breaking it, so not sure what to try next.

Question

Is is possible to  use push on my variable inside _forEach? If so, how?

答:
TypeScript doesn't understand _forEach well enough to know that notifications will not be reassigned before it runs the code in the callback.  Since notifications is not const, TypeScript thinks it is possible for it to be reassigned.  There are many tradeoffs in how TypeScript does its type-based control flow analysis; type narrowing propagating into closures is hard.  Since you can't really get TypeScript to follow the control flow, you have a few options:

The easiest is to just assert that notifications is an array when you do the push():

```<code>_forEach(notificationsObj, function(notification, type) { // Culprit
  notification['type'] = type;
  (notifications as object[]).push(notification); // assertion
});
</code>```

This assertion is you telling the compiler not to worry.

To get a more type safety at the expense of a little runtime assignment shuffling, introduce a const variable and then assign that to notifications:

```<code>const notificationsArray: object[] | boolean = []; // cannot be reassigned
_forEach(notificationsObj, function(notification, type) { // Culprit
  notification['type'] = type;
  notificationsArray.push(notification); // no error
});
notifications = notificationsArray; // assignment works
</code>```

Here TypeScript knows that notificationsArray can never be reassigned, so its type stays narrowed object[] all the way into the callback.  Then you can assign its value to notifications.  (You could also just declare notificationsArray to just be type object[] and leave off | boolean.  I was just showing that const affects the narrowing.)

Hope you understand and that one of those solutions works for you.  Good luck!

Body:
Background

Creating a variable notifications that I want to be false when I have no data, otherwise an array of objects. So I did a union type: let notifications: object[] | boolean = []; Fine except when I do notifications.push(notification); I got

Property 'push' does not exist on type 'boolean | object[]'.
  Property 'push' does not exist on type 'true'.

Right, TS isn't sure that it's an array. I'll let it know. notifications = []; Same error. Bunch more digging, realize the guard is working fine, it's only when I have my .push inside lodash's _forEach that I get the error.

Current state:

let notifications: object[] | boolean;

if (noNotifications) {
  notifications = false;
} else {
  notifications = [];
  _forEach(notificationsObj, function (notification, type) { // Culprit
    notification['type'] = type;
    notifications.push(notification); // <-- TS error on push
  });
}
return notifications;

What I've tried

A bunch of different ways of type guarding. Don't understand the reason _forEach is breaking it, so not sure what to try next.

Question

Is is possible to  use push on my variable inside _forEach? If so, how?

Body:
TypeScript doesn't understand _forEach well enough to know that notifications will not be reassigned before it runs the code in the callback.  Since notifications is not const, TypeScript thinks it is possible for it to be reassigned.  There are many tradeoffs in how TypeScript does its type-based control flow analysis; type narrowing propagating into closures is hard.  Since you can't really get TypeScript to follow the control flow, you have a few options:

The easiest is to just assert that notifications is an array when you do the push():

_forEach(notificationsObj, function(notification, type) { // Culprit
  notification['type'] = type;
  (notifications as object[]).push(notification); // assertion
});

This assertion is you telling the compiler not to worry.

To get a more type safety at the expense of a little runtime assignment shuffling, introduce a const variable and then assign that to notifications:

const notificationsArray: object[] | boolean = []; // cannot be reassigned
_forEach(notificationsObj, function(notification, type) { // Culprit
  notification['type'] = type;
  notificationsArray.push(notification); // no error
});
notifications = notificationsArray; // assignment works

Here TypeScript knows that notificationsArray can never be reassigned, so its type stays narrowed object[] all the way into the callback.  Then you can assign its value to notifications.  (You could also just declare notificationsArray to just be type object[] and leave off | boolean.  I was just showing that const affects the narrowing.)

Hope you understand and that one of those solutions works for you.  Good luck!


来源: stackexchange

问:
How do you get an unsigned long out of a string?
What's the safest and best way to retrieve an unsigned long from a string in C++?

I know of a number of possible methods.

First, converting a signed long taken from atol.

```<code>char *myStr; // Initalized to some value somehow.
unsigned long n = ((unsigned)atol(myStr));
</code>```

The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain?  What does atol retrieve?

The next possibility is to use strtoul.

```<code>char *myStr; // Initalized to some value somehow.
unsigned long n = strtoul(myStr, 0, 10);
</code>```

However, this is a little over complicated for my needs.  I'd like a simple function, string in, unsigned long base 10 out.  Also, the error handling leaves much to be desired.

The final possibility I have found is to use sscanf.

```<code>char *myStr; // Initalized to some value somehow.
unsigned long n = 0;
if(sscanf(myStr, "%lu", n) != 1) {
    //do some error handling
}
</code>```

Again, error handling leaves much to be desired, and a little more complicated than I'd like.

The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX.

My question is, what are the other options that my google-fu has failed to find?  Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure?

My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.

答:
Use "atol" in-built std function

For example std::string input = "1024";

std::atol(input.c_str());

Atol expect parameter to be of type c string, so c_str() does it that for you.

ContentLicense: CC BY-SA 2.5

Body:
What's the safest and best way to retrieve an unsigned long from a string in C++?

I know of a number of possible methods.

First, converting a signed long taken from atol.

char *myStr; // Initalized to some value somehow.
unsigned long n = ((unsigned)atol(myStr));

The obvious problem with this is, what happens when the value stored in myStr is larger than a signed long can contain?  What does atol retrieve?

The next possibility is to use strtoul.

char *myStr; // Initalized to some value somehow.
unsigned long n = strtoul(myStr, 0, 10);

However, this is a little over complicated for my needs.  I'd like a simple function, string in, unsigned long base 10 out.  Also, the error handling leaves much to be desired.

The final possibility I have found is to use sscanf.

char *myStr; // Initalized to some value somehow.
unsigned long n = 0;
if(sscanf(myStr, "%lu", n) != 1) {
    //do some error handling
}

Again, error handling leaves much to be desired, and a little more complicated than I'd like.

The remaining obvious option is to write my own either a wrapper around one of the previous possibilities or some thing which cycles through the string and manually converts each digit until it reaches ULONG_MAX.

My question is, what are the other options that my google-fu has failed to find?  Any thing in the C++ std library that will cleanly convert a string to an unsigned long and throw exceptions on failure?

My apologies if this is a dupe, but I couldn't find any questions that exactly matched mine.

ContentLicense: CC BY-SA 3.0


问:
Browsers does not reflects updates in the code
While working on HTML, CSS (and more) like changing the code and refreshing the browser, after updating the files (local or remote [ftp]) and refreshing the browser won't reflect the changes.

Many browses suffer from this problem. Firefox, Safari and even Opera (Opera GX); any updates or changes to the remote or local files won't be reflected. This problem is not new, it's been around for decades!

Even if I upload the new file to the server and refresh in FF it is not showing the new code styles, I have emptied cookies. I am confused; any ideas?

答: Yes. That's because of the browser cache. Better clear the cache and refresh the page. I use a private window or icognito as in Chrome so its not cached. Make the change and refresh the page. Your changes should have been reflected.</p>

ContentLicense: CC BY-SA 4.0


问:
Fusebox layout files not refreshing
I have a live site in fusebox 5.5 "production" mode.

No matter, what I do, I can not get the application to register any changes I make to a layout file. I have tried all the different fusebox reload parameters and they do work for all files, except the layout file.

For example, I delete the "parsed" folder and reload fusebox with the FB parameters in the url. I then see all the parsed files being recreated, but the layout does not refresh.

Also, if I delete the layout files and reload Fusebox, it still works without error!!!!!?? Nothing I do registers the changes to the layout files.

The only thing that works, is restarting the Railo / Coldfusion service.
Then it picks up the changes.

Why is this happening and how do I get my application to pick up the layout changes without restarting the service??

答: Is the page being cached in the CF Administrator?  Try clearing template cache and see if that works.</p>

Title: Fusebox layout files not refreshing


问:
Unreal Engine 4.18 Set IOS icons [IOS11]
In the project settings I have replaced all the default Unreal icons with my custom ones of the correct sizes, but yet when I build and launch to my phone the default icon is still showing.

Not sure what I am missing here, any help would be amazing. I am using 4.18 so maybe it could be something with the version and it not being very friendly to IOS11?

Thanks!

答: This was just a bug in Unreal Engine 4.18.0, with the new patch 4.18.1, this problem has been fixed.</p>


问:
Android Layout Weight not working with relative layout

I am trying to implement layout weight for the first time, a bit I tried with linear layout it works good, but when I tried with relative and linear layout something went wrong. What is wrong here?

My XML File

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >

<RelativeLayout
    android:id="@+id/Rlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="45" >

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:spacing="4dip" >
    </Gallery>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/Rlayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="10"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />

    <ImageView
        android:id="@+id/ImageView02"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />
</RelativeLayout>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navbar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="45"
    android:background="@drawable/button1"
    android:orientation="horizontal"
    android:weightSum="100" >

    <Button
        android:id="@+id/makerback"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerback" />

    <Button
        android:id="@+id/makerphoto"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerphoto" />

    <Button
        android:id="@+id/makerselves"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerselves" />

    <Button
        android:id="@+id/makerskins"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerskins" />

    <Button
        android:id="@+id/makersave"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makersave" />
</LinearLayout>

</LinearLayout>
</code>```

I need to achieve the above image:

答:
You can implement it with traditional layout hierarchy but you should be aware of nested layout's negative impact on UI performance. Read Understanding the performance benefits of ConstraintLayout for reference.

To flatten your layout and use percentage values you can use ConstraintLayout's guidelines:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/ImageView02"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:spacing="4dip"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/horGuideline1" />

    <Button
        android:id="@+id/makerback"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerphoto"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline2"
        app:layout_constraintStart_toEndOf="@+id/verGuideline1"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerselves"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline3"
        app:layout_constraintStart_toEndOf="@+id/verGuideline2"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerskins"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline4"
        app:layout_constraintStart_toEndOf="@+id/verGuideline3"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makersave"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/verGuideline4"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <android.support.constraint.Guideline
        android:id="@+id/horGuideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/horGuideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.9" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.4" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I am trying to implement layout weight for the first time, a bit I tried with linear layout it works good, but when I tried with relative and linear layout something went wrong. What is wrong here?

My XML File

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/Linearlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="100" >

<RelativeLayout
    android:id="@+id/Rlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="45" >

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:spacing="4dip" >
    </Gallery>
</RelativeLayout>

<RelativeLayout
    android:id="@+id/Rlayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="10"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />

    <ImageView
        android:id="@+id/ImageView02"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="fitXY" />
</RelativeLayout>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navbar"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="45"
    android:background="@drawable/button1"
    android:orientation="horizontal"
    android:weightSum="100" >

    <Button
        android:id="@+id/makerback"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerback" />

    <Button
        android:id="@+id/makerphoto"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerphoto" />

    <Button
        android:id="@+id/makerselves"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerselves" />

    <Button
        android:id="@+id/makerskins"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makerskins" />

    <Button
        android:id="@+id/makersave"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_weight="20"
        android:background="@drawable/makersave" />
</LinearLayout>

</LinearLayout>

I need to achieve the above image:

Body:
You can implement it with traditional layout hierarchy but you should be aware of nested layout's negative impact on UI performance. Read Understanding the performance benefits of ConstraintLayout for reference.

To flatten your layout and use percentage values you can use ConstraintLayout's guidelines:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/ImageView01"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/ImageView02"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Gallery
        android:id="@+id/Gallery01"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:spacing="4dip"
        app:layout_constraintBottom_toTopOf="@+id/horGuideline2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/horGuideline1" />

    <Button
        android:id="@+id/makerback"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerphoto"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline2"
        app:layout_constraintStart_toEndOf="@+id/verGuideline1"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerselves"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline3"
        app:layout_constraintStart_toEndOf="@+id/verGuideline2"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makerskins"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/verGuideline4"
        app:layout_constraintStart_toEndOf="@+id/verGuideline3"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <Button
        android:id="@+id/makersave"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/verGuideline4"
        app:layout_constraintTop_toTopOf="@+id/horGuideline2" />

    <android.support.constraint.Guideline
        android:id="@+id/horGuideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.1" />

    <android.support.constraint.Guideline
        android:id="@+id/horGuideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.9" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.2" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.4" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.6" />

    <android.support.constraint.Guideline
        android:id="@+id/verGuideline4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.8" />

</android.support.constraint.ConstraintLayout>


问:
Adding @google-cloud/logging in typescript functions project gives error
EDIT:
for others with the same problem - using const Logging: any = require('@google-cloud/logging') together with var logger = Logging() in the body of the class worked like a charm!

Remember to use var logger = Logging() to instantiate the logger library. Otherwise you will still get the logger.log is not a function!

Original post

I've got a firebase functions project, written in typescript - transpiled with webpack. I'm currently trying to implement the @google-cloud/logging library, but I'm having issues. It comes out saying

Could not find a declaration file for module "google-cloud/logging". Try npm install @types/@google-cloud/logging if it exists or add a new declaration (.d.ts) file containing declare module '@google-cloud/logging';

I've tried adding the library the following ways:

```<code>import * as Logging from '@google-cloud/logging';
import * as logging from '@google-cloud/logging';
import { Logging } from '@google-cloud/logging';
</code>```

But I'm still getting this error. Trying to run a function which is using "logging" results in

logging.log is not a function

I have even tried the javascript way of requiring the library, still with no success.

My tsconfig.json:

```<code>{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "./",
        "noImplicitAny": true
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}
</code>```

I've read that some people had success by adding a "d.ts" file to the project manually, though I did not understand much of it. Here is the link to the article in stack overflow - Importing non-typescript module in typescript

How might I go about adding the library in a typescript project?

I can provide more details if needed. This was what I could think of including.

答:
There is not yet type definitions for @google-cloud/logging. So you need to provide some !
In the meantime, you can do

```<code>const Logging: any = require('@google-cloud/logging')
</code>```

If you have @types/node installed and target nodejs or if you target the browser but use "moduleResolution": "CommonJS" (you also need to provide node typefs).

Otherwise, you can use

```<code>import * as Logging from '@google-cloud/logging'
</code>```

But in that case you need to declare the types for this module

```<code>// logging.d.ts
declare module '@google-cloud/logging' {

  interface LogConfig {
    removeCircular: boolean
  }

  class Entry {
    metadata: object
    data: object
    constructor (metadata: object | null | undefined, data: object | string)
    constructor (data: object | string)
    toJSON (options?: LogConfig): any
  }

  interface WriteOptions {
    gaxOptions: object
    labels: object[]
    resource: object
  }

  type LogWriteCallback = (err: Error | null, apiResponse: object) => void
  type DeleteLogCallback = (err: Error | null, apiResponse: object) => void

  type LogWriteResponse = object[]
  type DeleteLogResponse = object[]

  type EntryArg = Entry | Entry[]

  class Log {
    constructor (logging: Logging, name: string, options: LogConfig)
    alert (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    critical (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    debug (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    emergency (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    info (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    notice (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    warning (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    error (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    write (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    delete (gaxOptions: object): Promise<DeleteLogResponse>
    delete (gaxOptions: object, callback?: DeleteLogCallback): Promise<DeleteLogResponse>
    delete (callback?: DeleteLogCallback): Promise<DeleteLogResponse>
  }

  interface ClientConfig {
    projectId?: string
    keyFilename?: string
    email?: string
    credentials?: {
      client_email: string
      private_key: string
    }
    autoRetry?: boolean
    maxRetries?: number
    promise?: Function
  }

  class Logging {
    constructor (options: ClientConfig)
    log (name: string, options?: LogConfig): Log
    entry (resource: object | string | null | undefined, data: object | string): Entry
  }
  export = Logging
}
</code>```

This definition is just a draft and a lot of functions are missing, but I guess it's a necessary first step :-)

Body:
EDIT:
for others with the same problem - using const Logging: any = require('@google-cloud/logging') together with var logger = Logging() in the body of the class worked like a charm!

Remember to use var logger = Logging() to instantiate the logger library. Otherwise you will still get the logger.log is not a function!

Original post

I've got a firebase functions project, written in typescript - transpiled with webpack. I'm currently trying to implement the @google-cloud/logging library, but I'm having issues. It comes out saying

Could not find a declaration file for module "google-cloud/logging". Try npm install @types/@google-cloud/logging if it exists or add a new declaration (.d.ts) file containing declare module '@google-cloud/logging';

I've tried adding the library the following ways:

import * as Logging from '@google-cloud/logging';
import * as logging from '@google-cloud/logging';
import { Logging } from '@google-cloud/logging';

But I'm still getting this error. Trying to run a function which is using "logging" results in

logging.log is not a function

I have even tried the javascript way of requiring the library, still with no success.

My tsconfig.json:

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "outDir": "./",
        "noImplicitAny": true
    },
    "include": [
        "src/**/*.ts"
    ],
    "exclude": [
        "node_modules"
    ]
}

I've read that some people had success by adding a "d.ts" file to the project manually, though I did not understand much of it. Here is the link to the article in stack overflow - Importing non-typescript module in typescript

How might I go about adding the library in a typescript project?

I can provide more details if needed. This was what I could think of including.

Body:
There is not yet type definitions for @google-cloud/logging. So you need to provide some !
In the meantime, you can do

const Logging: any = require('@google-cloud/logging')

If you have @types/node installed and target nodejs or if you target the browser but use "moduleResolution": "CommonJS" (you also need to provide node typefs).

Otherwise, you can use

import * as Logging from '@google-cloud/logging'

But in that case you need to declare the types for this module

// logging.d.ts
declare module '@google-cloud/logging' {

  interface LogConfig {
    removeCircular: boolean
  }

  class Entry {
    metadata: object
    data: object
    constructor (metadata: object | null | undefined, data: object | string)
    constructor (data: object | string)
    toJSON (options?: LogConfig): any
  }

  interface WriteOptions {
    gaxOptions: object
    labels: object[]
    resource: object
  }

  type LogWriteCallback = (err: Error | null, apiResponse: object) => void
  type DeleteLogCallback = (err: Error | null, apiResponse: object) => void

  type LogWriteResponse = object[]
  type DeleteLogResponse = object[]

  type EntryArg = Entry | Entry[]

  class Log {
    constructor (logging: Logging, name: string, options: LogConfig)
    alert (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    critical (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    debug (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    emergency (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    info (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    notice (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    warning (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    error (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    write (entry: EntryArg, options?: WriteOptions, callback?: LogWriteCallback): Promise<LogWriteResponse>
    delete (gaxOptions: object): Promise<DeleteLogResponse>
    delete (gaxOptions: object, callback?: DeleteLogCallback): Promise<DeleteLogResponse>
    delete (callback?: DeleteLogCallback): Promise<DeleteLogResponse>
  }

  interface ClientConfig {
    projectId?: string
    keyFilename?: string
    email?: string
    credentials?: {
      client_email: string
      private_key: string
    }
    autoRetry?: boolean
    maxRetries?: number
    promise?: Function
  }

  class Logging {
    constructor (options: ClientConfig)
    log (name: string, options?: LogConfig): Log
    entry (resource: object | string | null | undefined, data: object | string): Entry
  }
  export = Logging
}

This definition is just a draft and a lot of functions are missing, but I guess it's a necessary first step :-)


问:
How to link with Python3 Libs with cmake?
I have Python3 installed via brew install python3. However, cmake cannot find PythonLibs 3. Here's the header of my CMakeLists.txt.

```<code>cmake_minimum_required(VERSION 3.0)
find_package(PythonLibs 3 REQUIRED)
</code>```

When I ran cmake, I got this error message

```<code>Could NOT find PythonLibs: Found unsuitable version "2.7.6", but required is at least "3" (found /usr/lib/libpython2.7.dylib)
</code>```

Not sure what I did wrong.

答:
Another reason for this is that CMake can't ever find Python 3 when it is installed from brew on OSX. It looks like the CMake devs know that FindPythonLibs sucks and have a ticket to revamp it but it doesn't look like it will happen any time soon.

I believe the Python interpreter itself knows where its libraries and headers are so I think the best thing to do would be to run it to find out. To get the path to the Python interpreter I would force the user to specify it manually. One of the big issues with Python is that lots of software includes its own copy so you'll end up with 5 copies of it on your system. The chance of picking up the wrong one is just too high. Get the user to specify the correct one.

Body:
I have Python3 installed via brew install python3. However, cmake cannot find PythonLibs 3. Here's the header of my CMakeLists.txt.

cmake_minimum_required(VERSION 3.0)
find_package(PythonLibs 3 REQUIRED)

When I ran cmake, I got this error message

Could NOT find PythonLibs: Found unsuitable version "2.7.6", but required is at least "3" (found /usr/lib/libpython2.7.dylib)

Not sure what I did wrong.


问:
Configuring SSO utilizing ADFS 2.0, SAML 2.0, and simpleSAMLphp
My knowledge of these systems is not large so please forgive me if I am asking dumb questions.

I hope to achieve the following:

Idp (AD FS 2.0) -> SAML 2.0 -> Sp (simpleSAMLphp)

*I don't need anything more fancy than to simply authenticate a user.

I have attempted to configure Windows Server 2008 with AD FS 2.0 (domain A) as an Identity provider and have it handle authentication requests from a service provider on a different domain (created using simpleSAMLphp (domain B)).

The AD FS 2.0 Management application allows me to add raw meta XML from the SP to configure the idp. And my SP has the facility to do the same. So I figure that If I setup the idp (AD FS 2.0) correctly then I will simple just have to make the SP interpret the metadata of the idp.

Currently I feel that I am close to a solution (but then again I am probably wrong!). Currently it seems everything is find right up to the point when the Idp asks for your login credentials, and I enter my credentials, it appears that the session has started, but I get a 'Not Authorized - HTTP Error 401. The requested resource requires user authentication.' message after entering the correct login credentials.

Could someone please explain how to fix this? or if it's quicker a step by step setup to make AD FS 2.0 authenticate using SAML 2.0 for simply authenticating a username and password.

Thankyou in advance for any hints!

答:
Have you established a claims provider trust within ADFS 2.0 management? Your system needs to accept claims-bearing tokens from a trusted claims provider. That is, whatever STS -- "Security Token Service" -- you have in front of your user repository. ADFS can both a "Relying Party" -- RP -- or a STS. You need both a relying party and a STS.

Check out Eugenio Pace's MSDN blog for more details:

http://blogs.msdn.com/b/eugeniop/archive/tags/federated+identity/


问:
How can I avoid having my R script printed every time I run it?
Suppose I have an R script:

```<code>library('nnet')
something <- runif(50);
print(something)
</code>```

When I run this script from the command line, it prints:

```<code>> library('nnet')
> something <- runif(5);
> print(something)
 [1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019
</code>```

I would like it to print only:

```<code>[1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019
</code>```

and I cannot figure out how to do this. sink("/dev/null") doesn't do anything, redirecting stderr manually doesn't do anything, and I can't find any useful information on this.

答:
For RStudio IDE (Version 1.1.383) in Windows:

Pressing Ctrl+Shift+Enter keys run entire script with echo (verbose)

Pressing Ctrl+Shift+S     keys run entire script without echo (non-verbose)

Body:
Suppose I have an R script:

library('nnet')
something <- runif(50);
print(something)

When I run this script from the command line, it prints:

> library('nnet')
> something <- runif(5);
> print(something)
 [1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019

I would like it to print only:

[1] 0.04665518 0.93574275 0.96387299 0.07410239 0.92834019

and I cannot figure out how to do this. sink("/dev/null") doesn't do anything, redirecting stderr manually doesn't do anything, and I can't find any useful information on this.


问:
How to integrate checking of readme in pytest
I use pytest in my .travis.yml to check my code.

I would like to check the README.rst, too.

I found readme_renderer via this StackO answer

Now I ask myself how to integrate this into my current tests.

The docs of readme_renderer suggest this, but I have not clue how to integrate this into my setup:

```<code>python setup.py check -r -s
</code>```

答:
So I implemented something but it does require some modifications. You need to modify your setup.py as below

```<code>from distutils.core import setup

setup_info = dict(
    name='so1',
    version='',
    packages=[''],
    url='',
    license='',
    author='tarun.lalwani',
    author_email='',
    description=''
)

if __name__ == "__main__":
    setup(**setup_info)
</code>```

Then you need to create a symlink so we can import this package in the test

```<code>ln -s setup.py setup_mypackage.py
</code>```

And then you can create a test like below

```<code># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import os
import unittest
from distutils.command.check import check
from distutils.dist import Distribution

import setup_mypackage

class Test(unittest.TestCase):
    def test_readme_rst_valid(self):
        dist = Distribution(setup_mypackage.setup_info)
        test = check(dist)
        test.ensure_finalized()
        test.metadata = True
        test.strict = True
        test.restructuredtext = True

        global issues
        issues = []

        def my_warn(msg):
            global issues
            issues += [msg]
        test.warn = my_warn

        test.check_metadata()
        test.check_restructuredtext()

        if len(issues) > 0:
            assert len(issues) == 0, "\n".join(issues)
</code>```

Running the test then I get

```<code>...
AssertionError: missing required meta-data: version, url
missing meta-data: if 'author' supplied, 'author_email' must be supplied too

Ran 1 test in 0.067s

FAILED (failures=1)
</code>```

This is one possible workaround that I can think of

Body:
I use pytest in my .travis.yml to check my code.

I would like to check the README.rst, too.

I found readme_renderer via this StackO answer

Now I ask myself how to integrate this into my current tests.

The docs of readme_renderer suggest this, but I have not clue how to integrate this into my setup:

python setup.py check -r -s

Body:
So I implemented something but it does require some modifications. You need to modify your setup.py as below

from distutils.core import setup

setup_info = dict(
    name='so1',
    version='',
    packages=[''],
    url='',
    license='',
    author='tarun.lalwani',
    author_email='',
    description=''
)

if __name__ == "__main__":
    setup(**setup_info)

Then you need to create a symlink so we can import this package in the test

ln -s setup.py setup_mypackage.py

And then you can create a test like below

# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function

import os
import unittest
from distutils.command.check import check
from distutils.dist import Distribution

import setup_mypackage

class Test(unittest.TestCase):
    def test_readme_rst_valid(self):
        dist = Distribution(setup_mypackage.setup_info)
        test = check(dist)
        test.ensure_finalized()
        test.metadata = True
        test.strict = True
        test.restructuredtext = True

        global issues
        issues = []

        def my_warn(msg):
            global issues
            issues += [msg]
        test.warn = my_warn

        test.check_metadata()
        test.check_restructuredtext()

        if len(issues) > 0:
            assert len(issues) == 0, "\n".join(issues)

Running the test then I get

...
AssertionError: missing required meta-data: version, url
missing meta-data: if 'author' supplied, 'author_email' must be supplied too

Ran 1 test in 0.067s

FAILED (failures=1)

This is one possible workaround that I can think of


问:
Comparing 40 million lines in a file with 6 million list items in Python
I have a file with 40 million entries in the form of:

```<code>#No Username
</code>```

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

```<code>import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()
</code>```

How can I improve the performance of this code?

答:
I see two obvious improvements: first, make usernames a set. Then, create a result list and write '\n'.join(resultlist) to file once.

```<code>import os

usernames = []

for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)

usernames = set(usernames)

f = open('/path/to/6 million','r')
resultlist = []
for l in f:
    l = l.split(' ')
    if (l[1] in usernames):
        resultlist.append(l[1])
f.close()

common=open('/path/to/filf','w')
common.write('\n'.join(resultlist) + '\n')
common.close()
</code>```

Edit: assuming all you want is to find the most common names:

```<code>usernames = set(os.listdir('/path/to/directory/with/usernames/'))
from collections import Counter

f = open('/path/to/6 million')
name_counts = Counter(line.split()[1] for line in f if line in usenames)
print name_counts.most_common()
</code>```

Edit2: Given the clarification, here's how to create a file that contains names common to the usernames in path and in the 6 million lines file:

```<code>import os
usernames = set(os.listdir('/path/to/directory/with/usernames/'))

f = open('/path/to/6 million')
resultlist = [line.split()[1] for line in f if line[1] in usernames]

common = open('/path/to/filf','w')
common.write('\n'.join(resultlist) + '\n')
common.close()
</code>```

Body:
I have a file with 40 million entries in the form of:

#No Username

And I have a list with 6 million items, where each item is a username.

I want to find the common usernames in the fastest way possible. Here’s what I’ve got so far:

import os
usernames=[]
common=open('/path/to/filf','w')
f=open('/path/to/6 million','r')
for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)
#noOfUsers=len(usernames)
for l in f:
    l=l.split(' ')
    if(l[1] in usernames):
        common.write(l[1]+'\n')
common.close()
f.close()

How can I improve the performance of this code?

Body:
I see two obvious improvements: first, make usernames a set. Then, create a result list and write '\n'.join(resultlist) to file once.

import os

usernames = []

for l in os.listdir('/path/to/directory/with/usernames/'):
    usernames.append(l)

usernames = set(usernames)

f = open('/path/to/6 million','r')
resultlist = []
for l in f:
    l = l.split(' ')
    if (l[1] in usernames):
        resultlist.append(l[1])
f.close()

common=open('/path/to/filf','w')
common.write('\n'.join(resultlist) + '\n')
common.close()

Edit: assuming all you want is to find the most common names:

usernames = set(os.listdir('/path/to/directory/with/usernames/'))
from collections import Counter

f = open('/path/to/6 million')
name_counts = Counter(line.split()[1] for line in f if line in usenames)
print name_counts.most_common()

Edit2: Given the clarification, here's how to create a file that contains names common to the usernames in path and in the 6 million lines file:

import os
usernames = set(os.listdir('/path/to/directory/with/usernames/'))

f = open('/path/to/6 million')
resultlist = [line.split()[1] for line in f if line[1] in usernames]

common = open('/path/to/filf','w')
common.write('\n'.join(resultlist) + '\n')
common.close()


问:
chartjs show dot point on hover over line chart
I am using Chartjs v.1.0.2 and trying to set a point dot only to appear on hover over chart. After it it should be removed. I have managed to show it, by changing the object value, but it is not fluid motion and it doesn't show point always. This also doesn't hide it on hover out.
How can it be fluid and hide when mouse is not over?

```<code>window.onload = function(){

        var ctx = $("#chart1").get(0).getContext("2d");
                var chart1 = new Chart(ctx).Line(data1, options);

                $("#chart1").hover(function(e) {
                    var activeBars = chart1.getPointsAtEvent(e);
                    activeBars[0].display = true;
//                    console.log(activeBars[0]);
                    chart1.update();
                 });

    };

    var data1 = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fillColor: "rgba(95,186,88,0.7)",
                    strokeColor: "rgba(95,186,88,1)",
                    pointColor: "rgba(95,186,88,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [65, 59, 80, 81, 56, 55, 40]
                }
            ]
    };

var options = {
    responsive: true,
    bezierCurve : false,
    scaleShowLabels: false,
    scaleFontSize: 0,
    pointDot : false,
    scaleBeginAtZero: true,
    scaleShowHorizontalLines: false,
    scaleShowVerticalLines: true,
    scaleGridLineColor : "rgba(232,232,232)",
    showTooltips: true,

    customTooltips: function (tooltip) {
        var tooltipEl = $('#chartjs-tooltip');

        if (!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }

        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);

        // split out the label and value and make your own tooltip here
        var parts = tooltip.text.split(":");
        var innerHtml = '<span>' + parts[0].trim() + '</span> : <span><b>' + parts[1].trim() + '</b></span>';
        tooltipEl.html(innerHtml);

        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }

};
</code>```

simplified fiddle

答:
Tested with Chart.js v2.6.0

Global setting will do the trick:

```<code>Chart.defaults.global.hover.intersect = false;
</code>```

Or directly in chart config:

```<code>options: {
  hover: {
    intersect: false;
  }
}
</code>```

And point settings for dataset.

initial color of the point should be transparent

hover color must be set to the desired color

e.g.

```<code>datasets: [{
  label: 'My First dataset',
  borderColor: 'rgb(255, 99, 132)',
  backgroundColor: 'rgb(255, 99, 132)',
  data: [10, 30, 46, 2, 8, 50, 0],
  fill: false,
  pointBorderColor: 'rgba(0, 0, 0, 0)',
  pointBackgroundColor: 'rgba(0, 0, 0, 0)',
  pointHoverBackgroundColor: 'rgb(255, 99, 132)',
  pointHoverBorderColor: 'rgb(255, 99, 132)'}],...
</code>```

window.onload = function() {
  const mode = 'index';
  const intersect = false;
  const config = {
    type: 'line',
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [{
        label: 'My First dataset',
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgb(255, 99, 132)',
        data: [10, 30, 46, 2, 8, 50, 0],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(255, 99, 132)',
        pointHoverBorderColor: 'rgb(255, 99, 132)',
      }, {
        label: 'My Second dataset',
        borderColor: 'rgb(54, 162, 235)',
        backgroundColor: 'rgb(54, 162, 235)',
        data: [7, 49, 46, 13, 25, 30, 22],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(54, 162, 235)',
        pointHoverBorderColor: 'rgb(54, 162, 235)',
      }]
    },
    options: {
      responsive: true,
      title: {
        display: true,
        text: 'Mode: index, intersect = false'
      },
      tooltips: {
        mode: 'index',
        intersect: intersect,
      },
      hover: {
        mode: mode,
        intersect: intersect
      },
    }
  };
  const ctx = document.getElementById('canvas').getContext('2d');
  const chart = new Chart(ctx, config);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script></code>```

Body:
I am using Chartjs v.1.0.2 and trying to set a point dot only to appear on hover over chart. After it it should be removed. I have managed to show it, by changing the object value, but it is not fluid motion and it doesn't show point always. This also doesn't hide it on hover out.
How can it be fluid and hide when mouse is not over?

window.onload = function(){

        var ctx = $("#chart1").get(0).getContext("2d");
                var chart1 = new Chart(ctx).Line(data1, options);

                $("#chart1").hover(function(e) {
                    var activeBars = chart1.getPointsAtEvent(e);
                    activeBars[0].display = true;
//                    console.log(activeBars[0]);
                    chart1.update();
                 });

    };

    var data1 = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fillColor: "rgba(95,186,88,0.7)",
                    strokeColor: "rgba(95,186,88,1)",
                    pointColor: "rgba(95,186,88,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: [65, 59, 80, 81, 56, 55, 40]
                }
            ]
    };

var options = {
    responsive: true,
    bezierCurve : false,
    scaleShowLabels: false,
    scaleFontSize: 0,
    pointDot : false,
    scaleBeginAtZero: true,
    scaleShowHorizontalLines: false,
    scaleShowVerticalLines: true,
    scaleGridLineColor : "rgba(232,232,232)",
    showTooltips: true,

    customTooltips: function (tooltip) {
        var tooltipEl = $('#chartjs-tooltip');

        if (!tooltip) {
            tooltipEl.css({
                opacity: 0
            });
            return;
        }

        tooltipEl.removeClass('above below');
        tooltipEl.addClass(tooltip.yAlign);

        // split out the label and value and make your own tooltip here
        var parts = tooltip.text.split(":");
        var innerHtml = '' + parts[0].trim() + ' : ' + parts[1].trim() + '';
        tooltipEl.html(innerHtml);

        tooltipEl.css({
            opacity: 1,
            left: tooltip.chart.canvas.offsetLeft + tooltip.x + 'px',
            top: tooltip.chart.canvas.offsetTop + tooltip.y + 'px',
            fontFamily: tooltip.fontFamily,
            fontSize: tooltip.fontSize,
            fontStyle: tooltip.fontStyle,
        });
    }

};

simplified fiddle

Body:
Tested with Chart.js v2.6.0

Global setting will do the trick:

Chart.defaults.global.hover.intersect = false;

Or directly in chart config:

options: {
  hover: {
    intersect: false;
  }
}

And point settings for dataset.

initial color of the point should be transparent

hover color must be set to the desired color

e.g.

datasets: [{
  label: 'My First dataset',
  borderColor: 'rgb(255, 99, 132)',
  backgroundColor: 'rgb(255, 99, 132)',
  data: [10, 30, 46, 2, 8, 50, 0],
  fill: false,
  pointBorderColor: 'rgba(0, 0, 0, 0)',
  pointBackgroundColor: 'rgba(0, 0, 0, 0)',
  pointHoverBackgroundColor: 'rgb(255, 99, 132)',
  pointHoverBorderColor: 'rgb(255, 99, 132)'}],...

window.onload = function() {
  const mode = 'index';
  const intersect = false;
  const config = {
    type: 'line',
    data: {
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
      datasets: [{
        label: 'My First dataset',
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgb(255, 99, 132)',
        data: [10, 30, 46, 2, 8, 50, 0],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(255, 99, 132)',
        pointHoverBorderColor: 'rgb(255, 99, 132)',
      }, {
        label: 'My Second dataset',
        borderColor: 'rgb(54, 162, 235)',
        backgroundColor: 'rgb(54, 162, 235)',
        data: [7, 49, 46, 13, 25, 30, 22],
        fill: false,
        pointBorderColor: 'rgba(0, 0, 0, 0)',
        pointBackgroundColor: 'rgba(0, 0, 0, 0)',
        pointHoverBackgroundColor: 'rgb(54, 162, 235)',
        pointHoverBorderColor: 'rgb(54, 162, 235)',
      }]
    },
    options: {
      responsive: true,
      title: {
        display: true,
        text: 'Mode: index, intersect = false'
      },
      tooltips: {
        mode: 'index',
        intersect: intersect,
      },
      hover: {
        mode: mode,
        intersect: intersect
      },
    }
  };
  const ctx = document.getElementById('canvas').getContext('2d');
  const chart = new Chart(ctx, config);
}

<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>


问:
how to get status in c for system() commands
I want to get the status of command which i passed as a parameter to the system() function. suppose i pass "attrib +h E:/songs/lovingsong.mp3" as system("attrib +h E:/songs/lovingsong.mp3") since i know that the path give by me is not right , i.e there is no such folder songs in my E: drive so on console it says path not found.
How can i get "path not found" message in my c program or any status code ,so that i can know the command did not work.</p>

```<code>/* system example : DIR */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */

int main ()
{
  int i;
  printf ("Checking if processor is available...");
  if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);
  printf ("Executing command DIR...\n");
  i = system ("attrib +h E:/songs/lovingsong.mp3");
  //want to get status here
  printf ("The value returned was: %d.\n",i);
  return 0;
}
</code>```

答:
Notice that the C11 standard (read n1570) defines system in §7.22.4.8 (with its formal argument being called string below):

If string is  a  null  pointer,  the system function  determines  whether  the  host environment has a command  processor. If string is  not  a  null  pointer,  the system function  passes  the  string  pointed to by  string to that command  processor to be executed in a manner which the implementation shall document; this might then cause the program calling
  system to behave in a non-conforming manner or to terminate

So there is no clear definition, according to the C11 standard, of what system does. You need to dive into the documentation of your particular C11 implementation.

On POSIX (e.g. Linux or MacOSX), system is required to run the POSIX shell /bin/sh with the -c argument followed by the string and there is a complex chapter describing what is a POSIX shell.

Perhaps you want to pass a command which is redirecting the stderr of attrib to stdout, and read that stdout produced by your attrib command. On POSIX you could use popen (with pclose) for that purpose. Maybe (and probably) your implementation has something similar: _popen. And you also need to read the documentation of your attrib command.

So your question is really operating system specific. You need to dive into the documentation of your particular operating system.

And you might simply test (before running system) that the file E:/songs/lovingsong.mp3 exists. Maybe use _access (with perhaps a race condition if that file gets removed before running attrib).

Be also aware of the $PATH variable.

PS. I don't know anything about Windows, but you did not tag your question with Windows.

Body:
I want to get the status of command which i passed as a parameter to the system() function. suppose i pass "attrib +h E:/songs/lovingsong.mp3" as system("attrib +h E:/songs/lovingsong.mp3") since i know that the path give by me is not right , i.e there is no such folder songs in my E: drive so on console it says path not found.
How can i get "path not found" message in my c program or any status code ,so that i can know the command did not work.

/* system example : DIR */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */

int main ()
{
  int i;
  printf ("Checking if processor is available...");
  if (system(NULL)) puts ("Ok");
    else exit (EXIT_FAILURE);
  printf ("Executing command DIR...\n");
  i = system ("attrib +h E:/songs/lovingsong.mp3");
  //want to get status here
  printf ("The value returned was: %d.\n",i);
  return 0;
}


问:
How do I resize text inside a table using media queries?
I have this html

```<code><meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/newcss.css"/>
</code>```

...

```<code><table>
  <tbody>
    <tr>
      <td>General Inquiries:</td>
      <td>Email@email.com</td>
    </tr>
    <tr>
      <td>Phone:</td>
      <td>#########</td>
    </tr>
    <tr>
      <td>Mailing address:</td>
      <td>123 Some St. 123 456</td>
    </tr>
  </tbody>
</table>
</code>```

and this css

```<code>table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
}

td {
    padding: 0px 10px;
}

@media (max-width: 730){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}
</code>```

However, when I resize the window to below 730, the font size does not change on any of the elements listed in the media query. Any Ideas?

答:
you have a mistake in your media query</p>

```<code>@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}
</code>```

Body:
I have this html

<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="css/normalize.css"/>
<link rel="stylesheet" href="css/newcss.css"/>

...

      General Inquiries:
      Email@email.com

      Phone:
      #########

      Mailing address:
      123 Some St. 123 456

and this css

table {
    border-collapse: collapse;
    font-size: 34px;
    color: white;
    margin: 15px;
    width: 90%;
}

td {
    padding: 0px 10px;
}

@media (max-width: 730){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}

However, when I resize the window to below 730, the font size does not change on any of the elements listed in the media query. Any Ideas?

Body:
you have a mistake in your media query

@media (max-width: 730px){
    table, tr, td, tbody, thead {
        font-size: 14px;
    }
}


问:
Printing reverse complement of DNA in single-line Perl
I want to write a quick single-line perl script to produce the reverse complement of a sequence of DNA. The following isn't working for me, however:

```<code>$ cat sample.dna.sequence.txt | perl -ne '{while (<>) {$seq = $_; $seq =~ tr /atcgATCG/tagcTAGC/; $revComp = reverse($seq); print $revComp;}}'
</code>```

Any suggestions? I'm aware that

```<code>tr -d "\n " < input.txt | tr "[ATGCatgcNn]" "[TACGtacgNn]" | rev
</code>```

works in bash, but I want to do it with perl for the practice.

答:
The problem is that you're using -n in the perl flag, yet you've written your own loop.  -n wraps your supplied code in a while loop like while(<STDIN>){...}.  So the STDIN file handle has already been read from and your code does it again, getting EOF (end of file) or rather 'undefined'.  You either need to remove the n from -ne or remove the while loop from your code.

Incidentally, a complete complement tr pattern, including ambiguous bases, is:

tr/ATGCBVDHRYKMatgcbvdhrykm/TACGVBHDYRMKtacgvbhdyrmk/

Ambiguous bases have complements too.  For example, a V stands for an A, C, or G.  Their complements are T, G, and C, which is represented by the ambiguous base B.  Thus, V and B are complementary.

You don't need to include any N's or n's in your tr pattern (as was demonstrated in another answer) because the complement is the same and leaving them out will leave them untouched.  It's just extra processing to put them in the pattern.

Body:
I want to write a quick single-line perl script to produce the reverse complement of a sequence of DNA. The following isn't working for me, however:

$ cat sample.dna.sequence.txt | perl -ne '{while (<>) {$seq = $_; $seq =~ tr /atcgATCG/tagcTAGC/; $revComp = reverse($seq); print $revComp;}}'

Any suggestions? I'm aware that

tr -d "\n " < input.txt | tr "[ATGCatgcNn]" "[TACGtacgNn]" | rev

works in bash, but I want to do it with perl for the practice.


问:
Comparing keys in HashMap and Values
I have a HashMap as follows-

```<code>HashMap<String, Integer> BC = new HashMap<String, Integer>();
</code>```

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

```<code>"the/at" 153
"that/cs" 45
"Ann/np" 3
</code>```

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

```<code>"the/at" 153
"the/det" 80
</code>```

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

```<code>private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }
</code>```

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

答:
Create a new

```<code>Map<String,Integer> highCount = new HashMap<>();
</code>```

that will map tokens to their largest count.

Make a single pass through the keys.

Split each key into its component tokens.

For each token, look in highMap.  If the key does not exist, add it with its count. If the entry already exists and the current count is greater than the previous maximum, replace the maximum in the map.

When you are done with the single pass the highCount will contain all the unique tokens along with the highest count seen for each token.

Note: This answer is intended to give you a starting point from which to develop a complete solution. The key concept is that you create and populate a new map from token to some "value" type (not necessarily just Integer) that provides you with the functionality you need.  Most likely the value type will be a new custom class that stores the tag and the count.

Title: Comparing keys in HashMap and Values

Body:
I have a HashMap as follows-

HashMap<String, Integer> BC = new HashMap<String, Integer>();

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

"the/at" 153
"that/cs" 45
"Ann/np" 3

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

"the/at" 153
"the/det" 80

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

Body:
Create a new

Map<String,Integer> highCount = new HashMap<>();

that will map tokens to their largest count.

Make a single pass through the keys.

Split each key into its component tokens.

For each token, look in highMap.  If the key does not exist, add it with its count. If the entry already exists and the current count is greater than the previous maximum, replace the maximum in the map.

When you are done with the single pass the highCount will contain all the unique tokens along with the highest count seen for each token.

Note: This answer is intended to give you a starting point from which to develop a complete solution. The key concept is that you create and populate a new map from token to some "value" type (not necessarily just Integer) that provides you with the functionality you need.  Most likely the value type will be a new custom class that stores the tag and the count.


问:
How to extract numbers from string containing numbers+characters into an array in Ruby?
I have string that contains integers and characters and I need to extract all numbers in array, for example:

```<code>str = "achance123for84faramir3toshowhis98quality"
#=> [123, 84, 3, 98] #Desired output
</code>```

I am having trouble grouping them together. I have tried:

```<code>str.split('').select {|el| el.match(/[\d]+.*/)}
#=> ["1", "2", "3", "8", "4", "3", "9", "8"]

str.split('').select {|el| el.match(/[\d]+[\D]+/)}
#=> []
</code>```

How can I maintain the grouping for all integers and list them in array? Assume it will contain only numbers and characters (a-z). No whitespace/ non-word characters. All will be lowercased.

(they don't have to be converted to integer. I am just having problem coming up with the regex to separate them in groups. If there is a solution without Regex, that'd be awesome too!)

答:
Try using String#scan, like this:

```<code>str.scan(/\d+/)
#=> ["123", "84", "3", "98"]
</code>```

If you want integers instead of strings, just add map to it:

```<code>str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]
</code>```

Body:
I have string that contains integers and characters and I need to extract all numbers in array, for example:

str = "achance123for84faramir3toshowhis98quality"
#=> [123, 84, 3, 98] #Desired output

I am having trouble grouping them together. I have tried:

str.split('').select {|el| el.match(/[\d]+.*/)}
#=> ["1", "2", "3", "8", "4", "3", "9", "8"]

str.split('').select {|el| el.match(/[\d]+[\D]+/)}
#=> []

How can I maintain the grouping for all integers and list them in array? Assume it will contain only numbers and characters (a-z). No whitespace/ non-word characters. All will be lowercased.

(they don't have to be converted to integer. I am just having problem coming up with the regex to separate them in groups. If there is a solution without Regex, that'd be awesome too!)

Body:
Try using String#scan, like this:

str.scan(/\d+/)
#=> ["123", "84", "3", "98"]

If you want integers instead of strings, just add map to it:

str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]


问:
How to change Attributes on a Pop Up to equal to the Attributes of the Buttons that opened said Pop Up?
My project is a card game. Each Card is also a Button. When you click on a card in play, a Pop Up opens with a Card Image, a Scrollable Label of Card Text, and various Buttons.

My current problem is trying to change the Image and Text in the Pop Up to match that of the actual Card Button information. I currently have the ability to change the information that shows up but only as the most recent definition of it. From what I understand this is because I'm redefining the class attribute, not an instance of the class attribute.

I've tried to do a def__init__(self, parameters): in the Card (Button Image) file, however this would crash anytime I tried to perform the draw method of the PlayMatWidget.

I think this may have something to do with Kivy Object Properties but I'm not entirely sure on how to use them for this exactly (largely since the buttons aren't created at runtime)

Thank you for reading!

Python File:

```<code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import random

Builder.load_string('''
<ScrollableLabel>:
    Label:
        size_hint_y: None
        height: self.texture_size[1]
        text_size: self.width, None
        text: root.text
''')

class ScrollableLabel(ScrollView):
    text = StringProperty('')

# Visual Representation of a Card or Deck
class ImageButton(ButtonBehavior, Image):
    pass

class CardBackend:
    def __init__(self, name, card_art, effect_one):
        self.name = name
        self.card_art = card_art
        self.effect = effect_one

class Card(ImageButton):
    # Defining the Popup Window
    main_pop = Popup()
    main_pop.title = 'Inspect Card'
    main_pop.title_align = 'center'
    main_pop.size_hint = None, None
    main_pop.size = 400, 400
    main_pop.auto_dismiss = False
    main_pop.opacity = 0.8

    # Variables or Variables to Be
    card_text = 'ABCDEFGHIJK1234567890' * 100
    card_art = Image(source='test.png', size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

    # Primary Child Widget
    main_box = FloatLayout()

    # Buttons
    play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
    discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
    close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
    close_button.bind(on_press=main_pop.dismiss)

    # Scrolling Card Text Viewer
    card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

    # Building main_pop.content
    main_box.add_widget(play_button)
    main_box.add_widget(discard_button)
    main_box.add_widget(close_button)
    main_box.add_widget(card_info)
    main_box.add_widget(card_art)
    main_pop.content = main_box

class PlayMatWidget(FloatLayout):
    def draw(self):
        # Create Backend
        # Draw Backend
        # Create Card() using Backend

        # Defining Card Data (Removed for imported Decks)
        backend_bewd = CardBackend('Blue Eyes White Dragon', 'bewd.png', 'One')
        backend_dragon = CardBackend('Dragon Egg', 'test.png', 'Two')
        backend_lava = CardBackend('Lava Golem', 'lavagolem.png', 'Three')

        # Creating Card Button Objects
        card_zero = Card()
        card_one = Card()
        card_two = Card()

        # Defining Card Title
        card_zero.main_pop.title = backend_lava.name
        card_one.main_pop.title = backend_dragon.name
        card_two.main_pop.title = backend_bewd.name

        # Defining Card Text for Scrollview
        card_zero.card_info.text = backend_bewd.effect

        # Defining Card Art
        card_zero.source = backend_bewd.card_art
        card_one.source = backend_dragon.card_art
        card_two.source = backend_lava.card_art

        deck_dictionary = {
            0: card_zero,
            1: card_one,
            2: card_two,
        }

        # Prototype Shuffle for top card
        # drawing = random.choice(deck_list)

        # Creating a Physical Card Object
        # drawn_card = Card()

        # OLD
        # Applying Card Data from backend to front end Card Object
        # drawn_card.main_pop.title = drawing.name
        # drawn_card.source = drawing.card_art
        # drawn_card.card_art.source = drawing.card_art
        # drawn_card.card_info.text = drawing.effect

        # Used to check somethings
        for x in range(0, 3):
            print(deck_dictionary[x].source)
            print(deck_dictionary[x].main_pop.title)

        self.ids.PlayerField.add_widget(random.choice(deck_dictionary), index=int(len(self.ids.PlayerField.children)/2))

class CardGameApp(App):
    def build(self):
        return PlayMatWidget()

if __name__ == "__main__":
    CardGameApp().run()
</code>```

Kivy File:

```<code><Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    on_press: print('confirming press')
    on_press: root.main_pop.open()

<PlayMatWidget>:
    id: PlayMat
    canvas:
        Rectangle:
            size: self.size
            pos: self.pos
            source: 'tron1.png'
    StackLayout:
        id: OppHand
        size_hint: 0.6, 0.1
        pos_hint: {'x':0.2,'y': 0.9}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: OppField
        size_hint: 0.6, 0.4
        pos_hint: {'x':0.2, 'y':0.5}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: cards
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    AnchorLayout:
        id: PlayerFieldAnchor
        anchor_x: 'center'
        anchor_y: 'center'
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas.before:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
        BoxLayout:
            id: PlayerField
            orientation: 'horizontal'
    StackLayout:
        id: PlayerHand
        orientation: 'lr-tb'
        size_hint: 0.6,0.1
        pos_hint: {'x': 0.2, 'y':0}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    ImageButton:
        id: PlayerDeck
        source: 'cardback.png'
        size_hint: 0.15, 0.15
        pos_hint: {'x':0.025,'y':0.05}
        on_press: root.draw()
</code>```

答:
I solved it. I moved the creation of the Pop Up Box into a Function with the Card Class. In the kivy file, I bound the inspect_card() function to the on_press event of the Kivy Card Button.

Previously the Pop Up was being defined at the creation of the card. So the Pop Up would always have the information correspond to the latest created card, regardless of which card button I clicked.

Moving it to a function meant that the Pop Up is only ever created when that function is initiated, so all of the relevant information corresponds to the source information of the Button that called it. This way it doesn't matter whether the instance is inside the class or not because it will be redefined correctly every time it runs.

Success Video

Card Class w/Function:

```<code>class Card(ImageButton):
    # Defining the Popup Window
    def inspect_card(self):
        main_pop = Popup()
        main_pop.title = 'Inspecting ' + self.cardname
        main_pop.title_align = 'center'
        main_pop.size_hint = None, None
        main_pop.size = 400, 400
        main_pop.auto_dismiss = False
        main_pop.opacity = 0.8

        # Variables or Variables to Be
        card_text = self.effecttext
        card_art = Image(source=self.source, size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

        # Primary Child Widget
        main_box = FloatLayout()

        # Buttons
        play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
        discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
        close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
        close_button.bind(on_press=main_pop.dismiss)

        # Scrolling Card Text Viewer
        card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

        # Building main_pop.content
        main_box.add_widget(play_button)
        main_box.add_widget(discard_button)
        main_box.add_widget(close_button)
        main_box.add_widget(card_info)
        main_box.add_widget(card_art)
        main_pop.content = main_box
        main_pop.open()
</code>```

Kivy Card Button with new binding and referenced properties for the Pop Up

```<code><Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    cardname: 'stuff'
    effecttext: 'ABCDEFGHIJKL123456789' * 30
    on_press: print('confirming press')
    on_press: root.inspect_card()
</code>```

(Prop Values listed are default, I change them below in the MainGameWidget before their brought to the field. I'll be moving most of this to the Deckbuilder functionality later)

Body:
My project is a card game. Each Card is also a Button. When you click on a card in play, a Pop Up opens with a Card Image, a Scrollable Label of Card Text, and various Buttons.

My current problem is trying to change the Image and Text in the Pop Up to match that of the actual Card Button information. I currently have the ability to change the information that shows up but only as the most recent definition of it. From what I understand this is because I'm redefining the class attribute, not an instance of the class attribute.

I've tried to do a def__init__(self, parameters): in the Card (Button Image) file, however this would crash anytime I tried to perform the draw method of the PlayMatWidget.

I think this may have something to do with Kivy Object Properties but I'm not entirely sure on how to use them for this exactly (largely since the buttons aren't created at runtime)

Thank you for reading!

Python File:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import random

Builder.load_string('''
<ScrollableLabel>:
    Label:
        size_hint_y: None
        height: self.texture_size[1]
        text_size: self.width, None
        text: root.text
''')

class ScrollableLabel(ScrollView):
    text = StringProperty('')

# Visual Representation of a Card or Deck
class ImageButton(ButtonBehavior, Image):
    pass

class CardBackend:
    def __init__(self, name, card_art, effect_one):
        self.name = name
        self.card_art = card_art
        self.effect = effect_one

class Card(ImageButton):
    # Defining the Popup Window
    main_pop = Popup()
    main_pop.title = 'Inspect Card'
    main_pop.title_align = 'center'
    main_pop.size_hint = None, None
    main_pop.size = 400, 400
    main_pop.auto_dismiss = False
    main_pop.opacity = 0.8

    # Variables or Variables to Be
    card_text = 'ABCDEFGHIJK1234567890' * 100
    card_art = Image(source='test.png', size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

    # Primary Child Widget
    main_box = FloatLayout()

    # Buttons
    play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
    discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
    close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
    close_button.bind(on_press=main_pop.dismiss)

    # Scrolling Card Text Viewer
    card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

    # Building main_pop.content
    main_box.add_widget(play_button)
    main_box.add_widget(discard_button)
    main_box.add_widget(close_button)
    main_box.add_widget(card_info)
    main_box.add_widget(card_art)
    main_pop.content = main_box

class PlayMatWidget(FloatLayout):
    def draw(self):
        # Create Backend
        # Draw Backend
        # Create Card() using Backend

        # Defining Card Data (Removed for imported Decks)
        backend_bewd = CardBackend('Blue Eyes White Dragon', 'bewd.png', 'One')
        backend_dragon = CardBackend('Dragon Egg', 'test.png', 'Two')
        backend_lava = CardBackend('Lava Golem', 'lavagolem.png', 'Three')

        # Creating Card Button Objects
        card_zero = Card()
        card_one = Card()
        card_two = Card()

        # Defining Card Title
        card_zero.main_pop.title = backend_lava.name
        card_one.main_pop.title = backend_dragon.name
        card_two.main_pop.title = backend_bewd.name

        # Defining Card Text for Scrollview
        card_zero.card_info.text = backend_bewd.effect

        # Defining Card Art
        card_zero.source = backend_bewd.card_art
        card_one.source = backend_dragon.card_art
        card_two.source = backend_lava.card_art

        deck_dictionary = {
            0: card_zero,
            1: card_one,
            2: card_two,
        }

        # Prototype Shuffle for top card
        # drawing = random.choice(deck_list)

        # Creating a Physical Card Object
        # drawn_card = Card()

        # OLD
        # Applying Card Data from backend to front end Card Object
        # drawn_card.main_pop.title = drawing.name
        # drawn_card.source = drawing.card_art
        # drawn_card.card_art.source = drawing.card_art
        # drawn_card.card_info.text = drawing.effect

        # Used to check somethings
        for x in range(0, 3):
            print(deck_dictionary[x].source)
            print(deck_dictionary[x].main_pop.title)

        self.ids.PlayerField.add_widget(random.choice(deck_dictionary), index=int(len(self.ids.PlayerField.children)/2))

class CardGameApp(App):
    def build(self):
        return PlayMatWidget()

if __name__ == "__main__":
    CardGameApp().run()

Kivy File:

<Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    on_press: print('confirming press')
    on_press: root.main_pop.open()

<PlayMatWidget>:
    id: PlayMat
    canvas:
        Rectangle:
            size: self.size
            pos: self.pos
            source: 'tron1.png'
    StackLayout:
        id: OppHand
        size_hint: 0.6, 0.1
        pos_hint: {'x':0.2,'y': 0.9}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: OppField
        size_hint: 0.6, 0.4
        pos_hint: {'x':0.2, 'y':0.5}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: cards
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    AnchorLayout:
        id: PlayerFieldAnchor
        anchor_x: 'center'
        anchor_y: 'center'
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas.before:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
        BoxLayout:
            id: PlayerField
            orientation: 'horizontal'
    StackLayout:
        id: PlayerHand
        orientation: 'lr-tb'
        size_hint: 0.6,0.1
        pos_hint: {'x': 0.2, 'y':0}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    ImageButton:
        id: PlayerDeck
        source: 'cardback.png'
        size_hint: 0.15, 0.15
        pos_hint: {'x':0.025,'y':0.05}
        on_press: root.draw()

Body:
I solved it. I moved the creation of the Pop Up Box into a Function with the Card Class. In the kivy file, I bound the inspect_card() function to the on_press event of the Kivy Card Button.

Previously the Pop Up was being defined at the creation of the card. So the Pop Up would always have the information correspond to the latest created card, regardless of which card button I clicked.

Moving it to a function meant that the Pop Up is only ever created when that function is initiated, so all of the relevant information corresponds to the source information of the Button that called it. This way it doesn't matter whether the instance is inside the class or not because it will be redefined correctly every time it runs.

Success Video

Card Class w/Function:

class Card(ImageButton):
    # Defining the Popup Window
    def inspect_card(self):
        main_pop = Popup()
        main_pop.title = 'Inspecting ' + self.cardname
        main_pop.title_align = 'center'
        main_pop.size_hint = None, None
        main_pop.size = 400, 400
        main_pop.auto_dismiss = False
        main_pop.opacity = 0.8

        # Variables or Variables to Be
        card_text = self.effecttext
        card_art = Image(source=self.source, size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

        # Primary Child Widget
        main_box = FloatLayout()

        # Buttons
        play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
        discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
        close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
        close_button.bind(on_press=main_pop.dismiss)

        # Scrolling Card Text Viewer
        card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

        # Building main_pop.content
        main_box.add_widget(play_button)
        main_box.add_widget(discard_button)
        main_box.add_widget(close_button)
        main_box.add_widget(card_info)
        main_box.add_widget(card_art)
        main_pop.content = main_box
        main_pop.open()

Kivy Card Button with new binding and referenced properties for the Pop Up

<Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    cardname: 'stuff'
    effecttext: 'ABCDEFGHIJKL123456789' * 30
    on_press: print('confirming press')
    on_press: root.inspect_card()

(Prop Values listed are default, I change them below in the MainGameWidget before their brought to the field. I'll be moving most of this to the Deckbuilder functionality later)