问:
TextView onClcikclistener seems not being working
The onClickListener on this TextView seems not be working when I click the text in the app it doesn't show the TimePickerDialog or anything .Should I use a TouchListener ? Whats the problem? Please help thanks in advance --Emanuel.

Here is the code:

```<code>hora_text.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        hora_button.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick (View v){
                    Calendar cal = Calendar.getInstance();
                    int hora = cal.get(Calendar.HOUR);
                    int minutos = cal.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(),TimePickerDialog.THEME_HOLO_LIGHT,hourSetListener,hora,minutos,true);
                    mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    mTimePicker.show();
                 }
             });

         hourSetListener = new TimePickerDialog.OnTimeSetListener() {
             @Override
             public void onTimeSet(TimePicker timePicker, int hora, int minutos) {
                 hora_text.setText(hora+":"+minutos);
             }
         };
    }
});

date_text.setOnClickListener(
    new View.OnClickListener() {
        public void onClick(View v) {
            date_button.setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            Calendar cal = Calendar.getInstance();
                            int year = cal.get(Calendar.YEAR);
                            int month = cal.get(Calendar.MONTH);
                            int day = cal.get(Calendar.DAY_OF_MONTH);
                            DatePickerDialog date_dialog = new DatePickerDialog(getActivity(),
                                           android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                           dateSetListener,
                                            year, month, day);
                            date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            date_dialog.show();
                        };
                    }
            );

            dateSetListener = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                    month=month + 1;
                    String dt = day + "-" + month + "-" + year;
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                    try {
                        sdf.parse(dt);
                        date_text.setText(dt);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            };
        }
    }
);
</code>```

答:
Just like @PPartisan mentioned in the comments, you're not really setting the TextView clickable with functionality since you're setting the functionality within a button instead. So in your case, it should be:</p>

```<code>hora_text.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Calendar cal = Calendar.getInstance();
        int hora = cal.get(Calendar.HOUR);
        int minutos = cal.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(),TimePickerDialog.THEME_HOLO_LIGHT,hourSetListener,hora,minutos,true);
        mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mTimePicker.show();
    }
);
</code>```

Body:
The onClickListener on this TextView seems not be working when I click the text in the app it doesn't show the TimePickerDialog or anything .Should I use a TouchListener ? Whats the problem? Please help thanks in advance --Emanuel.

Here is the code:

hora_text.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        hora_button.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick (View v){
                    Calendar cal = Calendar.getInstance();
                    int hora = cal.get(Calendar.HOUR);
                    int minutos = cal.get(Calendar.MINUTE);
                    TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(),TimePickerDialog.THEME_HOLO_LIGHT,hourSetListener,hora,minutos,true);
                    mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    mTimePicker.show();
                 }
             });

         hourSetListener = new TimePickerDialog.OnTimeSetListener() {
             @Override
             public void onTimeSet(TimePicker timePicker, int hora, int minutos) {
                 hora_text.setText(hora+":"+minutos);
             }
         };
    }
});

date_text.setOnClickListener(
    new View.OnClickListener() {
        public void onClick(View v) {
            date_button.setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            Calendar cal = Calendar.getInstance();
                            int year = cal.get(Calendar.YEAR);
                            int month = cal.get(Calendar.MONTH);
                            int day = cal.get(Calendar.DAY_OF_MONTH);
                            DatePickerDialog date_dialog = new DatePickerDialog(getActivity(),
                                           android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                           dateSetListener,
                                            year, month, day);
                            date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            date_dialog.show();
                        };
                    }
            );

            dateSetListener = new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                    month=month + 1;
                    String dt = day + "-" + month + "-" + year;
                    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
                    try {
                        sdf.parse(dt);
                        date_text.setText(dt);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            };
        }
    }
);

Body:
Just like @PPartisan mentioned in the comments, you're not really setting the TextView clickable with functionality since you're setting the functionality within a button instead. So in your case, it should be:

hora_text.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        Calendar cal = Calendar.getInstance();
        int hora = cal.get(Calendar.HOUR);
        int minutos = cal.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(),TimePickerDialog.THEME_HOLO_LIGHT,hourSetListener,hora,minutos,true);
        mTimePicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mTimePicker.show();
    }
);


来源: stackexchange

问:
SQL wont allow me to add foreign key?
I'm building a question and answer site and for linking the user accounts to the questions I want to have the username from the login table be a foreign key of the questions table so when a user asks a question it must be linked to his or her username.  Can I not have foreign key's that are varchar datatype?  Or must the foreign key be only a primary key of another table?  The error I'm getting says 'Key column "'username' doesn't exist in table" .  What am I doing wrong?</p>

```<code>create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (username) references
login (username));
</code>```

答:
Two issues here:

Your Questions table does not have a username column. It must. Even then it would not work because of problem 2.

As a general rule, your foreign key reference needs to use the user_id and not the username. The reason is that Fk references generally start from a column and end in a primary key value.

create table questions (q_id int not null auto_increment, user_id int not   null, question varchar (100), primary key (q_id), foreign key (user_id) references login (user_id));

Here is a more elaborate elaboration from a related question:

ContentLicense: CC BY-SA 3.0

Title: SQL wont allow me to add foreign key?

Body:
I'm building a question and answer site and for linking the user accounts to the questions I want to have the username from the login table be a foreign key of the questions table so when a user asks a question it must be linked to his or her username.  Can I not have foreign key's that are varchar datatype?  Or must the foreign key be only a primary key of another table?  The error I'm getting says 'Key column "'username' doesn't exist in table" .  What am I doing wrong?

create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (username) references
login (username));


问:
Failed to open dex file, unrecognized version number
I've pushed an apk to system/priv-app on my tv box, but I get this error when I try to uninstall an app:

```<code>dex2oat : Failed to create oat file: /data/dalvik-cache/arm/system@priv-app@CanvasPackageInstaller@CanvasPackageInstaller.apk@classes.dex: Permission denied
dex2oat : dex2oat took 803.750us (threads: 4)
art     : Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm --instruction-set-features=smp,-div,-atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=cortex-a9 --instruction-set-features=default --dex-file=/system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk --oat-file=/data/dalvik-cache/arm/system@priv-app@CanvasPackageInstaller@CanvasPackageInstaller.apk@classes.dex) because non-0 exit status
art     : Failed to open dex file '/system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk' from memory: Unrecognized version number in /system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk: 0 3 7
</code>```

I've tried to clean the dalvik-cache but with no success. What does it mean ?

答:
In my case problem was solved by enabling Instant Run.
On each start of application there was prompt (Install Android 7 platform for instant run/Continue without instant run). When i press SKIP, there was same exception (dex version... bla-bla) for some apks. Installing appropriate platform dismissed exception.</p>

Body:
I've pushed an apk to system/priv-app on my tv box, but I get this error when I try to uninstall an app:

dex2oat : Failed to create oat file: /data/dalvik-cache/arm/system@priv-app@CanvasPackageInstaller@CanvasPackageInstaller.apk@classes.dex: Permission denied
dex2oat : dex2oat took 803.750us (threads: 4)
art     : Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --instruction-set=arm --instruction-set-features=smp,-div,-atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=cortex-a9 --instruction-set-features=default --dex-file=/system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk --oat-file=/data/dalvik-cache/arm/system@priv-app@CanvasPackageInstaller@CanvasPackageInstaller.apk@classes.dex) because non-0 exit status
art     : Failed to open dex file '/system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk' from memory: Unrecognized version number in /system/priv-app/CanvasPackageInstaller/CanvasPackageInstaller.apk: 0 3 7

I've tried to clean the dalvik-cache but with no success. What does it mean ?


问:
run for-loop for large numbers in python
```<code> for i in range(1000000000):
 print(i)
</code>```

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

```<code>>>>MemoryError
</code>```

UPDATE:
Actually I was trying something like this:

```<code>arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))
</code>```

I don't know how to deal with such large numbers.

答: on python2 this will give an error since range returns a list and in this case your list is too big for memory to hold, try in python3 and it will work. try xrange in python2.

Body:
 for i in range(1000000000):
 print(i)

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

>>>MemoryError

UPDATE:
Actually I was trying something like this:

arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))

I don't know how to deal with such large numbers.


问:
How do I add references to a container when the borrowed values are created after the container?
For reasons related to code organization, I need the compiler to accept the following (simplified) code:

```<code>fn f() {
    let mut vec = Vec::new();
    let a = 0;
    vec.push(&a);
    let b = 0;
    vec.push(&b);
    // Use `vec`
}
</code>```

The compiler complains

error: `a` does not live long enough
 --> src/main.rs:8:1
  |
4 |     vec.push(&a);
  |               - borrow occurs here
...
8 | }
  | ^ `a` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

error: `b` does not live long enough
 --> src/main.rs:8:1
  |
6 |     vec.push(&b);
  |               - borrow occurs here
7 |     // Use `vec`
8 | }
  | ^ `b` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created
