问:
Dynamic Router Path validation in vue
{path: '/institute_details/:id', component: require('./views/institutedetails/instdetails.vue')},

I want to validate id before redirect on path

{path: '/institute_details/:id', component: require('./views/institutedetails/instdetails.vue')},

methods: {
      validateData() {
        var re = new RegExp("^[a-zA-Z][0-9]{6}$")
        var string1=this.seatno
        var vm=this
        if(this.seatno==' ' || this.seatno.length==0 ){
          this.seatno=''
          alert("Enter Your Seat Number...!")
          this.$refs.seatno1.focus();
        }else if(!re.test(string1)){
          this.seatno=''
          alert("Invalid...!")
          this.$router.push({path:'/' })
        }
      }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn_result">
  <span v-on:click="validateData">
    <router-link :to="'institute_details/' + seatno " class="btn btn-success">View Path
    </router-link>
  </span>
</div></code>```

答:
You can use beforeRouteEnter hook in your component.

And its usage is specified in the official vue-router document.see vue-router document

Code Example in your component

```<code>export default {
    data() {
        // define your component's data here.
    },

    methods: {
        validateDate() {
            // function to valiate your data
        },
    },

    beforeRouteEnter(to, from, next) {
        // check before enter the route
        // if check failed, you can cancel this routing

        // fake code here
        const isCheckPassed = checkWithSomeLogic();

        if (isCheckPassed) {
            next();
        } else {

            // cancel this routing
            // or redirect to the page you want with next function
            next({
                path: 'route you want to redirect to',
                query: {
                    // your query params here
                },
            });
        }
    },
};
</code>```

Hope it helps.

Title: Dynamic Router Path validation in vue

Body:
{path: '/institute_details/:id', component: require('./views/institutedetails/instdetails.vue')},

I want to validate id before redirect on path

{path: '/institute_details/:id', component: require('./views/institutedetails/instdetails.vue')},

methods: {
      validateData() {
        var re = new RegExp("^[a-zA-Z][0-9]{6}$")
        var string1=this.seatno
        var vm=this
        if(this.seatno==' ' || this.seatno.length==0 ){
          this.seatno=''
          alert("Enter Your Seat Number...!")
          this.$refs.seatno1.focus();
        }else if(!re.test(string1)){
          this.seatno=''
          alert("Invalid...!")
          this.$router.push({path:'/' })
        }
      }
    }

    <router-link :to="'institute_details/' + seatno " class="btn btn-success">View Path
    </router-link>

Body:
You can use beforeRouteEnter hook in your component.

And its usage is specified in the official vue-router document.see vue-router document

Code Example in your component

export default {
    data() {
        // define your component's data here.
    },

    methods: {
        validateDate() {
            // function to valiate your data
        },
    },

    beforeRouteEnter(to, from, next) {
        // check before enter the route
        // if check failed, you can cancel this routing

        // fake code here
        const isCheckPassed = checkWithSomeLogic();

        if (isCheckPassed) {
            next();
        } else {

            // cancel this routing
            // or redirect to the page you want with next function
            next({
                path: 'route you want to redirect to',
                query: {
                    // your query params here
                },
            });
        }
    },
};

Hope it helps.


来源: stackexchange

问:
Use JS to modify properties declared in CSS files.
Say I have a css declaration

```<code>.example {
  height: 60px;
}
</code>```

Is there a way to use Javascript to modify that 60px?

Say for example,

```<code>function updateHeight() {
  // add 10px to the css class `example`;
}
</code>```

So the css class will effectively become

```<code>.example {
  height: 70px;
}
</code>```

答:
You can use code like this:

document.querySelector('.test').style.height = '150px';```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
  width : 100px;
  height : 100px;
  background : #0AF;
}</code>```

```
</div>
</div>
</p>

<p>Of course, you have always the opportunity to make the code as abstract as you desire.</p>

<p>In example you can have a function that can work like that:</p>

```// Responsible to set the CSS Height property of the given element
function changeHeight( selector, height ) {
    // Choose the element should get modified
    var $element = document.querySelector( selector );
    // Change the height proprety
    $element.style.height = height;
}

changeHeight( '.test', '150px' );
```

<p>or you can go even more abstract like that:</p>

```// Responsible to modify the given CSS property of the given
// HTML element
function changeCssProperty( selector, property, value ) {
    // Find the given element in the DOM
    var $element = document.querySelector( selector );
    // Set the value to the given property
    $element.style[property] = value;
}

changeCssProperty( '.test', 'width', '200px' );
```

ContentLicense: CC BY-SA 3.0

Body:
Say I have a css declaration

.example {
  height: 60px;
}

Is there a way to use Javascript to modify that 60px?

Say for example,

function updateHeight() {
  // add 10px to the css class `example`;
}

So the css class will effectively become

.example {
  height: 70px;
}

Body:
You can use code like this:

document.querySelector('.test').style.height = '150px';

.test {
  width : 100px;
  height : 100px;
  background : #0AF;
}

<div class="test"></div>

Of course, you have always the opportunity to make the code as abstract as you desire.

In example you can have a function that can work like that:

// Responsible to set the CSS Height property of the given element
function changeHeight( selector, height ) {
    // Choose the element should get modified
    var $element = document.querySelector( selector );
    // Change the height proprety
    $element.style.height = height;
}

changeHeight( '.test', '150px' );

or you can go even more abstract like that:

// Responsible to modify the given CSS property of the given
// HTML element
function changeCssProperty( selector, property, value ) {
    // Find the given element in the DOM
    var $element = document.querySelector( selector );
    // Set the value to the given property
    $element.style[property] = value;
}

changeCssProperty( '.test', 'width', '200px' );


问:
VBA code to clearcontents in excel
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold
</code>```

Desired results:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6
</code>```

答:
If you don't want to loop over the cells, you may try something like below...</p>

```<code>Sub ClearDuplicateItems()
    Dim lr As Long
    Application.ScreenUpdating = True
    lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Columns("G:H").Insert
    Range("G2:G" & lr).Formula = "=INDEX(B$2:B2,MATCH(""zzz"",B$2:B2))"
    Range("H2:H" & lr).Formula = "=IF(COUNTIFS(G$2:G2,INDEX(B$2:B2,MATCH(""zzz"",B$2:B2)),E$2:E2,E2)>1,NA(),"""")"
    On Error Resume Next
    Range("H2:H" & lr).SpecialCells(xlCellTypeFormulas, 16).Offset(0, -2).ClearContents
    Range("H2:H" & lr).SpecialCells(xlCellTypeFormulas, 16).Offset(0, -3).ClearContents
    Columns("G:H").Delete
    Application.ScreenUpdating = True
End Sub
</code>```

Title: VBA code to clearcontents in excel

Body:
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold

Desired results:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6

Body:
If you don't want to loop over the cells, you may try something like below...