```

However, I'm having a hard time convincing the compiler to drop the vector before the variables it references. vec.clear() doesn't work, and neither does drop(vec). mem::transmute() doesn't work either (to force vec to be 'static).

The only solution I found was to transmute the reference into &'static _. Is there any other way? Is it even possible to compile this in safe Rust?

答:
Is it even possible to compile this in safe Rust?

No. What you are trying to do is inherently unsafe in the general case.

The collection contains a reference to a variable that will be dropped before the collection itself is dropped. This means that the destructor of the collection has access to references that are no longer valid. The destructor could choose to dereference one of those values, breaking Rust's memory safety guarantees.

note: values in a scope are dropped in the opposite order they are created

As the compiler tells you, you need to reorder your code. You didn't actually say what the limitations are for "reasons related to code organization", but the straight fix is:

```<code>fn f() {
    let a = 0;
    let b = 0;
    let mut vec = Vec::new();
    vec.push(&a);
    vec.push(&b);
}
</code>```

A less obvious one is:

```<code>fn f() {
    let a;
    let b;

    let mut vec = Vec::new();
    a = 0;
    vec.push(&a);
    b = 0;
    vec.push(&b);
}
</code>```

That all being said, once non-lexical lifetimes are enabled, your original code will work! The borrow checker becomes more granular about how long a value needs to live.

But wait; I just said that the collection might access invalid memory if a value inside it is dropped before the collection, and now the compiler is allowing that to happen? What gives?

This is because the standard library pulls a sneaky trick on us. Collections like Vec or HashSet guarantee that they do not access their generic parameters in the destructor. They communicate this to the compiler using the unstable #[may_dangle] feature.

See also:

Moved variable still borrowing after calling `drop`?

"cannot move out of variable because it is borrowed" when rotating variables

ContentLicense: CC BY-SA 4.0

Body:
For reasons related to code organization, I need the compiler to accept the following (simplified) code:

fn f() {
    let mut vec = Vec::new();
    let a = 0;
    vec.push(&a);
    let b = 0;
    vec.push(&b);
    // Use `vec`
}

The compiler complains

error: `a` does not live long enough
 --> src/main.rs:8:1
  |
4 |     vec.push(&a);
  |               - borrow occurs here
...
8 | }
  | ^ `a` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

error: `b` does not live long enough
 --> src/main.rs:8:1
  |
6 |     vec.push(&b);
  |               - borrow occurs here
7 |     // Use `vec`
8 | }
  | ^ `b` dropped here while still borrowed
  |
  = note: values in a scope are dropped in the opposite order they are created

However, I'm having a hard time convincing the compiler to drop the vector before the variables it references. vec.clear() doesn't work, and neither does drop(vec). mem::transmute() doesn't work either (to force vec to be 'static).

The only solution I found was to transmute the reference into &'static _. Is there any other way? Is it even possible to compile this in safe Rust?

Body:
Is it even possible to compile this in safe Rust?

No. What you are trying to do is inherently unsafe in the general case.

The collection contains a reference to a variable that will be dropped before the collection itself is dropped. This means that the destructor of the collection has access to references that are no longer valid. The destructor could choose to dereference one of those values, breaking Rust's memory safety guarantees.

note: values in a scope are dropped in the opposite order they are created

As the compiler tells you, you need to reorder your code. You didn't actually say what the limitations are for "reasons related to code organization", but the straight fix is:

fn f() {
    let a = 0;
    let b = 0;
    let mut vec = Vec::new();
    vec.push(&a);
    vec.push(&b);
}

A less obvious one is:

fn f() {
    let a;
    let b;

    let mut vec = Vec::new();
    a = 0;
    vec.push(&a);
    b = 0;
    vec.push(&b);
}

That all being said, once non-lexical lifetimes are enabled, your original code will work! The borrow checker becomes more granular about how long a value needs to live.

But wait; I just said that the collection might access invalid memory if a value inside it is dropped before the collection, and now the compiler is allowing that to happen? What gives?

This is because the standard library pulls a sneaky trick on us. Collections like Vec or HashSet guarantee that they do not access their generic parameters in the destructor. They communicate this to the compiler using the unstable #[may_dangle] feature.

See also:

Moved variable still borrowing after calling `drop`?

"cannot move out of variable because it is borrowed" when rotating variables


答:
I think this is what you want:

```<code>create table login (username
varchar (100), password varchar (100), primary key (username));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), username varchar(100),foreign key (username) references
login (username));

create table answers (a_id int not null auto_increment, answer varchar (100), primary key (a_id), q_id int, foreign key (q_id) references questions (q_id));
</code>```

I tested it here: http://sqlfiddle.com/#!9/61ec2a

You need to:

```<code>1) Make Login.UserName unique
2) Declare UserName in the questions table
</code>```

Title: SQL wont allow me to add foreign key?

Body:
I think this is what you want:

create table login (username
varchar (100), password varchar (100), primary key (username));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), username varchar(100),foreign key (username) references
login (username));

create table answers (a_id int not null auto_increment, answer varchar (100), primary key (a_id), q_id int, foreign key (q_id) references questions (q_id));

I tested it here: http://sqlfiddle.com/#!9/61ec2a

You need to:

1) Make Login.UserName unique
2) Declare UserName in the questions table


问:
Managing dynamic plotting in matplotlib Animation module
I would like to have an iteratively plotted graph that allows for skipping to the next frame, stopping it and coming back to a previous frame.

I have looked at matplotlib Animation module which would be perfect if there was a way to implement the previous frame functionality (like run Animation backwards for a few frames when a key is pressed)

It would be nice to something like this:

```<code>def update_frame(i, data):
    fig.set_data(data[i])
</code>```

but in a way that I could explicitly manage whether the i iterator increases or decreases.

Is there a way to do that in matplotlib?
Should I look for a different python module?

答:
For a proper working answer with the Animation module see the answer of ImportanceOfBeingErnest

I have multiple issues with your intended functionality. How would the animation's progress work together with reversing? Would there be a video, but pressing a button starts playing it back? Or should there be individual steps of frames? I'm not sure I understand how an animation could be coupled to this reversal feature; I picture matplotlib animations to be essentially movies.

My other issue is a technical one: I'm not sure this can be done with matplotlib animations. The docs explain that a FuncAnimation superficially performs

```<code>for d in frames:
   artists = func(d, *fargs)
   fig.canvas.draw_idle()
   plt.pause(interval)
</code>```

where frames is essentially an iterable. It doesn't seem straightforward to me to dynamically adjust frames during the animation, so this is a technical obstacle.

Actually, the functionality you described works much better in my head in a widget-based approach. Buttons could propagate the "animation", or you could have a check button that modifies whether the next step goes forward or backward. Here's a simple proof of concept of what I mean:

```<code>import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np # just for dummy data generation

# generate dummy data
ndat = 20
x = np.linspace(0,1,ndat)
phi = np.linspace(0,2*np.pi,100,endpoint=False)
dat = np.transpose([x[:,None]*np.cos(phi),x[:,None]*np.sin(phi)],(1,2,0))

# create figure and axes
fig = plt.figure()
ax_pl = plt.subplot2grid((5,5),(0,0),colspan=5,rowspan=3)  # axes_plot
ax_bl = plt.subplot2grid((5,5),(4,0),colspan=2,rowspan=1)  # axes_button_left
ax_br = plt.subplot2grid((5,5),(4,3),colspan=2,rowspan=1)  # axes_button_right

# create forward/backward buttons
butt_l = Button(ax_bl, '\N{leftwards arrow}') # or u'' on python 2
butt_r = Button(ax_br, '\N{rightwards arrow}') # or u'' on python 2

# create initial plot
# store index of data and handle to plot as axes property because why not
ax_pl.idat = 0
hplot = ax_pl.scatter(*dat[ax_pl.idat].T)
ax_pl.hpl = hplot
ax_pl.axis('scaled')
ax_pl.axis([dat[...,0].min(),dat[...,0].max(),
            dat[...,1].min(),dat[...,1].max()])
ax_pl.set_autoscale_on(False)
ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))

# define and hook callback for buttons
def replot_data(ax_pl,dat):
    '''replot data after button push, assumes constant data shape'''
    ax_pl.hpl.set_offsets(dat[ax_pl.idat])
    ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))
    ax_pl.get_figure().canvas.draw()

def left_onclicked(event,ax=ax_pl,dat=dat):
    '''try to decrement data index, replot if success'''
    if ax.idat > 0:
        ax.idat -= 1
        replot_data(ax,dat)

def right_onclicked(event,ax=ax_pl,dat=dat):
    '''try to increment data index, replot if success'''
    if ax.idat < dat.shape[0]-1:
        ax.idat += 1
        replot_data(ax,dat)

butt_l.on_clicked(left_onclicked)
butt_r.on_clicked(right_onclicked)

plt.show()
</code>```

Note that I'm not really experienced with matplotlib widgets or GUIs in general, so don't expect the above to conform with best practices in the subject. I also added some additional parameters to be passed here and there, because I have an aversion to using global names, but this might be somewhat superstitious in this context; I honestly can't tell. Also, if you're defining these objects inside a class or a function, make sure to keep a reference to the widgets otherwise they might become unresponsive when accidentally garbage-collected.

The resulting figure has an axes for plotting the scatter plots, and there are two buttons to increment the slicing index. The data is shaped (ndat,100,2), where the trailing indices define 100 points in 2d space. A specific state:

(It doesn't have to be this ugly, I just didn't want to fiddle with the design.)

I could even imagine a setup where a timer automatically updates the plot, and the direction of the update can be set with a widget. I'm not sure how this could be done properly, but I would try to pursue this path for the kind of visualization you seem to be after.

Also note that the above approach is entirely missing blitting and other optimizations that FuncAnimation would do, but this will hopefully not interfere with your visualization.

Body:
I would like to have an iteratively plotted graph that allows for skipping to the next frame, stopping it and coming back to a previous frame.

I have looked at matplotlib Animation module which would be perfect if there was a way to implement the previous frame functionality (like run Animation backwards for a few frames when a key is pressed)

It would be nice to something like this:

def update_frame(i, data):
    fig.set_data(data[i])

but in a way that I could explicitly manage whether the i iterator increases or decreases.

Is there a way to do that in matplotlib?
Should I look for a different python module?

Body:
For a proper working answer with the Animation module see the answer of ImportanceOfBeingErnest

I have multiple issues with your intended functionality. How would the animation's progress work together with reversing? Would there be a video, but pressing a button starts playing it back? Or should there be individual steps of frames? I'm not sure I understand how an animation could be coupled to this reversal feature; I picture matplotlib animations to be essentially movies.

My other issue is a technical one: I'm not sure this can be done with matplotlib animations. The docs explain that a FuncAnimation superficially performs

for d in frames:
   artists = func(d, *fargs)
   fig.canvas.draw_idle()
   plt.pause(interval)

where frames is essentially an iterable. It doesn't seem straightforward to me to dynamically adjust frames during the animation, so this is a technical obstacle.

Actually, the functionality you described works much better in my head in a widget-based approach. Buttons could propagate the "animation", or you could have a check button that modifies whether the next step goes forward or backward. Here's a simple proof of concept of what I mean:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np # just for dummy data generation

# generate dummy data
ndat = 20
x = np.linspace(0,1,ndat)
phi = np.linspace(0,2*np.pi,100,endpoint=False)
dat = np.transpose([x[:,None]*np.cos(phi),x[:,None]*np.sin(phi)],(1,2,0))

# create figure and axes
fig = plt.figure()
ax_pl = plt.subplot2grid((5,5),(0,0),colspan=5,rowspan=3)  # axes_plot
ax_bl = plt.subplot2grid((5,5),(4,0),colspan=2,rowspan=1)  # axes_button_left
ax_br = plt.subplot2grid((5,5),(4,3),colspan=2,rowspan=1)  # axes_button_right

# create forward/backward buttons
butt_l = Button(ax_bl, '\N{leftwards arrow}') # or u'' on python 2
butt_r = Button(ax_br, '\N{rightwards arrow}') # or u'' on python 2

# create initial plot
# store index of data and handle to plot as axes property because why not
ax_pl.idat = 0
hplot = ax_pl.scatter(*dat[ax_pl.idat].T)
ax_pl.hpl = hplot
ax_pl.axis('scaled')
ax_pl.axis([dat[...,0].min(),dat[...,0].max(),
            dat[...,1].min(),dat[...,1].max()])
ax_pl.set_autoscale_on(False)
ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))

# define and hook callback for buttons
def replot_data(ax_pl,dat):
    '''replot data after button push, assumes constant data shape'''
    ax_pl.hpl.set_offsets(dat[ax_pl.idat])
    ax_pl.set_title('{}/{}'.format(ax_pl.idat,dat.shape[0]-1))
    ax_pl.get_figure().canvas.draw()

def left_onclicked(event,ax=ax_pl,dat=dat):
    '''try to decrement data index, replot if success'''
    if ax.idat > 0:
        ax.idat -= 1
        replot_data(ax,dat)

def right_onclicked(event,ax=ax_pl,dat=dat):
    '''try to increment data index, replot if success'''
    if ax.idat < dat.shape[0]-1:
        ax.idat += 1
        replot_data(ax,dat)

butt_l.on_clicked(left_onclicked)
butt_r.on_clicked(right_onclicked)

plt.show()

Note that I'm not really experienced with matplotlib widgets or GUIs in general, so don't expect the above to conform with best practices in the subject. I also added some additional parameters to be passed here and there, because I have an aversion to using global names, but this might be somewhat superstitious in this context; I honestly can't tell. Also, if you're defining these objects inside a class or a function, make sure to keep a reference to the widgets otherwise they might become unresponsive when accidentally garbage-collected.

The resulting figure has an axes for plotting the scatter plots, and there are two buttons to increment the slicing index. The data is shaped (ndat,100,2), where the trailing indices define 100 points in 2d space. A specific state:

(It doesn't have to be this ugly, I just didn't want to fiddle with the design.)

I could even imagine a setup where a timer automatically updates the plot, and the direction of the update can be set with a widget. I'm not sure how this could be done properly, but I would try to pursue this path for the kind of visualization you seem to be after.

Also note that the above approach is entirely missing blitting and other optimizations that FuncAnimation would do, but this will hopefully not interfere with your visualization.


问:
update panel webcontrol required form field
I created a simple control which uses an update panel with a button click trigger and yes a script manager above the control. Click the button and a label is updated with the current time and this has worked fine for 6 years

Today, I changed the page to be responsive with Bootstrap but this is irrelevant to this question.

The control was added to a page which has labels and textboxes (simple form with first name / last name).

```<code><asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control input-lg" Placeholder="Your First Name" MaxLength="20" Required="true"></asp:TextBox>
</code>```

If I remove:

```<code>Required="true"
</code>```

and click the button in the control the date / time updates but placing this back stops the date / time updating. I need to use both as I wish for the first name to be required but also for the time to update

Simple Example:

```<code><asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
        <asp:Button ID="btnRefreshTime" runat="server" Text="Refresh Time" OnClick="btnRefreshTime_Click" />
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnRefreshTime" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>
</code>```

Code Behind:

```<code>Protected Sub btnRefreshTime_Click(sender As Object, e As EventArgs)
    lblTime.Text = DateTime.Now.ToString()
End Sub
</code>```

What am I doing wrong and what would I need to do to resolve it without opening the form up to abuse (script attacks) etc? I don't wish to add the following to the page directive:

```<code>ValidateRequest="false"
</code>```

Thank you in advance

答:
Probabily the button server side event is prevented to execute due to the client side validation of required = "true".

Try to change the button with somewhat else which does not trigger client side validation by design. I would try with a LinkButton.

Body:
I created a simple control which uses an update panel with a button click trigger and yes a script manager above the control. Click the button and a label is updated with the current time and this has worked fine for 6 years

Today, I changed the page to be responsive with Bootstrap but this is irrelevant to this question.

The control was added to a page which has labels and textboxes (simple form with first name / last name).

<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control input-lg" Placeholder="Your First Name" MaxLength="20" Required="true"></asp:TextBox>

If I remove:

Required="true"

and click the button in the control the date / time updates but placing this back stops the date / time updating. I need to use both as I wish for the first name to be required but also for the time to update

Simple Example:

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
        <asp:Button ID="btnRefreshTime" runat="server" Text="Refresh Time" OnClick="btnRefreshTime_Click" />
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnRefreshTime" EventName="Click" />
    </Triggers>
</asp:UpdatePanel>

Code Behind:

Protected Sub btnRefreshTime_Click(sender As Object, e As EventArgs)
    lblTime.Text = DateTime.Now.ToString()
End Sub

What am I doing wrong and what would I need to do to resolve it without opening the form up to abuse (script attacks) etc? I don't wish to add the following to the page directive:

ValidateRequest="false"

Thank you in advance


答:
The correct way is,

```<code>create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (user_id) references
login (user_id));
</code>```

Title: SQL wont allow me to add foreign key?

Body:
The correct way is,

create table login (user_id int NOT NULL AUTO_INCREMENT, username
varchar (100), password varchar (100), primary key (user_id));

create table questions (q_id int not null auto_increment, question
varchar (100), primary key (q_id), foreign key (user_id) references
login (user_id));


问:
Display Array in a JTextArea with ability to scroll
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.

```<code>public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;

// this is called in my initComponent method to create both
    textAreaDisplay = new JTextArea();

    for (Object obj : lake)
    {
        textAreaDisplay.append(obj.toString() + " ");
    }

    spDisplay = new JScrollPane(textAreaDisplay);

    textAreaDisplay.setLineWrap(true);
    textAreaDisplay.setWrapStyleWord(true);
    spDisplay.setPreferredSize(new Dimension(500, 500));

    // this is called in my createEvents method. After creating lakes in the database
    // it will display the else statement but it is empty

    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {

            }

        }
    });