Sub ClearDuplicateItems()
    Dim lr As Long
    Application.ScreenUpdating = True
    lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Columns("G:H").Insert
    Range("G2:G" & lr).Formula = "=INDEX(B$2:B2,MATCH(""zzz"",B$2:B2))"
    Range("H2:H" & lr).Formula = "=IF(COUNTIFS(G$2:G2,INDEX(B$2:B2,MATCH(""zzz"",B$2:B2)),E$2:E2,E2)>1,NA(),"""")"
    On Error Resume Next
    Range("H2:H" & lr).SpecialCells(xlCellTypeFormulas, 16).Offset(0, -2).ClearContents
    Range("H2:H" & lr).SpecialCells(xlCellTypeFormulas, 16).Offset(0, -3).ClearContents
    Columns("G:H").Delete
    Application.ScreenUpdating = True
End Sub


问:
in ReactiveUI binding, How to disable 2 buttons by 2 ReactiveCommand
I'm using ReactiveCommand and bind it to a button and let the button be disabled automatically when the command is executing, it works great.

Now I have 2 ReactiveCommand and 2 buttons, I want the 2 buttons to be disabled when any of the command is executing. What I tried is:

```<code>    public class MyClass
    {
        public MyClass()
        {
            ReadClFilesCommand = ReactiveCommand.Create(ReadClFiles, c.IsExecuting.Select(exe => !exe));

            WriteClFilesCommand = ReactiveCommand.Create(WriteClFiles, ReadClFilesCommand.IsExecuting.Select(exe => !exe));
        }
    }
</code>```

It looks very elegent and I like its cleanness. But when I try to run the code, I got an NullReferenceException for WriteClFilesCommand because it's not created yet.

I guess I need to create the command first and then set its CanExecute later, but CanExecute is readonly.

Maybe I can create a separate IObserable and let in ReadClFilesCommand.CanExecute and WriteClFilesCommand.CanExecute, is it possible?

Any other ways to do it?

Thanks.

答:
I'm still using RxUI 6 so my syntax is a little different but I think either of these ways will work. The WhenAny* helpers are your best friend whenever something isn't available yet or if you don't know when it will be available. As long as you have it setup so setting those commands will throw an INotifyPropertyChanged event.

```<code>        IObservable<bool> canExecute =
            Observable.CombineLatest(
                this.WhenAnyObservable(x=> x.WriteClFilesCommand.IsExecuting),
                this.WhenAnyObservable(x => x.ReadClFilesCommand.IsExecuting))
                .Select(x => !x.Any(exec => exec));

        ReadClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);
</code>```

Or you can use a subject to "play" all your events through

```<code>        BehaviorSubject<bool> canExecute = new BehaviorSubject<bool>(true);

        ReadClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);

        Observable.CombineLatest(
                WriteClFilesCommand.IsExecuting,
                ReadClFilesCommand.IsExecuting)
                .Select(x => !x.Any(exec => exec))
                .Subscribe(canExecute);
</code>```

Body:
I'm using ReactiveCommand and bind it to a button and let the button be disabled automatically when the command is executing, it works great.

Now I have 2 ReactiveCommand and 2 buttons, I want the 2 buttons to be disabled when any of the command is executing. What I tried is:

    public class MyClass
    {
        public MyClass()
        {
            ReadClFilesCommand = ReactiveCommand.Create(ReadClFiles, c.IsExecuting.Select(exe => !exe));

            WriteClFilesCommand = ReactiveCommand.Create(WriteClFiles, ReadClFilesCommand.IsExecuting.Select(exe => !exe));
        }
    }

It looks very elegent and I like its cleanness. But when I try to run the code, I got an NullReferenceException for WriteClFilesCommand because it's not created yet.

I guess I need to create the command first and then set its CanExecute later, but CanExecute is readonly.

Maybe I can create a separate IObserable and let in ReadClFilesCommand.CanExecute and WriteClFilesCommand.CanExecute, is it possible?

Any other ways to do it?

Thanks.

Body:
I'm still using RxUI 6 so my syntax is a little different but I think either of these ways will work. The WhenAny* helpers are your best friend whenever something isn't available yet or if you don't know when it will be available. As long as you have it setup so setting those commands will throw an INotifyPropertyChanged event.

        IObservable<bool> canExecute =
            Observable.CombineLatest(
                this.WhenAnyObservable(x=> x.WriteClFilesCommand.IsExecuting),
                this.WhenAnyObservable(x => x.ReadClFilesCommand.IsExecuting))
                .Select(x => !x.Any(exec => exec));

        ReadClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);

Or you can use a subject to "play" all your events through

        BehaviorSubject<bool> canExecute = new BehaviorSubject<bool>(true);

        ReadClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                ReadClFiles);

        WriteClFilesCommand =
            ReactiveCommand.CreateAsyncObservable(
                canExecute,
                WriteClFiles);

        Observable.CombineLatest(
                WriteClFilesCommand.IsExecuting,
                ReadClFilesCommand.IsExecuting)
                .Select(x => !x.Any(exec => exec))
                .Subscribe(canExecute);


问:
App crashes when when back button is pressed (Android Studio)
I am programming an android app in Android Studio using a thread in a fragment to graph 100 random values, but when the back button is pressed before all the values are graphed the app crashes.

Can somebody tell me how can I stop the thread when the back button is pressed.

```<code>public class fragment_Usuario_Mediciones extends Fragment{
//variables para grafica
private static final Random RANDOM= new Random();
private LineGraphSeries<DataPoint> series;
private int x = 0;

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

    //instancia del GraphView
    GraphView graph = (GraphView) rootView.findViewById(R.id.graphView);

    //datos
    series = new LineGraphSeries<DataPoint>();
    graph.addSeries(series);

    Viewport viewport = graph.getViewport();
    viewport.setXAxisBoundsManual(true);
    viewport.setMinX(0);
    viewport.setMaxX(100);
    viewport.setScrollable(true);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    //Simulacion en tiempo real con hilo
    new Thread(new Runnable() {
        @Override
        public void run() {
            //añade 100 nuevas entradas

            for (int i=0;i<100;i++){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AniadirEntrada();
                    }
                });
                //consumir pulsos de reloj
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    //manejar el error
                    e.printStackTrace();
                }

            }
        }
    }).start();
}

private void AniadirEntrada()
{
    series.appendData(new DataPoint(x++,RANDOM.nextDouble()*10d),true,100);
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
    //    getActivity().finish();
        return true;
    }
    return false;

}
</code>```

}

答:
Define a new handler and runnable:

```<code>private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Do what ever you want
    }
};
</code>```

To start execution use - handler.post(runnable);

Remove your callback from your handler in onpause or onstop overridden method:

```<code>handler.removeCallbacks(runnable);
</code>```

Or

```<code>handler.removeCallbacksAndMessages(null);
</code>```

In the docs for removeCallbacksAndMessages it says...

Remove any pending posts of callbacks and sent messages whose obj is
  token. If token is null, all callbacks and messages will be removed.

Body:
I am programming an android app in Android Studio using a thread in a fragment to graph 100 random values, but when the back button is pressed before all the values are graphed the app crashes.

Can somebody tell me how can I stop the thread when the back button is pressed.

public class fragment_Usuario_Mediciones extends Fragment{
//variables para grafica
private static final Random RANDOM= new Random();
private LineGraphSeries<DataPoint> series;
private int x = 0;

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

    //instancia del GraphView
    GraphView graph = (GraphView) rootView.findViewById(R.id.graphView);

    //datos
    series = new LineGraphSeries<DataPoint>();
    graph.addSeries(series);

    Viewport viewport = graph.getViewport();
    viewport.setXAxisBoundsManual(true);
    viewport.setMinX(0);
    viewport.setMaxX(100);
    viewport.setScrollable(true);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    //Simulacion en tiempo real con hilo
    new Thread(new Runnable() {
        @Override
        public void run() {
            //añade 100 nuevas entradas

            for (int i=0;i<100;i++){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AniadirEntrada();
                    }
                });
                //consumir pulsos de reloj
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    //manejar el error
                    e.printStackTrace();
                }

            }
        }
    }).start();
}

private void AniadirEntrada()
{
    series.appendData(new DataPoint(x++,RANDOM.nextDouble()*10d),true,100);
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
    //    getActivity().finish();
        return true;
    }
    return false;

}

}

Body:
Define a new handler and runnable:

private Handler handler = new Handler(Looper.getMainLooper());
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // Do what ever you want
    }
};

To start execution use - handler.post(runnable);

Remove your callback from your handler in onpause or onstop overridden method:

handler.removeCallbacks(runnable);

Or

handler.removeCallbacksAndMessages(null);

In the docs for removeCallbacksAndMessages it says...

Remove any pending posts of callbacks and sent messages whose obj is
  token. If token is null, all callbacks and messages will be removed.


问:
ActionController::RoutingError (uninitialized constant Users):
I have added a t.boolean :admin field to my Devise migration file. It was saying that it was an unpermitted parameter in the console so I attempted to create a protected permitter for the :admin value when the form is submitted.

Here is my Users::RegistrationsController < Devise::RegistrationsController:

```<code>    class Users::RegistrationsController < Devise::RegistrationsController
      before_action :configure_permitted_parameters

      protected

      #Permitting the admin boolean
      def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up).push(:admin)
      end
    end
</code>```

And my routes.rb file with the devise_for method.

```<code>    devise_for :users, :controllers => { :registrations => "users/registrations" }
</code>```

I cannot seem to fix ActionController::RoutingError (uninitialized constant Users): despite me looking on stack overflow for 30 minutes and trying to rename a couple of things. Any ideas?

答: Your controller has probably the wrong name or it is placed in the wrong folder. When following Ruby on Rails conventions then a controller named Users::RegistrationsController should be defined in a file named app/controllers/users/registrations_controller.rb.

Body:
I have added a t.boolean :admin field to my Devise migration file. It was saying that it was an unpermitted parameter in the console so I attempted to create a protected permitter for the :admin value when the form is submitted.

Here is my Users::RegistrationsController < Devise::RegistrationsController:

    class Users::RegistrationsController < Devise::RegistrationsController
      before_action :configure_permitted_parameters

      protected

      #Permitting the admin boolean
      def configure_permitted_parameters
        devise_parameter_sanitizer.permit(:sign_up).push(:admin)
      end
    end

And my routes.rb file with the devise_for method.

    devise_for :users, :controllers => { :registrations => "users/registrations" }

I cannot seem to fix ActionController::RoutingError (uninitialized constant Users): despite me looking on stack overflow for 30 minutes and trying to rename a couple of things. Any ideas?

ContentLicense: CC BY-SA 4.0


问:
JPA cascade persist - many to one unidirectional
I have a many to one relationship unidirectional and I am trying to persist a child entity i.e. SubscriptionEntity also expect that it should also persist Parent as I am using cascade = CascadeType.PERSIST

Background about relationships : SubscriptionEntity let you know which user is associated with which business and there are few more entity to like state and product which tells us state of subscription and what are the product associated with subscription. Subscription state is one to many bi-directional because subscription can move to many status throughout the membership on-hold, active, deactivate etc.. And similarly Subscription relation with product is one to many bi-directional as user can subscribe for one product or more than one.

We can't do bi-directional association between User and Subscription because user can have association with many businesses.

```<code>    public class SubscriptionEntity implements Domain, Serializable
    {
        @Column(name = "subscription2user")
        @ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
        @JoinColumn(name = "subscription2user")
        private UserEntity user;

        @Column(name = "subscription2biz")
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        @JoinColumn(name = "subscription2biz")
        private BusinessEntity business;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<ProductSubscriptionEntity> subscribedProducts;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<SubscriptionStateEntity> state;
    }

public class UserEntity implements Domain, Serializable
{
    private static final long serialVersionUID = 755369097357065341L;

    @Id
    @Column(name = "user_id")
    private String id;

    @Column(name = "user_first_name")
    private String firstName;

    @Column(name = "user_last_name")
    private String lastName;

    @Column(name = "user_mobile")
    private BigInteger mobile;

    @Column(name = "user_password")
    private String password;

    @Column(name = "user_create_date")
    private Date createDate;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user2address")
    @Column(name = "user2address")
    private UserAddressEntity address;
}

public class SubscriptionStateEntity implements Domain, Serializable
{
    @Column(name = "subscription_state2subscription")
    @ManyToOne(optional = false)
    @JoinColumn(name="subscription_state2subscription")
    protected SubscriptionEntity subscription;
}

public class ProductSubscriptionEntity implements Domain, Serializable
{
    @Column(name = "user_product_subscription2subscription")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "user_product_subscription2subscription")
    private SubscriptionEntity subscription;
}
</code>```

Scenario : Business is already present but User is new, and association between user and subscription is also new. When I am trying to add new subscription getting below error. If User already present in DB then it work smoothly.

```<code>void addSubscription(final UserEntity user, final String businessID)
{
    final UserEntity userTemp = this.userDao.readUserByIdOrMobile(user.getId(), user.getMobile());
    if (null == userTemp)
    {
        user.setId(java.util.UUID.randomUUID().toString());
        user.setCreateDate(DateUtil.getDateTimestamp());
    }
    final BusinessEntity business = getBusinessByID(businessID);
    SubscriptionEntity subscription = new SubscriptionEntity();
    subscription.setUser(user);
    subscription.setBusiness(business);

    super.getEm().persist(subscription);
}
</code>```

Caused by:
  org.apache.openjpa.persistence.EntityExistsException: Cannot add or
  update a child row: a foreign key constraint fails ... ... REFERENCES
  user (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION

Any help much appreciated. Thanks in advance.

答:
It looks like you have not given table and column mapping annotations on UserEntity entity.

Since you are not settimg the id for UserEntity, are you having the id generation strategy defined ? When you do not have the id set, there is no linking between subscription and user.

You can add the id generation strategy as auto increment using the annotation given below in the UserEntity on id field. This will generate id on creation.

GeneratedValue(strategy=GenerationType.IDENTITY)
   private String id;

Body:
I have a many to one relationship unidirectional and I am trying to persist a child entity i.e. SubscriptionEntity also expect that it should also persist Parent as I am using cascade = CascadeType.PERSIST

Background about relationships : SubscriptionEntity let you know which user is associated with which business and there are few more entity to like state and product which tells us state of subscription and what are the product associated with subscription. Subscription state is one to many bi-directional because subscription can move to many status throughout the membership on-hold, active, deactivate etc.. And similarly Subscription relation with product is one to many bi-directional as user can subscribe for one product or more than one.

We can't do bi-directional association between User and Subscription because user can have association with many businesses.

    public class SubscriptionEntity implements Domain, Serializable
    {
        @Column(name = "subscription2user")
        @ManyToOne(optional = false, fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
        @JoinColumn(name = "subscription2user")
        private UserEntity user;

        @Column(name = "subscription2biz")
        @ManyToOne(optional = false, fetch = FetchType.LAZY)
        @JoinColumn(name = "subscription2biz")
        private BusinessEntity business;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<ProductSubscriptionEntity> subscribedProducts;

        @OneToMany(fetch = FetchType.EAGER, mappedBy = "subscription", cascade = CascadeType.PERSIST)
        private List<SubscriptionStateEntity> state;
    }

public class UserEntity implements Domain, Serializable
{
    private static final long serialVersionUID = 755369097357065341L;

    @Id
    @Column(name = "user_id")
    private String id;

    @Column(name = "user_first_name")
    private String firstName;

    @Column(name = "user_last_name")
    private String lastName;

    @Column(name = "user_mobile")
    private BigInteger mobile;

    @Column(name = "user_password")
    private String password;

    @Column(name = "user_create_date")
    private Date createDate;

    @OneToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "user2address")
    @Column(name = "user2address")
    private UserAddressEntity address;
}

public class SubscriptionStateEntity implements Domain, Serializable
{
    @Column(name = "subscription_state2subscription")
    @ManyToOne(optional = false)
    @JoinColumn(name="subscription_state2subscription")
    protected SubscriptionEntity subscription;
}

public class ProductSubscriptionEntity implements Domain, Serializable
{
    @Column(name = "user_product_subscription2subscription")
    @ManyToOne(optional = false, fetch = FetchType.EAGER)
    @JoinColumn(name = "user_product_subscription2subscription")
    private SubscriptionEntity subscription;
}

Scenario : Business is already present but User is new, and association between user and subscription is also new. When I am trying to add new subscription getting below error. If User already present in DB then it work smoothly.

void addSubscription(final UserEntity user, final String businessID)
{
    final UserEntity userTemp = this.userDao.readUserByIdOrMobile(user.getId(), user.getMobile());
    if (null == userTemp)
    {
        user.setId(java.util.UUID.randomUUID().toString());
        user.setCreateDate(DateUtil.getDateTimestamp());
    }
    final BusinessEntity business = getBusinessByID(businessID);
    SubscriptionEntity subscription = new SubscriptionEntity();
    subscription.setUser(user);
    subscription.setBusiness(business);

    super.getEm().persist(subscription);
}

Caused by:
  org.apache.openjpa.persistence.EntityExistsException: Cannot add or
  update a child row: a foreign key constraint fails ... ... REFERENCES
  user (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION

Any help much appreciated. Thanks in advance.


问:
Moving objects with mouse click
I want to move the object(6-point star with 2 triangles) with mouse clicking.
I wrote the following code, but there is no response.

```<code>case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        float x_min = (-x + 500) / 500;
        float x_max = (x - 500) / 500;
        float y_min = (-y + 500) / 500;
        float y_max = (y - 500) / 500;
        gluOrtho2D(x_min, x_max, y_min, y_max);
    }
 glutPostRedisplay();
 break;
</code>```

In the case GLUT_LEFT_BUTTON, I put minimum/maxmimum x and y position but nothing works when I clicked left mouse button.

Here is the full codes:

```<code>#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };

static GLfloat spin = 0.0;

float x = 400.0f, y = 442.5f;
float x_position;
float y_position;

float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;
int rotate = 1;

void init(void);
void triangle_1(void);
void triangle_2(void);
void display(void);
void spinDisplay_1(void);
void spinDisplay_2(void);
void reshape(int, int);
void changeColor(int);
void mouse(int, int, int, int);

////////////////////////////////////////////////////////////////////

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}

////////////////////////////////////////////////////////////////////

void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void triangle_1(void) {          //// triangle_1 and triangle_2 make 6-point star ////
    glColor3fv(color1);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {
    glColor3fv(color2);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();

    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void spinDisplay_1(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void spinDisplay_2(void) {
    spin = spin - 2.0;

    if (spin < 360.0) {
        spin = spin + 360.0;
    }

    glutPostRedisplay();
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void changeColor(int n) {
    if (n == 1) {
        color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
        color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
    }
    else if (n == 2) {
        color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
        color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
    }
}

void mouse(int button, int state, int x, int y) {         /////// mouse event ////////
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN) {
            float x_min = (-x + 500) / 500;
            float x_max = (x - 500) / 500;
            float y_min = (-y + 500) / 500;
            float y_max = (y - 500) / 500;
            gluOrtho2D(x_min, x_max, y_min, y_max);
        }
        glutPostRedisplay();
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN) {
            if (mode == 1) {
                changeColor(mode);
                mode = 2;
            }
            else if (mode == 2) {
                changeColor(mode);
                mode = 1;
            }
        }
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            if (rotate == 1) {
                glutIdleFunc(spinDisplay_1);
                rotate = 2;
            }
            else if (rotate == 2) {
                glutIdleFunc(spinDisplay_2);
                rotate = 1;
            }
        break;
    default:
        break;
    }
}
</code>```

答:
I want to move the object (6-point star with 2 triangles) with mouse clicking

If you want to left click and that position now being the center of the star, then you're overcomplicating things. You already have the star's position as global variables x and y. Thus in mouse() you just set those to the mouse position.

However remember to subtract the height of the window by y, since 0x0 is top left on the screen but bottom left in OpenGL.

```<code>if (state == GLUT_DOWN) {
    ::x = x;
    ::y = glutGet(GLUT_WINDOW_HEIGHT) - y;
}
</code>```

Since mouse()'s x and y parameters shadows your global variables x and y, you have to prefix with ::. You could also rename mouse()'s parameters to say mx and my:

```<code>void mouse(int button, int state, int mx, int my) {
    [...]
    if (state == GLUT_DOWN) {
        x = mx;
        y = glutGet(GLUT_WINDOW_HEIGHT) - my;
    }
</code>```

Here's a GIF of clicking random places on the window:

Title: Moving objects with mouse click

Body:
I want to move the object(6-point star with 2 triangles) with mouse clicking.
I wrote the following code, but there is no response.

case GLUT_LEFT_BUTTON:
    if (state == GLUT_DOWN) {
        float x_min = (-x + 500) / 500;
        float x_max = (x - 500) / 500;
        float y_min = (-y + 500) / 500;
        float y_max = (y - 500) / 500;
        gluOrtho2D(x_min, x_max, y_min, y_max);
    }
 glutPostRedisplay();
 break;

In the case GLUT_LEFT_BUTTON, I put minimum/maxmimum x and y position but nothing works when I clicked left mouse button.

Here is the full codes:

#include <stdlib.h>
#include <GL/glut.h>

float v1[3] = { -35.0f,  22.5f, 0.0f };
float v2[3] = { -35.0f, -22.5f, 0.0f };
float v3[3] = { 0.0f,  42.5f, 0.0f };
float v4[3] = { 0.0f, -42.5f, 0.0f };
float v5[3] = { 35.0f,  22.5f, 0.0f };
float v6[3] = { 35.0f, -22.5f, 0.0f };

static GLfloat spin = 0.0;

float x = 400.0f, y = 442.5f;
float x_position;
float y_position;

float color1[3] = { 1.0f, 1.0f, 1.0f };
float color2[3] = { 1.0f, 1.0f, 1.0f };

int mode = 1;
int rotate = 1;

void init(void);
void triangle_1(void);
void triangle_2(void);
void display(void);
void spinDisplay_1(void);
void spinDisplay_2(void);
void reshape(int, int);
void changeColor(int);
void mouse(int, int, int, int);

////////////////////////////////////////////////////////////////////

int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(300, 300);
    glutCreateWindow("6-Point Star");

    init();

    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMainLoop();

    return 0;
}

////////////////////////////////////////////////////////////////////

void init(void) {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
}

void triangle_1(void) {          //// triangle_1 and triangle_2 make 6-point star ////
    glColor3fv(color1);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v1);
    glVertex3fv(v4);
    glVertex3fv(v5);

    glEnd();
}

void triangle_2(void) {
    glColor3fv(color2);

    glBegin(GL_TRIANGLE_FAN);
    glVertex3fv(v2);
    glVertex3fv(v3);
    glVertex3fv(v6);

    glEnd();
}

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();

    glTranslatef(x, y, 0.0f);
    glRotatef(spin, 0.0, 0.0, 1.0);

    triangle_1();
    triangle_2();

    glPopMatrix();

    glutSwapBuffers();
}

void spinDisplay_1(void) {
    spin = spin + 2.0;

    if (spin > 360.0) {
        spin = spin - 360.0;
    }

    glutPostRedisplay();
}

void spinDisplay_2(void) {
    spin = spin - 2.0;

    if (spin < 360.0) {
        spin = spin + 360.0;
    }

    glutPostRedisplay();
}

void reshape(int w, int h) {
    glViewport(0, 0, (GLsizei)w, (GLsizei)h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 500.0, 0.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void changeColor(int n) {
    if (n == 1) {
        color1[0] = 0.0f, color1[1] = 0.0f, color1[2] = 1.0f;
        color2[0] = 0.0f, color2[1] = 1.0f, color2[2] = 0.0f;
    }
    else if (n == 2) {
        color1[0] = 1.0f, color1[1] = 1.0f, color1[2] = 1.0f;
        color2[0] = 1.0f, color2[1] = 1.0f, color2[2] = 1.0f;
    }
}

void mouse(int button, int state, int x, int y) {         /////// mouse event ////////
    switch (button) {
    case GLUT_LEFT_BUTTON:
        if (state == GLUT_DOWN) {
            float x_min = (-x + 500) / 500;
            float x_max = (x - 500) / 500;
            float y_min = (-y + 500) / 500;
            float y_max = (y - 500) / 500;
            gluOrtho2D(x_min, x_max, y_min, y_max);
        }
        glutPostRedisplay();
        break;
    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_DOWN) {
            if (mode == 1) {
                changeColor(mode);
                mode = 2;
            }
            else if (mode == 2) {
                changeColor(mode);
                mode = 1;
            }
        }
        break;
    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_DOWN)
            if (rotate == 1) {
                glutIdleFunc(spinDisplay_1);
                rotate = 2;
            }
            else if (rotate == 2) {
                glutIdleFunc(spinDisplay_2);
                rotate = 1;
            }
        break;
    default:
        break;
    }
}

Body:
I want to move the object (6-point star with 2 triangles) with mouse clicking

If you want to left click and that position now being the center of the star, then you're overcomplicating things. You already have the star's position as global variables x and y. Thus in mouse() you just set those to the mouse position.

However remember to subtract the height of the window by y, since 0x0 is top left on the screen but bottom left in OpenGL.

if (state == GLUT_DOWN) {
    ::x = x;
    ::y = glutGet(GLUT_WINDOW_HEIGHT) - y;
}

Since mouse()'s x and y parameters shadows your global variables x and y, you have to prefix with ::. You could also rename mouse()'s parameters to say mx and my:

void mouse(int button, int state, int mx, int my) {
    [...]
    if (state == GLUT_DOWN) {
        x = mx;
        y = glutGet(GLUT_WINDOW_HEIGHT) - my;
    }

Here's a GIF of clicking random places on the window:


问:
Making a grid with jquery - code not complete
I'm trying to figure out how to make my code work and look like this:

The question is:

Create an HTML page with a text input, a button, and container for a Raphaël paper object. We will have the user enter a number in the form and click the button, and then draw an n×n grid of squares.
  If the user enters 8 in the text input and clicks the button, you should draw eight rows and columns of little squares. To do this, you will need two for loops nested inside each other like this:*

```<code>for ( row=1; ... ) {
  for ( col=1; ... ) {
    ...
  }
}
</code>```

In the (inner-most) loop body, draw a little square on the paper with an x and y value calculated from the loop counters so the squares end up in a grid pattern.

This is my code:

x = 0
y = 0
grid = function() {
 entered_text = $('#howmany').val();
 for (row = entered_text; row <= 15; row += 1){
    for (col = entered_text; col <= 15; col += 1) {
   r = paper.rect(x, y, 20, 20);
   x = r * col
  }
  y = r + row;
 }
}

setup = function() {
  paper = Raphael('svg', 400, 400)
  jQuery('#start').click(grid)

}

jQuery(document).ready(setup)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.1.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<title>Exercise 11</title>
</head>
<body>
<h1>Exercise 11</h1>

<div class="gridsize">Grid Size:
<input type="text" id="howmany" />
<button id="start">Go</button></div>

<div id="svg"></div>

</body>
</html></code>```

答:
You're close, you were just multiplying the r value, a non number, by col, which will return NaN, which isn't good.  Then I also converted entered_text to a number and modified the for loop.  So I went ahead and updated it.  If you want padding, simply increase all 20 to 25.

x = 0
y = 0
grid = function() {
 entered_text = Number($('#howmany').val());
 for (row = 0; row < entered_text; row += 1){
    for (col = 0; col < entered_text; col += 1) {
   paper.rect(20 * col, 20 * row, 20, 20);
  }
 }
}

setup = function() {
  paper = Raphael('svg', 400, 400)
  jQuery('#start').click(grid)

}

jQuery(document).ready(setup)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.1.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<title>Exercise 11</title>
</head>
<body>
<h1>Exercise 11</h1>

<div class="gridsize">Grid Size:
<input type="text" id="howmany" />
<button id="start">Go</button></div>

<div id="svg"></div>

</body>
</html></code>```

Body:
I'm trying to figure out how to make my code work and look like this:

The question is:

Create an HTML page with a text input, a button, and container for a Raphaël paper object. We will have the user enter a number in the form and click the button, and then draw an n×n grid of squares.
  If the user enters 8 in the text input and clicks the button, you should draw eight rows and columns of little squares. To do this, you will need two for loops nested inside each other like this:*

for ( row=1; ... ) {
  for ( col=1; ... ) {
    ...
  }
}

In the (inner-most) loop body, draw a little square on the paper with an x and y value calculated from the loop counters so the squares end up in a grid pattern.

This is my code:

x = 0
y = 0
grid = function() {
 entered_text = $('#howmany').val();
 for (row = entered_text; row <= 15; row += 1){
    for (col = entered_text; col <= 15; col += 1) {
   r = paper.rect(x, y, 20, 20);
   x = r * col
  }
  y = r + row;
 }
}

setup = function() {
  paper = Raphael('svg', 400, 400)
  jQuery('#start').click(grid)

}

jQuery(document).ready(setup)

<!DOCTYPE html>

<meta charset="UTF-8" />

<title>Exercise 11</title>

Exercise 11

Grid Size:
<input type="text" id="howmany" />
<button id="start">Go</button>

Body:
You're close, you were just multiplying the r value, a non number, by col, which will return NaN, which isn't good.  Then I also converted entered_text to a number and modified the for loop.  So I went ahead and updated it.  If you want padding, simply increase all 20 to 25.

x = 0
y = 0
grid = function() {
 entered_text = Number($('#howmany').val());
 for (row = 0; row < entered_text; row += 1){
    for (col = 0; col < entered_text; col += 1) {
   paper.rect(20 * col, 20 * row, 20, 20);
  }
 }
}

setup = function() {
  paper = Raphael('svg', 400, 400)
  jQuery('#start').click(grid)

}

jQuery(document).ready(setup)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script src="http://cmpt165.csil.sfu.ca/js/jquery-3.1.1.js"></script>
<script src="http://cmpt165.csil.sfu.ca/js/raphael-2.1.4.js"></script>
<script src="logic.js"></script>
<title>Exercise 11</title>
</head>
<body>
<h1>Exercise 11</h1>

<div class="gridsize">Grid Size:
<input type="text" id="howmany" />
<button id="start">Go</button></div>

<div id="svg"></div>

</body>
</html>


问:
List and Library are not display in SharePoint designer 2010
When i try to open SharePoint designer (2010) the list and library are not shown, Its throws error like ‘testSplist’ is Broken.

How to resolve this error.

答:
Follow the below steps to resolve this issue.

Open the SharePoint PowerShell command prompt.

Write the following code on SharePoint powershell.

$web = Get-SPWeb http://[yoursite]

$list = $web.Lists["Your Broken List"]

$list.Delete()

Once you done restart the SharePoint designer.

Now open the SharePoint designer it will show the all list and library.


问:
How to do filtered aggregations by a filter field in olap cube?
Currently I have one field in a SQL DB table called Amount. This field will be used in a Reporting Services report that uses SSAS OLAP Cube behind to display the winners and the payments. The column payment of the report must use this field (I mean Amount), filtered
by the status X and the column winners must use this field (Amount too) filtered by status Y.
 How can I do this in the cube to use the same measure represented in two columns with their values filtered?

I tried to use the measure expressions but I don't know if this trick could help. I also heard about calculated measures but don't know how it works.

Any ideas?

答:
Add a dimension [STATUS] to your cube containing the members [X] and [Y]. This can be a hidden dimension. Add [Amount] as a measure and hide this measure also.

Then, add 2 calculated measures to your cube:

[Measures].[Payment] with MDX expression:

```<code>([Status].[Status].[X], [Measures].[Amount])
</code>```

And [Measures].[Winners] as

```<code>([Status].[Status].[Y], [Measures].[Amount])
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Add a dimension [STATUS] to your cube containing the members [X] and [Y]. This can be a hidden dimension. Add [Amount] as a measure and hide this measure also.

Then, add 2 calculated measures to your cube:

[Measures].[Payment] with MDX expression:

([Status].[Status].[X], [Measures].[Amount])

And [Measures].[Winners] as

([Status].[Status].[Y], [Measures].[Amount])


问:
Update android app on google playstore for new Android flagship devices
I am a cocos2d-x game developer and recently uploaded app on google playstore. I have just logged in the google play store and saw a notification message "Update your app to take advantage of the larger aspect ratio on new Android flagship devices ". I dont understand what exactly this means and what changes i need to make in my app to run properly after these new aspect ratio. See the below image.

答:
Have you read the recent announcement at below link ?

https://android-developers.googleblog.com/2017/03/update-your-app-to-take-advantage-of.html

The changes are also specified in the same article. Basically you need to add a piece of code in your manifest file, if you want to take advantage of the larger screen space going to be available with newer devices with 18:9 aspect ratio.

Code :

<meta-data android:name="android.max_aspect" android:value="2.1" />```


问:
Setup Redmine & plugins on local machine then deploy to Linux server, possible?
I am new to Ruby on Rails. My questions is:

Is it possible to setup Redmine and install the plugins on my local machine (macOS Sierra), test the Redmine application on localhost, once everything has been done successfully, then only deploy it on a Linux server?

If it is possible, which part of the code should I modify in order to deploy it on Linux server successfully? (Both of my local machine and Linux server are running MySQL database)

答:
Yes it is possible and you don't need to change any part of the Redmine code to do so. Deployment of Rails apps is often done with a tool called Capistrano (http://capistranorb.com/), which executes through ssh on your server, checks out the code and does any additional installation steps necessary. This approach requires you to have your app (Redmine and plugins in your case) in a git repository (or subversion etc). In the simplest case, fork redmine on github and add any plugins as git submodules.

As you're unfamiliar with the platform I'd suggest to start with a simple rails app that you create locally. once you have worked out deployment of that to a remote server, tackle Redmine.

Sounds like a lot of upfront effort but it's worth it since it  enables you to work on your local machine, make changes and then deploy the changed code with a single command.


问:
Button for a modal form not displaying or functioning
I've already been on here for a similar question, but moved this interaction in my code and have the same issue... but I believe with a different cause.

I have a page that has an "Email Me" button at the bottom of it:
http://danux.me/

When you click the "Email Me" button, an overlay should appear and with an email form in the middle of it. I had it working on a test page, and then moved all the items over to my index.html and it's not working.

My goal right now is just to get the overlay and form to pop up in the page.

I checked my paths to make sure they were right and I think they are, but I don't know how to parse or inspect php with Google's emulator to see where something might not be working.

I checked my index.html head link to the css, the javascript at the end of my index.html and then in the contact.js, there's a GET link that points down to the php file.

Also, I am unsure in the HTML how to "call"(?) the php or jquery on that button and if that's the issue. It worked before as is and I am assuming that class="contact" is what's making all this work? I don't know. I'd be interested to know how a class triggers a javascript file.

I also got ripped earlier for not having PHP, but I didn't know until today that can't be viewed, so I'll put it below. I'm not sure if it's helpful or not.

```<code>jQuery(function ($) {
 var contact = {
    message: null,
    init: function () {
        $('#contact-form input.contact, #contact-form a.contact').click(function (e) {
            e.preventDefault();

            // load the contact form using ajax
            $.get("contact/data/contact.php", function(data){
                // create a modal dialog with the data
                $(data).modal({
                    closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
                    position: ["15%",],
                    overlayId: 'contact-overlay',
                    containerId: 'contact-container',
                    onOpen: contact.open,
                    onShow: contact.show,
                    onClose: contact.close
                });
            });
        });
    },
    open: function (dialog) {
        // dynamically determine height
        var h = 280;
        if ($('#contact-subject').length) {
            h += 26;
        }
        if ($('#contact-cc').length) {
            h += 22;
        }

        var title = $('#contact-container .contact-title').html();
        $('#contact-container .contact-title').html('Loading...');
        dialog.overlay.fadeIn(200, function () {
            dialog.container.fadeIn(200, function () {
                dialog.data.fadeIn(200, function () {
                    $('#contact-container .contact-content').animate({
                        height: h
                    }, function () {
                        $('#contact-container .contact-title').html(title);
                        $('#contact-container form').fadeIn(200, function () {
                            $('#contact-container #contact-name').focus();

                            $('#contact-container .contact-cc').click(function () {
                                var cc = $('#contact-container #contact-cc');
                                cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
                            });
                        });
                    });
                });
            });
        });
    },
    show: function (dialog) {
        $('#contact-container .contact-send').click(function (e) {
            e.preventDefault();
            // validate form
            if (contact.validate()) {
                var msg = $('#contact-container .contact-message');
                msg.fadeOut(function () {
                    msg.removeClass('contact-error').empty();
                });
                $('#contact-container .contact-title').html('Sending...');
                $('#contact-container form').fadeOut(200);
                $('#contact-container .contact-content').animate({
                    height: '80px'
                }, function () {
                    $('#contact-container .contact-loading').fadeIn(200, function () {
                        $.ajax({
                            url: '/contact/data/contact.php',
                            data: $('#contact-container form').serialize() + '&action=send',
                            type: 'post',
                            cache: false,
                            dataType: 'html',
                            success: function (data) {
                                $('#contact-container .contact-loading').fadeOut(200, function () {
                                    $('#contact-container .contact-title').html('Thank you!');
                                    msg.html(data).fadeIn(200);
                                });
                            },
                            error: contact.error
                        });
                    });
                });
            }
            else {
                if ($('#contact-container .contact-message:visible').length > 0) {
                    var msg = $('#contact-container .contact-message div');
                    msg.fadeOut(200, function () {
                        msg.empty();
                        contact.showError();
                        msg.fadeIn(200);
                    });
                }
                else {
                    $('#contact-container .contact-message').animate({
                        height: '30px'
                    }, contact.showError);
                }

            }
        });
    },
    close: function (dialog) {
        $('#contact-container .contact-message').fadeOut();
        $('#contact-container .contact-title').html('Goodbye...');
        $('#contact-container form').fadeOut(200);
        $('#contact-container .contact-content').animate({
            height: 40
        }, function () {
            dialog.data.fadeOut(200, function () {
                dialog.container.fadeOut(200, function () {
                    dialog.overlay.fadeOut(200, function () {
                        $.modal.close();
                    });
                });
            });
        });
    },
    error: function (xhr) {
        alert(xhr.statusText);
    },
    validate: function () {
        contact.message = '';
        if (!$('#contact-container #contact-name').val()) {
            contact.message += 'Name is required. ';
        }

        var email = $('#contact-container #contact-email').val();
        if (!email) {
            contact.message += 'Email is required. ';
        }
        else {
            if (!contact.validateEmail(email)) {
                contact.message += 'Email is invalid. ';
            }
        }

        if (!$('#contact-container #contact-message').val()) {
            contact.message += 'Message is required.';
        }

        if (contact.message.length > 0) {
            return false;
        }
        else {
            return true;
        }
    },
    validateEmail: function (email) {
        var at = email.lastIndexOf("@");

        // Make sure the at (@) sybmol exists and
        // it is not the first or last character
        if (at < 1 || (at + 1) === email.length)
            return false;

        // Make sure there aren't multiple periods together
        if (/(\.{2,})/.test(email))
            return false;

        // Break up the local and domain portions
        var local = email.substring(0, at);
        var domain = email.substring(at + 1);

        // Check lengths
        if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
            return false;

        // Make sure local and domain don't start with or end with a period
        if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
            return false;

        // Check for quoted-string addresses
        // Since almost anything is allowed in a quoted-string address,
        // we're just going to let them go through
        if (!/^"(.+)"$/.test(local)) {
            // It's a dot-string address...check for valid characters
            if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
                return false;
        }

        // Make sure domain contains only valid characters and at least one period
        if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
            return false;

        return true;
    },
    showError: function () {
        $('#contact-container .contact-message')
            .html($('<div class="contact-error"></div>').append(contact.message))
            .fadeIn(200);
    }
};

contact.init();

  });
</code>```

答:
Is this the functionality you are looking for?
See:
http://www.joecodeman.com/ITServices/Demos/jQuery/ShowDemo_v01a.html

If this is the effect dgbenner is looking for... then it is just a matter of organizing his/her code so it works correctly.

The basic effect dgbenner is trying to achieve is very simple. Therefore, the code just needs to be organized correctly.

This is the basic code / pseudo code:

```<code>//1) run the currently selected effect
function runEffect() {

//2) Hide the button`
  $( "#eMailButton" ).fadeOut();

  //3) Show the email form
  $( "#effect" ).show( selectedEffect, options, 500, callback );

  //4) Hide the email form and show the button again ( 4 seconds later in this demo...)
  // other effects and actions can be coded when the user submits his/her info..)
  function callback() {
    setTimeout(function() {
      $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
      $( "#eMailButton" ).fadeIn();
    }, 4000 );
  };
</code>```

Body:
I've already been on here for a similar question, but moved this interaction in my code and have the same issue... but I believe with a different cause.

I have a page that has an "Email Me" button at the bottom of it:
http://danux.me/

When you click the "Email Me" button, an overlay should appear and with an email form in the middle of it. I had it working on a test page, and then moved all the items over to my index.html and it's not working.

My goal right now is just to get the overlay and form to pop up in the page.

I checked my paths to make sure they were right and I think they are, but I don't know how to parse or inspect php with Google's emulator to see where something might not be working.

I checked my index.html head link to the css, the javascript at the end of my index.html and then in the contact.js, there's a GET link that points down to the php file.

Also, I am unsure in the HTML how to "call"(?) the php or jquery on that button and if that's the issue. It worked before as is and I am assuming that class="contact" is what's making all this work? I don't know. I'd be interested to know how a class triggers a javascript file.

I also got ripped earlier for not having PHP, but I didn't know until today that can't be viewed, so I'll put it below. I'm not sure if it's helpful or not.

jQuery(function ($) {
 var contact = {
    message: null,
    init: function () {
        $('#contact-form input.contact, #contact-form a.contact').click(function (e) {
            e.preventDefault();

            // load the contact form using ajax
            $.get("contact/data/contact.php", function(data){
                // create a modal dialog with the data
                $(data).modal({
                    closeHTML: "x",
                    position: ["15%",],
                    overlayId: 'contact-overlay',
                    containerId: 'contact-container',
                    onOpen: contact.open,
                    onShow: contact.show,
                    onClose: contact.close
                });
            });
        });
    },
    open: function (dialog) {
        // dynamically determine height
        var h = 280;
        if ($('#contact-subject').length) {
            h += 26;
        }
        if ($('#contact-cc').length) {
            h += 22;
        }

        var title = $('#contact-container .contact-title').html();
        $('#contact-container .contact-title').html('Loading...');
        dialog.overlay.fadeIn(200, function () {
            dialog.container.fadeIn(200, function () {
                dialog.data.fadeIn(200, function () {
                    $('#contact-container .contact-content').animate({
                        height: h
                    }, function () {
                        $('#contact-container .contact-title').html(title);
                        $('#contact-container form').fadeIn(200, function () {
                            $('#contact-container #contact-name').focus();

                            $('#contact-container .contact-cc').click(function () {
                                var cc = $('#contact-container #contact-cc');
                                cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
                            });
                        });
                    });
                });
            });
        });
    },
    show: function (dialog) {
        $('#contact-container .contact-send').click(function (e) {
            e.preventDefault();
            // validate form
            if (contact.validate()) {
                var msg = $('#contact-container .contact-message');
                msg.fadeOut(function () {
                    msg.removeClass('contact-error').empty();
                });
                $('#contact-container .contact-title').html('Sending...');
                $('#contact-container form').fadeOut(200);
                $('#contact-container .contact-content').animate({
                    height: '80px'
                }, function () {
                    $('#contact-container .contact-loading').fadeIn(200, function () {
                        $.ajax({
                            url: '/contact/data/contact.php',
                            data: $('#contact-container form').serialize() + '&action=send',
                            type: 'post',
                            cache: false,
                            dataType: 'html',
                            success: function (data) {
                                $('#contact-container .contact-loading').fadeOut(200, function () {
                                    $('#contact-container .contact-title').html('Thank you!');
                                    msg.html(data).fadeIn(200);
                                });
                            },
                            error: contact.error
                        });
                    });
                });
            }
            else {
                if ($('#contact-container .contact-message:visible').length > 0) {
                    var msg = $('#contact-container .contact-message div');
                    msg.fadeOut(200, function () {
                        msg.empty();
                        contact.showError();
                        msg.fadeIn(200);
                    });
                }
                else {
                    $('#contact-container .contact-message').animate({
                        height: '30px'
                    }, contact.showError);
                }

            }
        });
    },
    close: function (dialog) {
        $('#contact-container .contact-message').fadeOut();
        $('#contact-container .contact-title').html('Goodbye...');
        $('#contact-container form').fadeOut(200);
        $('#contact-container .contact-content').animate({
            height: 40
        }, function () {
            dialog.data.fadeOut(200, function () {
                dialog.container.fadeOut(200, function () {
                    dialog.overlay.fadeOut(200, function () {
                        $.modal.close();
                    });
                });
            });
        });
    },
    error: function (xhr) {
        alert(xhr.statusText);
    },
    validate: function () {
        contact.message = '';
        if (!$('#contact-container #contact-name').val()) {
            contact.message += 'Name is required. ';
        }

        var email = $('#contact-container #contact-email').val();
        if (!email) {
            contact.message += 'Email is required. ';
        }
        else {
            if (!contact.validateEmail(email)) {
                contact.message += 'Email is invalid. ';
            }
        }

        if (!$('#contact-container #contact-message').val()) {
            contact.message += 'Message is required.';
        }

        if (contact.message.length > 0) {
            return false;
        }
        else {
            return true;
        }
    },
    validateEmail: function (email) {
        var at = email.lastIndexOf("@");

        // Make sure the at (@) sybmol exists and
        // it is not the first or last character
        if (at < 1 || (at + 1) === email.length)
            return false;

        // Make sure there aren't multiple periods together
        if (/(\.{2,})/.test(email))
            return false;

        // Break up the local and domain portions
        var local = email.substring(0, at);
        var domain = email.substring(at + 1);

        // Check lengths
        if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
            return false;

        // Make sure local and domain don't start with or end with a period
        if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
            return false;

        // Check for quoted-string addresses
        // Since almost anything is allowed in a quoted-string address,
        // we're just going to let them go through
        if (!/^"(.+)"$/.test(local)) {
            // It's a dot-string address...check for valid characters
            if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
                return false;
        }

        // Make sure domain contains only valid characters and at least one period
        if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
            return false;

        return true;
    },
    showError: function () {
        $('#contact-container .contact-message')
            .html($('

').append(contact.message))
            .fadeIn(200);
    }
};

contact.init();

  });

Body:
Is this the functionality you are looking for?
See:
http://www.joecodeman.com/ITServices/Demos/jQuery/ShowDemo_v01a.html

If this is the effect dgbenner is looking for... then it is just a matter of organizing his/her code so it works correctly.

The basic effect dgbenner is trying to achieve is very simple. Therefore, the code just needs to be organized correctly.

This is the basic code / pseudo code:

//1) run the currently selected effect
function runEffect() {

//2) Hide the button`
  $( "#eMailButton" ).fadeOut();

  //3) Show the email form
  $( "#effect" ).show( selectedEffect, options, 500, callback );

  //4) Hide the email form and show the button again ( 4 seconds later in this demo...)
  // other effects and actions can be coded when the user submits his/her info..)
  function callback() {
    setTimeout(function() {
      $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
      $( "#eMailButton" ).fadeIn();
    }, 4000 );
  };


问:
how can I keep a floating view always on top of my app?
If  my app have the permission ,"android.permission.SYSTEM_ALERT_WINDOW", you know my problem can be resolved esaily . But on most of the android phone from China , the user should grant this permission manually . so is there a solution while my app has not the permission ?  I just want the view floating on my app not the whole system . I have a bad way : let my app only contain one activity , and make all the pages just fragments  in the activity. </p>

答: There are no alternative solution of it. Almost all device above api 21 taking grant permission of user to show floating icon over any another app. Some phone like Redmi, Oppo etc. its all have given more security permissio, without user permission its not granted.</p>


问:
Why an image input button is not considered as a child element of a form in JavaScript?
I ran the following code and found a weird problem: the image input button is not treated as a child element form? Could anyone pls tell me why this happens?

window.onload = function(event) {
  formElements = document.forms[0].elements;

  //output 2
  console.log(formElements.length);

  //output only two elements
  for (var i = 0; i < formElements.length; i++) {
    console.log(formElements[i]);
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" name="form" action="" method="post">
  <input type="text" name="username" value="" />
  <button>Submit</button>
  <input type="image" src="http://www.starmarkcabinetry.com/Style%20Library/StarMark/images/right-button-small.png" />
</form></code>```

答:
The HTMLFormElement.elements property returns an
  HTMLFormControlsCollection (HTML 4 HTMLCollection) of all the form
  controls contained in the FORM element, with the exception of input
  elements which have a type attribute of image.

MDN Doc for HTMLFormElement.elements

Specification related to Listed Items

You can use children to get the same.

I can't find a reason why this is made the way it is, I feel bad for input[type=image] I hope someone who works closely with Web APIS can shed light into some funny reason like what happened with Pluto

The historical reasons can be found here

Body:
I ran the following code and found a weird problem: the image input button is not treated as a child element form? Could anyone pls tell me why this happens?

window.onload = function(event) {
  formElements = document.forms[0].elements;

  //output 2
  console.log(formElements.length);

  //output only two elements
  for (var i = 0; i < formElements.length; i++) {
    console.log(formElements[i]);
  }
};

<form id="form" name="form" action="" method="post">
  <input type="text" name="username" value="" />
  <button>Submit</button>
  <input type="image" src="http://www.starmarkcabinetry.com/Style%20Library/StarMark/images/right-button-small.png" />
</form>


问:
BlazeDS vs. GraniteDS
Anyone have any experience evaluating BlazeDS and GraniteDS? I'm curious about which is better at integrating with Spring/Hibernate.</p>

答:
If you are just looking for simple RPC and messaging, I would go with Blaze. The implementations are more mature and better proven, especially with respect to messaging.  The messaging in Granite is based on Comet and still pretty new from what I remember.  More details below...

Blaze DS is basically a stack that includes RPC and some simple messaging services over HTTP.  Integration with Spring is achieved easily using the SpringFactory implementation of FlexFactory: just google the class name and you'll find the code.  It doesn't offer any additional support for things Hibernate-related.

Granite DS is growing rapidly in terms of features.  It competes more with LCDS than Blaze DS.  It includes the ability to parse Hibernate object graphs and deal with lazy proxies in a clean fashion.  They also have a tool called "Tide" that creates an analog of a Session in the Flex client to ensure uniqueness of entities.  They also have explicit support for services exposed via Spring, EJB3 and Seam.  Granite also has a utility for generating AS3 classes from your Java classes (although this not hard to write yourself if you want to).

I worked with Granite about a year ago and had some problems getting it properly parse object graphs; the Flash Player would throw some nasty low-level exceptions.  My guess is that the documentation and implementation have matured since so that these are no longer issues.  However, I'm still a bit hesitant to recommend it since I ran into issues and switching to Blaze immediately resolved them with no trouble at all.

OwnerDisplayName: mikemacman

Title: BlazeDS vs. GraniteDS


问:
Pickaday2 not working properly in modal window
Getting issues in date picker.

If I use the picker in the bootstrap modal window. The year select drop-down list and month selection dropdown list not opening in firefox but it's working fine on chrome.

答:
Please check with below code, this should work, </p>

```<code>$.fn.modal.Constructor.prototype.enforceFocus = function() {};
</code>```

Body:
Please check with below code, this should work,

$.fn.modal.Constructor.prototype.enforceFocus = function() {};


问:
Wordpress slow due to unusual request
My Wordpress is extremely slow due to a request I have. I tried removing some plugins but no luck. I am using WP-rocket for caching.

Here is my analysis on pingdom where it says a request with xxxx/?version=4.7.3 is slowing down everything

How can I resolve this?

Many thanks

答:
Turn off all caching while you are testing. Disable all plugins and see if is still there. If it is still there, it might be from the theme. Switch to another theme and test again. If it was gone after deactivating all plugins, turn them on one by one and test again to see which one adds it.

Another thing to do is to download your whole folder of your site on your computer and then using a free grep program to search for the domain name dentiste-urgence.ca and see if it is mentioned in any files.

This might also be caused by malware. Install the free security plugin WordFence and scan your site for malware.

Title: Wordpress slow due to unusual request


问:
How to use MySQLdb with Python and Django in OSX 10.6?
This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:

Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit

I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error:

```<code>Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
</code>```

I've also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?).

Anyone dealt with this before?

答:
I overcame the same problem by installing MySQL-python library using pip. You can see the message displayed on my console when I first changed my database settings in settings.py and executed makemigrations command(The solution is following the below message, just see that).

```<code>  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb
</code>```

Finally I overcame this problem as follows:

```<code>(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$
</code>```

Body:
This is a much discussed issue for OSX 10.6 users, but I haven't been able to find a solution that works. Here's my setup:

Python 2.6.1 64bit
Django 1.2.1
MySQL 5.1.47 osx10.6 64bit

I create a virtualenvwrapper with --no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error:

Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I've also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?).

Anyone dealt with this before?

Body:
I overcame the same problem by installing MySQL-python library using pip. You can see the message displayed on my console when I first changed my database settings in settings.py and executed makemigrations command(The solution is following the below message, just see that).

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Finally I overcame this problem as follows:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$


问:
Morris.js line graph x-axis labels disappear after resize
X-axis labels dissapear after resize. Tried changing xLabelMargin, but it doesnt solve the problem. Could you help me please?

Before resize: http://prnt.sc/b5evpw
After resize: http://prnt.sc/b5evuo

My graph:

```<code><script>
    var months = ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'];
    var data = JSON.parse('{{ $data }}');
    var linegraph = Morris.Line({
          element: 'linegraph',
          data: data,
          xkey: 'month',
          ykeys: ['income', 'expenses'],
          labels: ['Pajamos', 'Išlaidos'],
          xLabelFormat: function (x) { return months[x.getMonth()]; },
          xLabelAngle: 45,
          hoverCallback: function (index, options, content, row) {
            return  "<span style='color:rgb(11, 98, 164)'>Pajamos "+ row.income + "</span><span style='color:rgb(122, 146, 163)'><br> Išlaidos " + row.expenses + "</span>";
          },
          resize: true
        });
</script>
</code>```

答: I had the same problem. After using parseTime:false its working fine for me


问:
How to build a method that counts how large a group is in an array?
I'm curious on how to build an array (in Java) that tallies how large a group is (consecutive elements with the same value) and prints it through a seperate runner file. So far, this is my code. I've got everything down except for the getNumGroupsOfSize method, which does the counting:

import static java.lang.System.*;
import java.util.Arrays;
import java.util.Scanner;

public class ArrayStats
{
    int[] numArray;

    public ArrayStats(int[]array)
    {
        setArray(int[]array);
    }

    public void setArray(int[]array)
    {
        numArray=array;
    }

    public int getNumGroupsOfSize(int size)
    {
        int cnt=0;
        for (int x=0; x<=size.length; x++)
        {
            do
            {
                count++;
            }
            while (size[x]=size[x+1]);
      return cnt;
     }
    }

    public String toString()
    {
        return ""+Arrays.toString(array);
    }
}```

答:
You could use the build in functionality for counting groups.

Example from another question here.

https://stackoverflow.com/a/25441208/2710666


问:
routerLink not working in innerHTML with angular2&4.0.0+
I'm using:[angular-cli=1.0.0+ node=7.7.4+ angular=4.0.0+]
in my html page i use code

ts: htmlWrite=''
but when i use 'npm start' start my serve,in html i just see ,there is no link with '/user/list'.
I search answer much about this and I tried much times but still failed,could you tell me how to solve this ? by using NgComponentOutlet? or others? please tell me the detail.thanks. PS:angular2(4.0.0+)

答:
write you code with simplicity. </p>

```<code><div> <a routerLink = "user/list"></a> </div>
</code>```

Body:
write you code with simplicity.

<div> <a routerLink = "user/list"></a> </div>