</code>```

Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.

答:
Some obvious issues:

```<code>textAreaDisplay = new JTextArea();
</code>```

A JTextArea should be created with code like:

```<code> textAreaDisplay = new JTextArea(5, 20);
</code>```

By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.

```<code>spDisplay.setPreferredSize(new Dimension(500, 500));
</code>```

Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.

```<code>textAreaDisplay.append(obj.toString() + " ");
</code>```

I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.

Body:
I am creating a GUI that will allow the user to input Lake information for the state of Florida and then has the ability to display that lake information. I want the display information to be in a JOptionPane.showMessageDialog that has the ability to scroll through the ArrayList of all the lake names. I am able to add the lakes into the ArrayList but they will not display in my JOptionPane and it is blank. I know it is reading something in the ArrayList since it is opening that window. Here is the code below in snippets as the whole thing would be cra.

public static ArrayList<Lakes> lake = new ArrayList<Lakes>();
private JTextArea textAreaDisplay;
private JScrollPane spDisplay;

// this is called in my initComponent method to create both
    textAreaDisplay = new JTextArea();

    for (Object obj : lake)
    {
        textAreaDisplay.append(obj.toString() + " ");
    }

    spDisplay = new JScrollPane(textAreaDisplay);

    textAreaDisplay.setLineWrap(true);
    textAreaDisplay.setWrapStyleWord(true);
    spDisplay.setPreferredSize(new Dimension(500, 500));

    // this is called in my createEvents method. After creating lakes in the database
    // it will display the else statement but it is empty

    btnDisplayLake.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try
            {
                if (lake.size() == 0)
                {
                    JOptionPane.showMessageDialog(null, "No Lakes in database!");
                }
                else
                    JOptionPane.showMessageDialog(null, spDisplay, "Display Lakes", JOptionPane.YES_NO_OPTION);
            }
            catch (Exception e1)
            {

            }

        }
    });

Thank you for any help you can provide. I have been racking my brain for a few days on this. Been able to get other stuff accomplished but coming back to this issue.

Body:
Some obvious issues:

textAreaDisplay = new JTextArea();

A JTextArea should be created with code like:

 textAreaDisplay = new JTextArea(5, 20);

By specifying the row/column the text area will be able to calculate its own preferred size. Scrollbars should appear when the preferred size of the text area is greater than the size of the scroll pane.

spDisplay.setPreferredSize(new Dimension(500, 500));

Don't use setPreferredSize(). The scroll area will calculate its preferred size based on the preferred size of the text area.

textAreaDisplay.append(obj.toString() + " ");

I would think you want each Lake to show on a different line, so I would append "\n" instead of the space.


问:
Conda openpxyl install results in No module named 'openpyxl'
I installed several conda environments with different Python versions.

After activating my Python 3.5 environment I have installed openpxyl via the line given here: https://anaconda.org/anaconda/openpyxl

However, when I try to import I get

ImportError: No module named 'openpxyl'

When I type conda list I do see

openpyxl                  2.4.7                    py35_0    anaconda

in the list.

(code to import is just import openpyxl or from openpyxl import *)

Any suggestions? Thanks!

答:
You can try deleting all openpyxl material then reinstall it using pip.

that's how i solved my problem at least.


问:
How to store uploaded files in a directory of the main domain from a subdomain upload form
please how can store uploaded file in my main domain directory should it be like this:</p>

```<code>move_uploaded_file(https://example.com/uploads)
</code>```

答:
First step is to start here with handling uploaded files:

http://php.net/manual/en/function.move-uploaded-file.php

The first example is almost exactly what you want:

```<code><?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>
</code>```

You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:

```<code>$uploads_dir = __DIR__ . '/../public_html/uploads';
</code>```

__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.

The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.

Body:
please how can store uploaded file in my main domain directory should it be like this:

move_uploaded_file(https://example.com/uploads)

Body:
First step is to start here with handling uploaded files:

http://php.net/manual/en/function.move-uploaded-file.php

The first example is almost exactly what you want:

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // basename() may prevent filesystem traversal attacks;
        // further validation/sanitation of the filename may be appropriate
        $name = basename($_FILES["pictures"]["name"][$key]);
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

You will need to make two edits. The $uploads_dir will need to have a relative path to where the files are uploaded. Let's say your form is in the root of your subdomain in subdomain.example.com/ and you want to move them to public_html/uploads. Your new $uploads_dir should look like the following:

$uploads_dir = __DIR__ . '/../public_html/uploads';

__DIR__ will give you the current director your php file is running in. This allows you to create a relative path to other directories.

The second edit is to update the $_FILES array to loop through the proper structure of what you are uploading. It might not be pictures as in the example.


问:
SQL Server: assigning string literals to a parameter
I need to do something like:

```<code>EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
   N'@pat nvarchar(max)', @pat=Tom
</code>```

My question is about the last parameter.

When the value to assign is a "simple" string, i.e. no spaces etc, I could use something like @pat=Tom, no quotes needed.

However, when the value to assign ends with the % character for example, it won't work, and I have to do something like @pat=N'Tom%'.

Is this how the syntax of assigning a string literal is defined?

Does it also mean that if my value contains the single quotation mark, I would have to escape it manually?

答:
I am surprised that it works with no quotes.  This must be a peculiarity of exec.

Always include the single quotes:

```<code>EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
   N'@pat nvarchar(max)', @pat='Tom';
</code>```

According to the documentation:

If the value of a parameter is an object name, character string, or
  qualified by a database name or schema name, the whole name must be
  enclosed in single quotation marks. If the value of a parameter is a
  keyword, the keyword must be enclosed in double quotation marks.

I don't know why it would work without the single quotes.

Body:
I need to do something like:

EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
   N'@pat nvarchar(max)', @pat=Tom

My question is about the last parameter.

When the value to assign is a "simple" string, i.e. no spaces etc, I could use something like @pat=Tom, no quotes needed.

However, when the value to assign ends with the % character for example, it won't work, and I have to do something like @pat=N'Tom%'.

Is this how the syntax of assigning a string literal is defined?

Does it also mean that if my value contains the single quotation mark, I would have to escape it manually?

Body:
I am surprised that it works with no quotes.  This must be a peculiarity of exec.

Always include the single quotes:

EXEC sp_ExecuteSQL N'select * from Members where Name like @pat',
   N'@pat nvarchar(max)', @pat='Tom';

According to the documentation:

If the value of a parameter is an object name, character string, or
  qualified by a database name or schema name, the whole name must be
  enclosed in single quotation marks. If the value of a parameter is a
  keyword, the keyword must be enclosed in double quotation marks.

I don't know why it would work without the single quotes.


问:
Converting find() in matlab to python
I am converting a code from Matlab to Python. The code in Matlab is:

```<code>x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;
</code>```

Both arrays are of same size, and I am basically creating a mask.

I read here that nonzero() in numpy is equivalent to find(), so I used that. In Python, I have dstc for sEdgepoints and dst for sNorm. I have also directly put in lowT = 60. So, the code was

```<code>x = np.nonzero(dstc > 0 and dst < 60)
dstc[x] = 0
</code>```

But, I get following error:

```<code>Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
</code>```

I read about the usage of a.any()/a.all() in this post, and I am not sure how that will work. So, I have two questions:
1. If it does, which array to use?
2. If I am correct and it does not work, how to convert the code?

答:
Try np.argwhere()
 (and note the importance of the () around the inequalities):

```<code>>>X=np.array([1,2,3,4,5])
>>Y=np.array([7,6,5,4,3])
>>ans = np.argwhere((X>3) & (Y<7))
>>ans

array([[3],
   [4]])
</code>```

Title: Converting find() in matlab to python

Body:
I am converting a code from Matlab to Python. The code in Matlab is:

x = find(sEdgepoints > 0 & sNorm < lowT);
sEdgepoints(x)=0;

Both arrays are of same size, and I am basically creating a mask.

I read here that nonzero() in numpy is equivalent to find(), so I used that. In Python, I have dstc for sEdgepoints and dst for sNorm. I have also directly put in lowT = 60. So, the code was

x = np.nonzero(dstc > 0 and dst < 60)
dstc[x] = 0

But, I get following error:

Traceback (most recent call last):
File "C:\Python27\Sheet Counter\customsobel.py", line 32, in <module>
    x = np.nonzero(dstc > 0 and dst < 60)
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

I read about the usage of a.any()/a.all() in this post, and I am not sure how that will work. So, I have two questions:
1. If it does, which array to use?
2. If I am correct and it does not work, how to convert the code?

Body:
Try np.argwhere()
 (and note the importance of the () around the inequalities):

>>X=np.array([1,2,3,4,5])
>>Y=np.array([7,6,5,4,3])
>>ans = np.argwhere((X>3) & (Y<7))
>>ans

array([[3],
   [4]])


问:
TypeError: undefined is not an object - reactjs
I am running some tests on components for a small project, and I keep getting the same error for the one component. When I run the project, everything operates as intended, however when I test I can't get rid of this TypeError: undefined is not an object(this.props.searchResults.map). I am confused by this because, as I said, it runs fine. Is it a problem with the way I'm writing my tests or is there an error in my code? The component is below:

```<code>class Results extends React.Component {
render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul className="the-list">
            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};
        </ul>
    );
  }
}
</code>```

答:
It seems like this.props.searchResults is undefined in your test. There are two options here:

1: Define a default prop for searchResults:

```<code>Results.defaultProps = {
    searchResults: []
}
</code>```

2: Define searchResults in your test:

```<code><Results searchResults={[]} />
</code>```

Body:
I am running some tests on components for a small project, and I keep getting the same error for the one component. When I run the project, everything operates as intended, however when I test I can't get rid of this TypeError: undefined is not an object(this.props.searchResults.map). I am confused by this because, as I said, it runs fine. Is it a problem with the way I'm writing my tests or is there an error in my code? The component is below:

class Results extends React.Component {
render(){
    const { handleEvent, searchResults } = this.props;
    return(

            {this.props.searchResults.map((result, idx) =>
                <ResultItem
                    key={`${result.trackId}-${idx}`}
                    trackName={result.trackName}
                    track={result}
                    handleClick={handleEvent} />
                )};

    );
  }
}

Body:
It seems like this.props.searchResults is undefined in your test. There are two options here:

1: Define a default prop for searchResults:

Results.defaultProps = {
    searchResults: []
}

2: Define searchResults in your test:

<Results searchResults={[]} />


问:
How to confirm if a popover is displayed on mouse over a element and how to get the inside text of the displayed popover using protractor
My protractor code

```<code>var meover = element(by.xpath('/html/body/div[2]/div[1]/div[2]/span[1]/code'));

meover.getText().then(console.log);

browser.actions().mouseMove(meover).perform();

browser.sleep(2000);
</code>```

How to get popover text?? see the images for better understanding

Images

答:
```<code>var meover = element(by.xpath('/html/body/div[2]/div[1]/div[2]/span[1]/code'));
var toolbox = 'selector here';
browser.actions().mouseMove(meover).perform().then(() => {
    toolbox.getText().then((text) => {
        console.log(text);
    });
});
</code>```

Body:
My protractor code

var meover = element(by.xpath('/html/body/div[2]/div[1]/div[2]/span[1]/code'));

meover.getText().then(console.log);

browser.actions().mouseMove(meover).perform();

browser.sleep(2000);

How to get popover text?? see the images for better understanding

Images


答:
You could implement it yourself like:

```<code>x = [[i,j] for i, j in zip(sEdgepoints , sNorm ) if i > 0 and j < lowT]
</code>```

Will give you a list of of lists corresponding to your the matching constraints.
I guess this might not be exactly what you are looking for.

Maybe look at the pandas module, it makes masking more comfortable than plain python or numpy:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html

Title: Converting find() in matlab to python

Body:
You could implement it yourself like:

x = [[i,j] for i, j in zip(sEdgepoints , sNorm ) if i > 0 and j < lowT]

Will give you a list of of lists corresponding to your the matching constraints.
I guess this might not be exactly what you are looking for.

Maybe look at the pandas module, it makes masking more comfortable than plain python or numpy:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mask.html


问:
Admin-on-rest - how to sync other components with query filtered from List?
I want to implement this structure in the page:

1. Cards with summary (revenue, users, etc.)

2. Map from google maps

3. List element

Inside List element there is filtering. I am stuck how to user filter options when filtering list to represent filtered information in the map and cards.

As @trixn recommended I am using this structure:

```<code>// app.js

<Admin restClient={jsonServerRestClient('http://jsonplaceholder.typicode.com')}>
    <Resource name="posts" list={MyCustomPostList} /* other views */ />
</Admin>

// MyCustomPostList.js
class MyCustomPostList extends React.Component {
render() {
    const {myOwnProp, ...otherProps} = this.props;

    return (
        <div>
            // render your own components here
            <AnyComponent myOwnProp={myOwnProp} />
            <AGoogleMapsComponent />

            // render the normal <List> component
            <List {...otherProps}>
                <Datagrid>
                    <TextField source="id" />
                    <TextField source="title" />
                    <TextField source="body" />
                </Datagrid>
             </List>
        </div>
    );
}
}
</code>```

Now I am failing to send required data to Maps and AnyComponent.
So I either have to pass same data to Maps and AnyComponent or somehow synchornize filters that are being used in the List component.

How shall I achieve this?

答:
Thank you! I would know how to connect new actions. But I am lost how to connect to already used actions to pass Filter options to Maps and AnyComponent, so I could show relevant information there, which should update its state after Filters are being triggered in List component.

You do not connect to actions. You dispatch them to alter the state of the redux store. It is important that you fully understand the concepts of redux otherwise it will be very hard for you to build this kind of custom app. To make sure data is only flowing from top to bottom components can only listen to changes of the store and not to actions.

So basically you have two options:

1. Create your own <List> component

Quoted from the admin-on-rest docs:

Admin-on-rest was build with customization in mind. You can replace any admin-on-rest component with a component of your own, for instance to display a custom list layout, or a different edition form for a given resource.

If you only want to display your additional elements in your list view you can wrap the <List> component instead of the <Resource> component. The <List> component receives the entities in a prop "data" and the filtered ids in a prop "ids". You can use that to display it in your own component. E.g. if you want to manage a list of locations and show a google map inside the list component:

import React from 'react';
import { List } from 'admin-on-rest';

const LocationsList = props => (
    // render your own components
    <MyGoogleMapsComponent  data={this.props.data} ids={this.props.ids}>

    // render the admin-on-rest <List> component
    <List {...props}>
        // render the DataGrid
    </List>
);
```

<p>Then you can pass your custom list to the <code><Resource></code> component:</p>

```<Admin>
    <Resource name="locations" list={LocationList} />
</Admin>
```

<p>When you filter your locations in the list the updated query will be passed to your <code><LocationList></code> and it will re-render with the new locations. But remember that this will only show your google map inside the list view of your admin page.</p>

<p><strong>2. Connect your component to the redux store.</strong> </p>

<p>Do this only if you want your component, e.g. the google map, to be displayed outside of your list view. This one is much more advanced as you will need to learn a lot more about the internals of <code>admin-on-rest</code>. You will have to connect your custom component to the redux store. You can do that with the <code>connect()</code> function from the <code>react-redux</code> package:</p>

```// in MyGoogleMapsComponent.js
import React from 'react';
import { connect } from 'react-redux';

const LocationMap = ({locations}) => (
    //render something based on the props
);

const mapStateToProps = (state, props) => {
    // state.admin contains all the registered resources with their name as a key
    const locationsResource = state.admin.locations;

    // every resource has a "data" object with all entities mapped by id
    const allLocations = locationsResource.data;

    // every resource has a "list" object that has an array of ids of the currently filtered entities
    const filteredIDs = locationsResource.list.ids;

    return {
        locations: filteredIDs.map(id => allLocations[id]),
    };
};

// connect your component to the store
export default connect(mapStateToProps)(LocationsList)
```

mapStateToProps is a function that takes the current state in your store and the props of your component and returns an object containing additional props to be passed to your component.

Also this approach uses internals of the implementation of the admin-on-rest components. Some of the props you'll need to use are not part of the api and could in the worst case suddenly change in which case your app may not work anymore if you update to a new version of admin-on-rest. So keep in mind you may need to update your implementation when breaking changes occur.

If you only want to access the filters itself, they are stored in every resource under yourResourceName.list.params.filter with the name of the filter as the key and the value as the value...

Hint: If you want to see, how data inside the store of an admin-on-rest app ist stored in a real life example install the Redux DevTools for google chrome and open the admin-on-rest demo. You can then open the inspection bar and there will be a new tab redux where you can see the contents of the redux store and all the actions that get dispatched when interacting with the app. This way you it will be much easier to understand how admin-on-rest works.

Body:
I want to implement this structure in the page:

1. Cards with summary (revenue, users, etc.)

2. Map from google maps

3. List element

Inside List element there is filtering. I am stuck how to user filter options when filtering list to represent filtered information in the map and cards.

As @trixn recommended I am using this structure:

// app.js

<Admin restClient={jsonServerRestClient('http://jsonplaceholder.typicode.com')}>
    <Resource name="posts" list={MyCustomPostList} /* other views */ />
</Admin>

// MyCustomPostList.js
class MyCustomPostList extends React.Component {
render() {
    const {myOwnProp, ...otherProps} = this.props;

    return (

            // render your own components here
            <AnyComponent myOwnProp={myOwnProp} />
            <AGoogleMapsComponent />

            // render the normal <List> component
            <List {...otherProps}>
                <Datagrid>
                    <TextField source="id" />
                    <TextField source="title" />
                    <TextField source="body" />
                </Datagrid>
             </List>

    );
}
}

Now I am failing to send required data to Maps and AnyComponent.
So I either have to pass same data to Maps and AnyComponent or somehow synchornize filters that are being used in the List component.

How shall I achieve this?

Body:
Thank you! I would know how to connect new actions. But I am lost how to connect to already used actions to pass Filter options to Maps and AnyComponent, so I could show relevant information there, which should update its state after Filters are being triggered in List component.

You do not connect to actions. You dispatch them to alter the state of the redux store. It is important that you fully understand the concepts of redux otherwise it will be very hard for you to build this kind of custom app. To make sure data is only flowing from top to bottom components can only listen to changes of the store and not to actions.

So basically you have two options:

1. Create your own <List> component

Quoted from the admin-on-rest docs:

Admin-on-rest was build with customization in mind. You can replace any admin-on-rest component with a component of your own, for instance to display a custom list layout, or a different edition form for a given resource.

If you only want to display your additional elements in your list view you can wrap the <List> component instead of the <Resource> component. The <List> component receives the entities in a prop "data" and the filtered ids in a prop "ids". You can use that to display it in your own component. E.g. if you want to manage a list of locations and show a google map inside the list component:

import React from 'react';
import { List } from 'admin-on-rest';

const LocationsList = props => (
    // render your own components
    <MyGoogleMapsComponent  data={this.props.data} ids={this.props.ids}>

    // render the admin-on-rest <List> component
    <List {...props}>
        // render the DataGrid
    </List>
);

Then you can pass your custom list to the <Resource> component:

<Admin>
    <Resource name="locations" list={LocationList} />
</Admin>

When you filter your locations in the list the updated query will be passed to your <LocationList> and it will re-render with the new locations. But remember that this will only show your google map inside the list view of your admin page.

2. Connect your component to the redux store.

Do this only if you want your component, e.g. the google map, to be displayed outside of your list view. This one is much more advanced as you will need to learn a lot more about the internals of admin-on-rest. You will have to connect your custom component to the redux store. You can do that with the connect() function from the react-redux package:

// in MyGoogleMapsComponent.js
import React from 'react';
import { connect } from 'react-redux';

const LocationMap = ({locations}) => (
    //render something based on the props
);

const mapStateToProps = (state, props) => {
    // state.admin contains all the registered resources with their name as a key
    const locationsResource = state.admin.locations;

    // every resource has a "data" object with all entities mapped by id
    const allLocations = locationsResource.data;

    // every resource has a "list" object that has an array of ids of the currently filtered entities
    const filteredIDs = locationsResource.list.ids;

    return {
        locations: filteredIDs.map(id => allLocations[id]),
    };
};

// connect your component to the store
export default connect(mapStateToProps)(LocationsList)

mapStateToProps is a function that takes the current state in your store and the props of your component and returns an object containing additional props to be passed to your component.

Also this approach uses internals of the implementation of the admin-on-rest components. Some of the props you'll need to use are not part of the api and could in the worst case suddenly change in which case your app may not work anymore if you update to a new version of admin-on-rest. So keep in mind you may need to update your implementation when breaking changes occur.

If you only want to access the filters itself, they are stored in every resource under yourResourceName.list.params.filter with the name of the filter as the key and the value as the value...

Hint: If you want to see, how data inside the store of an admin-on-rest app ist stored in a real life example install the Redux DevTools for google chrome and open the admin-on-rest demo. You can then open the inspection bar and there will be a new tab redux where you can see the contents of the redux store and all the actions that get dispatched when interacting with the app. This way you it will be much easier to understand how admin-on-rest works.


问:
Keep the same distance between 2 Path2D onMouseDragged
I have let's say two Path2D, one contains the other. When I move a point from first shape, the second shape move the same, but because of the angle changing, the distance between shapes changes too (and the final result...).

I have this so far, with hard coded points for the second triangle(innerTriangle):

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

class DragTest extends JPanel {

    private final class MouseDrag extends MouseAdapter {
        private boolean dragging = false;
        private Point last;

        @Override
        public void mousePressed(MouseEvent m) {
            if(dRect.contains(m.getPoint())){
                last = m.getPoint();
                dragging = isInsideRect(dRect, last);
                if (!dragging) {
                    x = last.x;
                    y = last.y;
                    width = 0;
                    height = 0;
                }
            }
            repaint();
        }

        @Override
        public void mouseReleased(MouseEvent m) {
            last = null;
            dragging = false;
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent m) {
            if(dRect.contains(m.getPoint())){
                int dx = m.getX() - last.x;
                int dy = m.getY() - last.y;
                if (dragging) {
                    x += dx;
                    y += dy;
                } else {
                    width += dx;
                    height += dy;
                }
                last = m.getPoint();
            }
            repaint();
        }
    }

    private int x;
    private int y;
    private int width;
    private int height;
    private Rectangle2D.Float dRect ;
    private Path2D triangle = new Path2D.Float();
    private Path2D innerTriangle = new Path2D.Float();

    private Point p1;
    private Point p2 = new Point(5,200);
    private Point p3 = new Point(400,200);

    private MouseDrag mouseDrag;

    public DragTest() {
        setBackground(Color.WHITE);
        dRect = new Rectangle2D.Float(x, y, 10+width, 10+height);
        mouseDrag = new MouseDrag();
        addMouseListener(mouseDrag);
        addMouseMotionListener(mouseDrag);

    }

    public boolean isInsideRect(Shape s, Point point) {
            return s.contains(point);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        dRect = new Rectangle2D.Float(x, y , 10, 10);
        g2.draw(dRect);

        triangle.reset();
        triangle.moveTo(dRect.getCenterX(), dRect.getCenterY());
        p1 = new Point((int)dRect.getCenterX(), (int)dRect.getCenterY());
        triangle.lineTo(p2.x, p2.y);
        triangle.lineTo(p3.x, p3.y);
        triangle.closePath();

       innerTriangle.reset();
       innerTriangle.moveTo(p1.x+10, p1.y+17);
       innerTriangle.lineTo(p2.x+10, p2.y-10);
       innerTriangle.lineTo(p3.x-47, p3.y-10);
       innerTriangle.closePath();

        g2.draw(triangle);
        g2.draw(innerTriangle);

        g2.dispose();

    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setSize(800, 600);
        jFrame.add(new DragTest());
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
</code>```

How can I maintain the same distance all around (say 10px), programmatically?

The distance between the outer triangle and the red (inner) triangle should be the same always, in all directions. Any idea?

SEE IMAGE

Currently I'm working on something:

```<code>// Calculate distance from point to line
public double pointToLineDistance(Point A, Point B, Point P) {
    double normalLength = Math.sqrt((B.x-A.x)*(B.x-A.x)+(B.y-A.y)*(B.y-A.y));
    return Math.abs((P.x-A.x)*(B.y-A.y)-(P.y-A.y)*(B.x-A.x))/normalLength;
}

// initially set :
// pi1.x = p1.x;
// pi1.y = p1.y;
// -------------------- Then ------------------------------

 while(pointToLineDistance(p1, p3, pi1) == 10 && pointToLineDistance(p1, p2, pi1) == 10){
        pi1.y++;
        pi1.x++;
        pi1.setLocation(pi1.x, pi1.y);
    }
</code>```

... but doesn't work. HELP!!! :)

SEE IMAGE FOR THE CODE ABOVE

Thank You!

答:
Keeping even spacing at line joins.

This problem needs a illistration to help explain. The solution is for one corner but the process will work for as many corners as you want.

Given two lines joined at one end find the two line offset by a fixed amount from both lines

Bold letters (example A) represent points. Lines as bold joined letters from start to end (example AB is line from A to B and BA is the line from B to A)

Given the lines AB and BC find the lines A1D and DC1 so that the area x distance from the original lines.

```<code>// all variables are assumed declared and floats or doubles (up to you)
 Ax = 10;   // x of Point A
 Ay = 200;  // y of A
 Bx = 200;  // x,y of B
 By = 200;
 Cx = 40;   // C
 Cy = 10;

 Dist = 40; // distance from the line
</code>```

Looking at the image we can see some nice symmetry that can be exploited to find the solution. The lines EB, BF, FD and DE are all the same length. That means that if we solve the right triangle gBF we can move along the line BA from B to g and from g to h as gh is the same length as FB

From this point the line AB is turned around to BA

Finding a point x distance from a line

To find the point A1 we find the normalised vector along the line BA

Finding A1

```<code>// get the vector from B to A and normalise it
BAx = Ax - Bx;
BAy = Ay - By;
leng = Math.sqrt(BAx * BAx + BAy * BAy);
BAx /= leng; // The vector BA is 1 pixel (unit long)
BAy /= leng;
</code>```

The normal moves along the line to go at 90 deg just swap x and y negating y

```<code>A1x = Ax - BAy * Dist;
A1y = Ay + BAx * Dist;
</code>```

Now do the same for the point C1

```<code>BCx = Cx - Bx;
BCy = Cy - By;
leng = Math.sqrt(BCx * BCx + BCy * BCy);
BCx /= leng;
BCy /= leng;
C1x = Cx + BCy * Dist;  // move in the opposite direction than from A
C1y = Cy - BCx * Dist;
</code>```

Finding D by solving the triangle FBg

If you only needed to find D (eg you are doing this on a closed line, triangle) you still have to get the normalised vectors BA and BC that were worked out above. BAx, BAy and BCx, BCy

To find the sin of the angle EBF use get the cross product of the two normalised vectors BA and BC. The sin of an angle relates the opposite side of a triangle Fg to the Hypotenuse BF as sin(ang) = opp/hypt

```<code>cross = BAx * BCy - BAy * BCx; // gets the sin of the angle
// you should check cross of zero. If so there is no solution
FBlen = Dist / cross; // gets the hypot the length of FB
</code>```

Now we have FB we know the distance gh we could get gB as we have two sides of a right triangle and the length of gB = sqrt(FB*FB+Dist*Dist) but this will become an issue if the angle of ABC is greater than 90 deg. Not only do we need to know the length but the direction (positive or negative).

We can solve for Bg using the dot product which finds the cosine of the angle ABC which relates the hypotenuse to the adjacent side of a right triangle cos(ang) = BF/Bg

```<code>dot = BAx * BCx + BAy * BCy;
Bglen = FBlen * dot;
</code>```

Now we can move along the line BA to g then to h then turn 90deg and out to D

```<code>// move from B to h using the normal vec of the line BA time the sum
// of the length FB
hx = Bx + BAx * (FBlen + BgLen);
hy = By + BAy * (FBlen + BgLen);
Dx = hx - BAy * Dist;  // then at 90 deg dist along to D
Dy = hy + BAx * Dist;
</code>```

And you are all done you have the points A1, D, C1

Code in one go

You may also prefer to use a vector lib to do the adding, normalising,cross product etc...

```<code>Ax = 10;   // x of Point A
Ay = 200;  // y of A
Bx = 200;  // x,y of B
By = 200;
Cx = 40;   // C
Cy = 10;

Dist = 40;  // dist out

BAx = Ax - Bx;
BAy = Ay - By;
BCx = Cx - Bx;
BCy = Cy - By;
leng = Math.sqrt(BAx * BAx + BAy * BAy);
BAx /= leng;
BAy /= leng;
leng = Math.sqrt(BCx * BCx + BCy * BCy);
BCx /= leng;
BCy /= leng;

// get inside end points
A1x = Ax - BAy * Dist;
A1y = Ay + BAx * Dist;
C1x = Cx + BCy * Dist;
C1y = Cy - BCx * Dist;

FBlen = Dist / (BAx * BCy - BAy * BCx);
FBlen += FBlen * (BAx * BCx + BAy * BCy);
Dx = Bx + BAx * FBlen - BAy * Dist;;
Dy = By + BAy * FBlen + BAx * Dist;
</code>```

Edge cases

You can do this for any number of lines as long as you go in the same direction and that your vectors are from the corners out. There are a few caveats.

If he distance between two corner points it too short the inside lines will overlap and cause problems. There is no simple solution to this apart from fixing the corner spacing and limiting the width.

Will fail if the lines are parallel. Check the result of the cross product, when zero or very close to zero line AB and BC are near parallel.

Miter extent. When the angle between the two lines starts to get near 360deg the point D will start getting further and further out. As the angle approaches 360deg or 2 Radians the distance from B to D will approch infinity. Again check cross product for zero or near zero. You can also set a miter limit by rounding the corner. or truncating it.

Mitering a corner. The above answer has given you the information you need to solve the above image. The distance DF is fixed to max miter limit, if the point B is further than F from D then find the point F. Look for symmetry and like triangles to find the other points.

If you are making long lines you will be best of doing thein on each side of the line. By defining the center not the edge you get a better result.

Body:
I have let's say two Path2D, one contains the other. When I move a point from first shape, the second shape move the same, but because of the angle changing, the distance between shapes changes too (and the final result...).

I have this so far, with hard coded points for the second triangle(innerTriangle):

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

class DragTest extends JPanel {

    private final class MouseDrag extends MouseAdapter {
        private boolean dragging = false;
        private Point last;

        @Override
        public void mousePressed(MouseEvent m) {
            if(dRect.contains(m.getPoint())){
                last = m.getPoint();
                dragging = isInsideRect(dRect, last);
                if (!dragging) {
                    x = last.x;
                    y = last.y;
                    width = 0;
                    height = 0;
                }
            }
            repaint();
        }

        @Override
        public void mouseReleased(MouseEvent m) {
            last = null;
            dragging = false;
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent m) {
            if(dRect.contains(m.getPoint())){
                int dx = m.getX() - last.x;
                int dy = m.getY() - last.y;
                if (dragging) {
                    x += dx;
                    y += dy;
                } else {
                    width += dx;
                    height += dy;
                }
                last = m.getPoint();
            }
            repaint();
        }
    }

    private int x;
    private int y;
    private int width;
    private int height;
    private Rectangle2D.Float dRect ;
    private Path2D triangle = new Path2D.Float();
    private Path2D innerTriangle = new Path2D.Float();

    private Point p1;
    private Point p2 = new Point(5,200);
    private Point p3 = new Point(400,200);

    private MouseDrag mouseDrag;

    public DragTest() {
        setBackground(Color.WHITE);
        dRect = new Rectangle2D.Float(x, y, 10+width, 10+height);
        mouseDrag = new MouseDrag();
        addMouseListener(mouseDrag);
        addMouseMotionListener(mouseDrag);

    }

    public boolean isInsideRect(Shape s, Point point) {
            return s.contains(point);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        dRect = new Rectangle2D.Float(x, y , 10, 10);
        g2.draw(dRect);

        triangle.reset();
        triangle.moveTo(dRect.getCenterX(), dRect.getCenterY());
        p1 = new Point((int)dRect.getCenterX(), (int)dRect.getCenterY());
        triangle.lineTo(p2.x, p2.y);
        triangle.lineTo(p3.x, p3.y);
        triangle.closePath();

       innerTriangle.reset();
       innerTriangle.moveTo(p1.x+10, p1.y+17);
       innerTriangle.lineTo(p2.x+10, p2.y-10);
       innerTriangle.lineTo(p3.x-47, p3.y-10);
       innerTriangle.closePath();

        g2.draw(triangle);
        g2.draw(innerTriangle);

        g2.dispose();

    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setSize(800, 600);
        jFrame.add(new DragTest());
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

How can I maintain the same distance all around (say 10px), programmatically?

The distance between the outer triangle and the red (inner) triangle should be the same always, in all directions. Any idea?

SEE IMAGE

Currently I'm working on something:

// Calculate distance from point to line
public double pointToLineDistance(Point A, Point B, Point P) {
    double normalLength = Math.sqrt((B.x-A.x)*(B.x-A.x)+(B.y-A.y)*(B.y-A.y));
    return Math.abs((P.x-A.x)*(B.y-A.y)-(P.y-A.y)*(B.x-A.x))/normalLength;
}

// initially set :
// pi1.x = p1.x;
// pi1.y = p1.y;
// -------------------- Then ------------------------------

 while(pointToLineDistance(p1, p3, pi1) == 10 && pointToLineDistance(p1, p2, pi1) == 10){
        pi1.y++;
        pi1.x++;
        pi1.setLocation(pi1.x, pi1.y);
    }

... but doesn't work. HELP!!! :)

SEE IMAGE FOR THE CODE ABOVE

Thank You!

Body:
Keeping even spacing at line joins.

This problem needs a illistration to help explain. The solution is for one corner but the process will work for as many corners as you want.

Given two lines joined at one end find the two line offset by a fixed amount from both lines

Bold letters (example A) represent points. Lines as bold joined letters from start to end (example AB is line from A to B and BA is the line from B to A)

Given the lines AB and BC find the lines A1D and DC1 so that the area x distance from the original lines.

// all variables are assumed declared and floats or doubles (up to you)
 Ax = 10;   // x of Point A
 Ay = 200;  // y of A
 Bx = 200;  // x,y of B
 By = 200;
 Cx = 40;   // C
 Cy = 10;

 Dist = 40; // distance from the line

Looking at the image we can see some nice symmetry that can be exploited to find the solution. The lines EB, BF, FD and DE are all the same length. That means that if we solve the right triangle gBF we can move along the line BA from B to g and from g to h as gh is the same length as FB

From this point the line AB is turned around to BA

Finding a point x distance from a line

To find the point A1 we find the normalised vector along the line BA

Finding A1

// get the vector from B to A and normalise it
BAx = Ax - Bx;
BAy = Ay - By;
leng = Math.sqrt(BAx * BAx + BAy * BAy);
BAx /= leng; // The vector BA is 1 pixel (unit long)
BAy /= leng;

The normal moves along the line to go at 90 deg just swap x and y negating y

A1x = Ax - BAy * Dist;
A1y = Ay + BAx * Dist;

Now do the same for the point C1

BCx = Cx - Bx;
BCy = Cy - By;
leng = Math.sqrt(BCx * BCx + BCy * BCy);
BCx /= leng;
BCy /= leng;
C1x = Cx + BCy * Dist;  // move in the opposite direction than from A
C1y = Cy - BCx * Dist;

Finding D by solving the triangle FBg

If you only needed to find D (eg you are doing this on a closed line, triangle) you still have to get the normalised vectors BA and BC that were worked out above. BAx, BAy and BCx, BCy

To find the sin of the angle EBF use get the cross product of the two normalised vectors BA and BC. The sin of an angle relates the opposite side of a triangle Fg to the Hypotenuse BF as sin(ang) = opp/hypt

cross = BAx * BCy - BAy * BCx; // gets the sin of the angle
// you should check cross of zero. If so there is no solution
FBlen = Dist / cross; // gets the hypot the length of FB

Now we have FB we know the distance gh we could get gB as we have two sides of a right triangle and the length of gB = sqrt(FB*FB+Dist*Dist) but this will become an issue if the angle of ABC is greater than 90 deg. Not only do we need to know the length but the direction (positive or negative).

We can solve for Bg using the dot product which finds the cosine of the angle ABC which relates the hypotenuse to the adjacent side of a right triangle cos(ang) = BF/Bg

dot = BAx * BCx + BAy * BCy;
Bglen = FBlen * dot;

Now we can move along the line BA to g then to h then turn 90deg and out to D

// move from B to h using the normal vec of the line BA time the sum
// of the length FB
hx = Bx + BAx * (FBlen + BgLen);
hy = By + BAy * (FBlen + BgLen);
Dx = hx - BAy * Dist;  // then at 90 deg dist along to D
Dy = hy + BAx * Dist;

And you are all done you have the points A1, D, C1

Code in one go

You may also prefer to use a vector lib to do the adding, normalising,cross product etc...

Ax = 10;   // x of Point A
Ay = 200;  // y of A
Bx = 200;  // x,y of B
By = 200;
Cx = 40;   // C
Cy = 10;

Dist = 40;  // dist out

BAx = Ax - Bx;
BAy = Ay - By;
BCx = Cx - Bx;
BCy = Cy - By;
leng = Math.sqrt(BAx * BAx + BAy * BAy);
BAx /= leng;
BAy /= leng;
leng = Math.sqrt(BCx * BCx + BCy * BCy);
BCx /= leng;
BCy /= leng;

// get inside end points
A1x = Ax - BAy * Dist;
A1y = Ay + BAx * Dist;
C1x = Cx + BCy * Dist;
C1y = Cy - BCx * Dist;

FBlen = Dist / (BAx * BCy - BAy * BCx);
FBlen += FBlen * (BAx * BCx + BAy * BCy);
Dx = Bx + BAx * FBlen - BAy * Dist;;
Dy = By + BAy * FBlen + BAx * Dist;

Edge cases

You can do this for any number of lines as long as you go in the same direction and that your vectors are from the corners out. There are a few caveats.

If he distance between two corner points it too short the inside lines will overlap and cause problems. There is no simple solution to this apart from fixing the corner spacing and limiting the width.

Will fail if the lines are parallel. Check the result of the cross product, when zero or very close to zero line AB and BC are near parallel.

Miter extent. When the angle between the two lines starts to get near 360deg the point D will start getting further and further out. As the angle approaches 360deg or 2 Radians the distance from B to D will approch infinity. Again check cross product for zero or near zero. You can also set a miter limit by rounding the corner. or truncating it.

Mitering a corner. The above answer has given you the information you need to solve the above image. The distance DF is fixed to max miter limit, if the point B is further than F from D then find the point F. Look for symmetry and like triangles to find the other points.

If you are making long lines you will be best of doing thein on each side of the line. By defining the center not the edge you get a better result.


问:
href attribute not found when searching for elements by tagname in vba
Using VBA, I am attempting to find the href attribute for weekly share price data of a given stock in the HTML of Yahoo finance. I need this to automate the download of the csv file containing the data. I have done my research, and have written the following code which I believe should find the URL. However, the code continues to end with an error. Is there a small error in my code or is there a bigger problem at hand.

I have searched for the parent of the hyperlink by classname to narrow the search which is successful. But when I search within this parent the code returns the error "The remote server machine does not exist or is unavailable".

I am new HTML scraping so any help would be much appreciated. Thanks in advance for any help.

```<code>    Sub webpage()

Dim internet As Object
Dim internetdata As Object
Dim Find_Parent As Object
Dim Stock_Links As Object
Dim Link As Object
Dim URL As String

Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = True

URL = "https://finance.yahoo.com/quote/GTE.AX/history?period1=1341266400&period2=1499032800&interval=1wk&filter=history&frequency=1wk"
internet.Navigate URL

Do While internet.ReadyState <> READYSTATE_COMPLETE
Loop

Set internetdata = internet.Document
Set Find_Parent = internetdata.getElementsByClassName("Fl(end) Pos(r) T(-6px)")
Set Stock_Links = Find_Parent.getElementsByTagName("a")

NextRow = 1

For Each Link In Stock_Links
    Sheet1.Range("A" & NextRow) = Link.getAttribute("href")
    NextRow = NextRow + 1
Next

MsgBox "Link Found"
</code>```

End Sub

答:
The first issue is that you're using the InternetExplorer constant READYSTATE_COMPLETE, while using late binding.  Therefore, it sees it as an empty variable instead of its value, which is 4.  This means that the Do While/Loop will always evaluate to True.  So you'll need to replace the constant with its value...

```<code>Do While internet.ReadyState <> 4
Loop
</code>```

The other issue is with getElementsByClass.  It returns a collection of elements, where the indexing starts at 0.  So you'll need to refer to one of the elements from that collection.  In this example, it looks like only the one element that you're looking for is returned.  So you'll need to refer to the first element, which has an index of 0...

```<code>Set Stock_Links = Find_Parent(0).getElementsByTagName("a")
</code>```

Body:
Using VBA, I am attempting to find the href attribute for weekly share price data of a given stock in the HTML of Yahoo finance. I need this to automate the download of the csv file containing the data. I have done my research, and have written the following code which I believe should find the URL. However, the code continues to end with an error. Is there a small error in my code or is there a bigger problem at hand.

I have searched for the parent of the hyperlink by classname to narrow the search which is successful. But when I search within this parent the code returns the error "The remote server machine does not exist or is unavailable".

I am new HTML scraping so any help would be much appreciated. Thanks in advance for any help.

    Sub webpage()

Dim internet As Object
Dim internetdata As Object
Dim Find_Parent As Object
Dim Stock_Links As Object
Dim Link As Object
Dim URL As String

Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = True

URL = "https://finance.yahoo.com/quote/GTE.AX/history?period1=1341266400&period2=1499032800&interval=1wk&filter=history&frequency=1wk"
internet.Navigate URL

Do While internet.ReadyState <> READYSTATE_COMPLETE
Loop

Set internetdata = internet.Document
Set Find_Parent = internetdata.getElementsByClassName("Fl(end) Pos(r) T(-6px)")
Set Stock_Links = Find_Parent.getElementsByTagName("a")

NextRow = 1

For Each Link In Stock_Links
    Sheet1.Range("A" & NextRow) = Link.getAttribute("href")
    NextRow = NextRow + 1
Next

MsgBox "Link Found"

End Sub

Body:
The first issue is that you're using the InternetExplorer constant READYSTATE_COMPLETE, while using late binding.  Therefore, it sees it as an empty variable instead of its value, which is 4.  This means that the Do While/Loop will always evaluate to True.  So you'll need to replace the constant with its value...

Do While internet.ReadyState <> 4
Loop

The other issue is with getElementsByClass.  It returns a collection of elements, where the indexing starts at 0.  So you'll need to refer to one of the elements from that collection.  In this example, it looks like only the one element that you're looking for is returned.  So you'll need to refer to the first element, which has an index of 0...

Set Stock_Links = Find_Parent(0).getElementsByTagName("a")


问:
Error: Laravel Notifications Broadcast Exception
I am trying to build a real-time notification system in an app I am working on. one of the requirements is, when an ID is expired, that particular user should be sent a notification. Since this task needs to be run on daily basis at the maximum, I developed an artisan command that is easy to run with CRON jobs i.e. Laravel Scheduler. Every thing is working fine i.e. the artisan command is run and notification is generated & stored in database & all the related stuff. but each time a notification is generated, the page needs to be reload and this is where I am stuck. I am trying to make it happen in real time but a very strange error is being thrown & I don't know what it means.

Here is the necessary code:

Artisan.file

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\User;
use Carbon\Carbon;
use App\Notifications\UserIdExpired;

class UpdateCatalog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:expiry';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'dummy command to check its purpose';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ZERO = 0;
        $MONTH = 30;
        $today = Carbon::today();
        $users = User::all();
        foreach($users as $user){
            $today = Carbon::today();
            $expiryDate = $user->qidexpire_on;

            if($today->diffInDays($expiryDate, false) <= $MONTH && $today->diffInDays($expiryDate, false) >= $ZERO){
               $this->info($user);
                $this->info($expiryDate->diffInDays($today));
                $user->notify(new UserIdExpired);

            } else {

            }
            }

        }
    }
}
</code>```

Notification.file

```<code><?php

namespace App\Notifications;

use Carbon\Carbon;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;

class UserIdExpired extends Notification
{
    use Queueable;

    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'user' => $notifiable,
            'id_expired' => Carbon::now()
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage([
            'user' => $notifiable,
            'id_expired' => Carbon::now()
        ]);
    }

}
</code>```

when I run php artisan check:expiry from console, Notification is generated & on page reload it updates number of notifications but its not happening in real time. Following is the error that is shown on console

```<code>[Illuminate\Broadcasting\BroadcastException]
</code>```

Note: Whenever i reload the page, Pusher Console shows the respective log like connected private channel and host & all that stuff which means the problem is not on the client side, (yet)

答:
just found the answer on this issue

had to encrypt false since I am developing locally

Body:
I am trying to build a real-time notification system in an app I am working on. one of the requirements is, when an ID is expired, that particular user should be sent a notification. Since this task needs to be run on daily basis at the maximum, I developed an artisan command that is easy to run with CRON jobs i.e. Laravel Scheduler. Every thing is working fine i.e. the artisan command is run and notification is generated & stored in database & all the related stuff. but each time a notification is generated, the page needs to be reload and this is where I am stuck. I am trying to make it happen in real time but a very strange error is being thrown & I don't know what it means.

Here is the necessary code:

Artisan.file

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\User;
use Carbon\Carbon;
use App\Notifications\UserIdExpired;

class UpdateCatalog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:expiry';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'dummy command to check its purpose';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $ZERO = 0;
        $MONTH = 30;
        $today = Carbon::today();
        $users = User::all();
        foreach($users as $user){
            $today = Carbon::today();
            $expiryDate = $user->qidexpire_on;

            if($today->diffInDays($expiryDate, false) <= $MONTH && $today->diffInDays($expiryDate, false) >= $ZERO){
               $this->info($user);
                $this->info($expiryDate->diffInDays($today));
                $user->notify(new UserIdExpired);

            } else {

            }
            }

        }
    }
}

Notification.file

<?php

namespace App\Notifications;

use Carbon\Carbon;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;

class UserIdExpired extends Notification
{
    use Queueable;

    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'user' => $notifiable,
            'id_expired' => Carbon::now()
        ];
    }

    public function toBroadcast($notifiable)
    {
        return new BroadcastMessage([
            'user' => $notifiable,
            'id_expired' => Carbon::now()
        ]);
    }

}

when I run php artisan check:expiry from console, Notification is generated & on page reload it updates number of notifications but its not happening in real time. Following is the error that is shown on console

[Illuminate\Broadcasting\BroadcastException]

Note: Whenever i reload the page, Pusher Console shows the respective log like connected private channel and host & all that stuff which means the problem is not on the client side, (yet)


答:
One way of solving it, even though xrange in most cases is superior, is to use a while loop.

```<code>counter = 0
while (counter < 1000000000):
    print i
    counter = counter + 1
</code>```

Title: run for-loop for large numbers in python

Body:
 for i in range(1000000000):
 print(i)

This snippet gives memory error than How to run this loop. Any suggestions on how to run it.Thanks.

>>>MemoryError

UPDATE:
Actually I was trying something like this:

arr = []

for i in xrange(1000000000):
    arr.append(i*i)
print(max(set(arr)))

I don't know how to deal with such large numbers.

Body:
One way of solving it, even though xrange in most cases is superior, is to use a while loop.

counter = 0
while (counter < 1000000000):
    print i
    counter = counter + 1