text:
Q: JPA @manytomany unidirectional mapping When I try remove ExternalDataStorage  This query throw a constraint violation exception with  constraint name null .ExternalDataStorage has no relation mapping on it.Query first check ExternalTasks whichs contain ExternalDataStorage(Which will be removed) in ExternalTask's externalsources List and remove from list, if  list is empty remove externaltask and finally remove ExternalDataStorage entity(Target entity).
      public boolean deleteExternalDataStorage(Long sid) {
     EntityManager em = getEntityManager();
    EntityTransaction et = em.getTransaction();
    try {
        et.begin();
        ExternalDataStorage s = em.find(ExternalDataStorage.class, sid);
        List<ExternalTask> tasks = (List<ExternalTask>) em.createQuery("SELECT t FROM ExternalTask t ").getResultList();
        for (ExternalTask t : tasks) {
            if (t.getExternalSources().contains(s)) {
                t.getExternalSources().remove(s);
                if (t.getExternalSources().isEmpty()) {
                    em.remove(t);
                } else {
                    t = em.merge(t);
                }
            }
        }
        em.remove(s);
        et.commit();
        return true;
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (et.isActive()) {
            et.rollback();
        }
    }
    return false;
}

@Entity
public class ExternalTask implements Serializable {
@ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(name = "ExternalTask_ExternalSource", joinColumns = @JoinColumn(name = "TID"), inverseJoinColumns = @JoinColumn(name = "EXID"))
private  List<ExternalDataStorage> externalSources =new ArrayList<ExternalDataStorage>();

@ManyToMany(cascade={CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
@JoinTable(name = "ExternalTask_Archive", joinColumns = @JoinColumn(name = "TID"), inverseJoinColumns = @JoinColumn(name = "AID"))
protected  List<Archive> archives=new ArrayList<Archive>();

@ManyToOne
private User  ownerUser;

_EDIT___________________
I change query a little for delete case but problem still there
  EntityManager em = getEntityManager();
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            ExternalDataStorage s = em.find(ExternalDataStorage.class, sid);
            List<ExternalTask> tasks=(List<ExternalTask>) em.createQuery("SELECT t FROM ExternalTask t ").getResultList();
           for(ExternalTask t:tasks) {
              if(t.getExternalSources().contains(s)){
                 t.getExternalSources().remove(s);
                  t= em.merge(t);
                  if(t.getExternalSources().isEmpty()){
                      em.remove(t);
                  }
               }
           }
            em.remove(s);
            et.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (et.isActive()) {
                et.rollback();
            }
        }
        return false;
    }

This is exception
**377249 [http-8080-2] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: null
377249 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter  - Batch entry 0 delete from ExternalSource where EXID=6 was aborted.  Call getNextException to see the cause.
377249 [http-8080-2] WARN  org.hibernate.util.JDBCExceptionReporter  - SQL Error: 0, SQLState: 23503
377249 [http-8080-2] ERROR org.hibernate.util.JDBCExceptionReporter  - ERROR: update or delete on table "externalsource" violates foreign key constraint "fk755287f526733b01" on table "externaltask_externalsource"
  Detail: Key (exid)=(6) is still referenced from table "externaltask_externalsource".
377250 [http-8080-2] ERROR org.hibernate.event.def.AbstractFlushingEventListener  - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
    at com.endersys.itap.ui.module.storage.StorageManager.deleteExternalDataStorage(StorageManager.java:351)
    at com.endersys.itap.ui.module.storage.ExternalDataStorageEditorBean.delete(ExternalDataStorageEditorBean.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:616)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:172)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
    at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:78)
    at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:57)
    at javax.faces.component.UICommand.broadcast(UICommand.java:127)
    at org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55)
    at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
    at org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)
    at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)
    at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)
    at org.apache.my**faces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:183)
    at org.apache.myfaces.webapp.MyFacesServlet.service(MyFacesServlet.java:103)
    at com.endersys.itap.ui.MyFacesServletWrapper.service(MyFacesServletWrapper.java:34)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
    at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
    at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
    at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at com.endersys.itap.ui.MenuFilter.doFilter(MenuFilter.java:169)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:636)

Caused by: java.sql.BatchUpdateException: Batch entry 0 delete from ExternalSource where EXID=6 was aborted.  Call getNextException to see the cause.
        at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2537)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1328)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:351)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2674)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
        ... 55 more
javax.persistence.RollbackException: Error while commiting the transaction
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:71)
        at com.endersys.itap.ui.module.storage.StorageManager.deleteExternalDataStorage(StorageManager.java:351)
        at com.endersys.itap.ui.module.storage.ExternalDataStorageEditorBean.delete(ExternalDataStorageEditorBean.java:73)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at org.apache.el.parser.AstValue.invoke(AstValue.java:172)
        at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:276)
        at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
        at javax.faces.component._MethodExpressionToMethodBinding.invoke(_MethodExpressionToMethodBinding.java:78)
        at org.apache.myfaces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:57)
        at javax.faces.component.UICommand.broadcast(UICommand.java:127)
        at org.ajax4jsf.component.AjaxActionComponent.broadcast(AjaxActionComponent.java:55)
        at org.ajax4jsf.component.AjaxViewRoot.processEvents(AjaxViewRoot.java:329)
        at org.ajax4jsf.component.AjaxViewRoot.broadcastEventsForPhase(AjaxViewRoot.java:304)
        at org.ajax4jsf.component.AjaxViewRoot.processPhase(AjaxViewRoot.java:261)
        at org.ajax4jsf.component.AjaxViewRoot.processApplication(AjaxViewRoot.java:474)
        at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:32)
        at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)
        at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:183)
        at org.apache.myfaces.webapp.MyFacesServlet.service(MyFacesServlet.java:103)
        at com.endersys.itap.ui.MyFacesServletWrapper.service(MyFacesServletWrapper.java:34)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:206)
        at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
        at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:388)
        at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:515)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at com.endersys.itap.ui.MenuFilter.doFilter(MenuFilter.java:169)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
        at java.lang.Thread.run(Thread.java:636)
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
        at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
        at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:249)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235)
        at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144)
        at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
        at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
        at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
        at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
        at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
        at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54)
        ... 47 more
Caused by: java.sql.BatchUpdateException: Batch entry 0 delete from ExternalSource where EXID=6 was aborted.  Call getNextException to see the cause.
        at org.postgresql.jdbc2.AbstractJdbc2Statement$BatchResultHandler.handleError(AbstractJdbc2Statement.java:2537)
        at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1328)
        at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:351)
        at org.postgresql.jdbc2.AbstractJdbc2Statement.executeBatch(AbstractJdbc2Statement.java:2674)
        at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
        at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242)
        ... 55 more
And this is constraint on table

ALTER TABLE externaltask_externalsource
  ADD CONSTRAINT fk755287f526733b01 FOREIGN KEY (exid)
      REFERENCES externalsource (exid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION;

A: Find it little bit hard to understand the question. I'm assuming you are looking for the externalsources to be removed when you remove the externaltask entity. I think for that you need to include REMOVE in your cascade settings or basically cascade={CascadeType.ALL}
EDIT:
Think I found the answer to your situation. When the many to many is wired the PP creates an integrity constraint on the db (I'm thinking you are doing an auto gen of the schema from the entities).
In this case SOURCE_TASK table where the relationship between source and task is held, has a foreign key relationship towards SOURCE table. So when you try to remove something from SOURCE table the underlying db gives a sql exception. I was able to reproduce your issue.
Solution:
What I did was I removed the foreign key constraint and I was able to remove the source entity fine.
As I originally stated for the TASK to SOURCE removal
If you remove the TASK entity with Cascade.ALL it should remove the entries everywhere.
Update: I'm thinking there is something in the way you are dealing with equality among your SOURCE objects. The List.contains(o) will be true if at least one object that is 'equal' is found. The List.remove(o) will remove the first occurrence of an object that 'equals' o. So I bet there are multiple occurrences of 'equal' objects inside the list.

A: I add join fetch and problem solved.
public boolean deleteExternalDataStorage(Long sid) {
        EntityManager em = getEntityManager();
        EntityTransaction et = em.getTransaction();

        try {
            et.begin();
            ExternalDataStorage s = em.find(ExternalDataStorage.class, sid);
            List<ExternalTask> tasks=(List<ExternalTask>) em.createQuery("SELECT t FROM ExternalTask t join fetch t.externalSources").getResultList();
           for(ExternalTask t:tasks) {
              if(t.getExternalSources().contains(s)){
                      t.getExternalSources().remove(s);
                  if(t.getExternalSources().isEmpty()){
                      em.remove(t);
                  }
               }
           }
            em.remove(s);
            et.commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
             if (et.isActive()) {
                et.rollback();
            }

        } finally {

        }
        return false;
    }


text:
Q: Getting html response from jsonp ajax call I'm curious as to why with this ajax call:
   $.ajax({
      dataType: 'jsonp',
      type: 'GET',
      url: 'http://localhost:3000/gwsearch/ajax_search?d1=36354&d2=36355',
      crossDomain: true
  }).done(function(data){
    alert(data);
  });

To this rails method:
    def ajax_search
     #random code
      respond_to do |format|
        format.html
        format.js { render :json => @gw_search_results.to_json, :callback => params['callback'] }
     end

I am getting an html response.  If I remove the "format.html" I get a jsonp response back with the correct data, but I am just curious as to why rails is choosing to send back html by default, instead of jsonp?  What am I missing?  I thought with  a js call, it shoots back a js response if available?

A: http://davidwparker.com/2010/03/09/api-in-rails-respond-to-and-respond-with/
There needs to be an explicit respond to and respond with statement.

A: Figured it out, for those wondering, the order of your respond_to statements does indeed matter.  I did not think they did.  This yields me a json response:
    respond_to do |format|
      if params[:callback]
        format.js { render :json => {:items_by_tag => @gw_search_results.to_json}, :callback => params[:callback] }
      else
        format.json { render json: {:items_by_tag => @gw_search_results}}
       end
    format.html
    end

It seems to hit the jsonp callback conditional and spit me back what I need, where as before, I had
    respond_to do |format|
    format.html
      if params[:callback]
        format.js { render :json => {:items_by_tag => @gw_search_results.to_json}, :callback => params[:callback] }
      else
        format.json { render json: {:items_by_tag => @gw_search_results}}
       end
    end

I'm guessing it saw the format.html as a valid response and yielded that response instead of the json.  Note that even when I changed the request headers on the ajax call to "application/json" I still was getting an html response back with the problematic code I have showcased at the bottom.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting "Unknown primary key for table" while the ID is there I've been debugging this strange problem of Rails giving me "Unknown primary key for table...", even when the table's ID is there.
I've copied the database from one heroku app to another, on the original databse there is no problem and the new one gives me a db error.
This is the error:
ProductsController# (ActionView::Template::Error) "Unknown primary key for table collections in model Collection."

/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:366:in `primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:480:in `association_primary_key'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:58:in `block in add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `each_with_index'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:39:in `add_constraints'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association_scope.rb:31:in `scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:98:in `association_scope'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:87:in `scoped'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:573:in `first_or_last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:105:in `last'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/associations/collection_proxy.rb:46:in `last'
/app/app/helpers/likes_helper.rb:62:in `significant_liker'

The line that causes it:
product.collections.last.try :user

and the table:
d8apjspa441pad=> \d collections
                                     Table "public.collections"
     Column     |          Type          |                        Modifiers
----------------+------------------------+----------------------------------------------------------
 id             | integer                | not null default nextval('collections_id_seq'::regclass)
 name           | character varying(255) |
 user_id        | integer                |
 permalink      | character varying(255) |
 category_id    | integer                |
 products_count | integer                |
 is_featured    | boolean                |
Indexes:
    "index_lists_on_user_id_and_permalink" UNIQUE, btree (user_id, permalink)

Any idea why this might happen?
Thanks!

A: Seems primary key is missing for the table collections.
Prior to Rails 3.2, set the primary key in model like
class Collection < ActiveRecord::Base
  set_primary_key "my_existing_column"
end

In Rails 3.2+ and Rails 4, set the primary key in model like
class Collection < ActiveRecord::Base
  self.primary_key = "my_existing_column"
end

OR
We can alter the table and set the primary key for id like
Create a migration file to set the primary key
class AddPrimaryKeyToCollections < ActiveRecord::Migration
 def change
   execute "ALTER TABLE collections ADD PRIMARY KEY (id);"
 end
end

A: I was restoring database dump from heroku to my local system and was getting this error..
ActiveRecord::UnknownPrimaryKey: ActiveRecord::UnknownPrimaryKey

I was restoring on existing database, so I dropped the database, created new database and then restore the dump and it worked for me

A: What helped for me (happened on heroku after a db restore) is reindexing the primary key index:
reindex index $primary_key_index_name

A: I was having a similar problem and this was the only page I could find.  So just in case it will be of help to anyone else...
I started suddenly getting missing primary key messages on a couple tables.  I'm guessing, but not sure, that this started happening after pushing data (pg_dump local, heroku pg:restore)
The primary keys in question were both on tables that had been renamed so that the pkey name did not match the table name--but on the other hand lots of other renamed tables were in the same boat and did not have problems.
Anyway, at one point in my flailing around I tried uploading another dump file and I noticed some complaints on the offending indices.  First it would try to delete them and complain that it couldn't because they did not exist.  Later it would try to create them and complain that it couldn't because they already existed.
Very annoying considering that pkey info doesn't show up in schema.rb and is supposed to 'just work', right?
Anyway, what worked for me (and thus the reason I'm posting) is to do a heroku pg:reset and then load the dump again.  Side note, I got 'internal server error' the first two times I tried heroku pg:reset.  But later I tried again and it worked.

A: TL;DR: try restarting the app.
heroku restart

I recently encountered this error: "Unknown primary key for table", and like the question asker, it appeared after copying a database to a Heroku app.
The copied database had no errors, so I was confident the table and primary key were fine.
I tried a few suggestions on this page, including starting from scratch with a heroku pg:reset, new pg_dump of the old database, and pgbackups:restore into the new database, then running migrations and seeding... nothing worked.
What finally solved my problem was restarting the app.  The new app had many database migrations, and restarting the app reloaded the schema and picked up the changes. This page from Heroku's documentation explains:
Running Rake Commands

After running a migration you'll want to restart your app with heroku restart to reload the schema and pickup any schema changes.

A: I was having this problem and the issue turned out to be that my table somehow actually didn't have a primary key index. The solution was to create a migration that added a primary key:
execute "ALTER TABLE appointment_reminder_text ADD PRIMARY KEY (id)"

A: The same thing happens to me also while importing the data dump from heroku to local. I have the Rails 5.1.6 for the application.
After adding self.primary_key = "id" to all of the models which is showing issue, everything works fine for me.

A: If you're trying to troubleshoot this issue make sure you check your logs carefully. I noticed an earlier error related to a js asset that wasn't being precompiled. This got lost in the stack of rendering messages.
Once I fixed the asset precompilation issue, the 'Unknown primary key for table' error was no longer thrown.
This was 100% definitely the only thing I changed.

A: Thanks changing the index above worked for me. Just another quick note about how this error will manifest itself if there's a more complex relation involved:
ActiveRecord::StatementInvalid - PG::SyntaxError: ERROR:  zero-length delimited identifier at or near """"
LINE 1: ...CT "users".* FROM "users"  WHERE "benefits"."" IN ('1'...

A: restarting the heroku server worked for me. Maybe it was the spring-preloader which was recognizing the empty db-schema, during the db-restorement

A: I encountered this error doing tests in RSPEC.
In my case, i solved it by adding/setting primary_key in my Rails model
class Tablename < ApplicationRecord
   self.primary_key ="id" if Rails.env.test? #optional condition
   ......
end

A: You should reload the schema on the target app. Then load the database.


text:
Q: How to change default root password for Live Kali Linux - USB persistence After making a USB Live with Persistence stick, I tried to change root default password (using passwd) to no avail. Every time I reboot it resets to the default one. All other changes I've made (e.g. keyboard layout change, language change, update & upgrade all packages) do persist, except this one.

A: From Kali's forum, they suggest sed, I use a text editor as root but either will work. sed syntax is scary if you're not used to it.
You can just comment out the line that is setting the password to a default value on boot. The config file is:
/lib/live/config/0031-root-password

Once this has been commented out by adding the # in front of the usermod command then your password will no longer be changed back to the default value every time you boot up.


text:
Q: Как конкатенировать значения из 3 столбцов в 1? Привет всем. У меня есть 2 таблицы:
Avto:
ID ID_driver
1  23
2  32

Driver
ID_driver  Name   Surname
23         Misha   Volkov
32         Valera  Petrov

Как мне запросом вывести в одно поле сразу и имя, и фамилию водителя, чтобы получить следующее при выводе в таблице Avto
ID Name_Driver
1  Misha Volkov
2  Valera Petrov

Cейчас у меня есть такой запрос, но он выводит по разным полям.
SELECT A.*, DR.NAME AS NAME, DR.SURNAME AS SURNAME
FROM Avto A
INNER JOIN DRIVER DR ON A.ID_Driver = DR.ID

Получается вот такое
ID ID_driver  Name   Surname
1    23       Misha  Volkov
2    32       Valera Petrov

A: ответ для interbase/firebird: select char_field1 || ' ' || char_field2 (гуглится с полпинка при правильном названии бд. )
первоначально теги были проставлены mysql/sql поэтому ответ про mysql оставлю для истории:
google://mysql concat
и в принципе, когда хотите что-нибудь соединить/сложить строки (в любом языке, хоть mysql, хоть python), гуглите concat+mysql, concat python,  а потом  уже задавайте вопрос здесь.  это будет хорошим тоном
в качестве упражнения можете исправить вот это решение:
SELECT A.*, CONCAT(DR.NAME, '%', DR.SURNAME) as driverName
FROM Avto A
INNER JOIN DRIVER DR ON A.ID_Driver = DR.ID

и пожалуйста, если вы о себе не думаете, подумайте о других, не надо писать названия таблиц и полей КАПСОМ. КАПСОМ следует писать операторы SQL.  Иначе кто-нибудь, когда будет дебажить ваши запросы без подсветки синтаксиса (да и с ней тоже), проклянет вас черным словом.
P.S. уточняйте, пожалуйста, базу данных, поскольку тег mysql вы удалили
mysql> use db;
Database changed
mysql>
mysql> create table driver (name text, surname text);
Query OK, 0 rows affected (0.22 sec)

mysql> insert into driver values ('vanya', 'petrov');
Query OK, 1 row affected (0.03 sec)

mysql> select concat(name, surname) from driver;
+-----------------------+
| concat(name, surname) |
+-----------------------+
| vanyapetrov           |
+-----------------------+
1 row in set (0.00 sec)

mysql> select concat(name, surname) as kek from driver;
+-------------+
| kek         |
+-------------+
| vanyapetrov |
+-------------+

автора простить можно только потому, что он не знает о существовании кучи диалектов SQL


text:
Q: Alternative to base64_encode Are there any other encoding functions other than base64_encode for encoding text in PHP?
Edit: The purpose of the encoding functions:
To generate a string that can be used in a URL that can be used as an identifier.
For example, instead of http://www.something.com/?id=4&category=books&type=20
I would like to have:
http://www.something.com/?q=a3444aAbt3daj492klsj
So to get the variables one has to decode the only query string which is a hash.

A: Yes, convert_uuencode for instance, but it might be a good idea to explain what you are trying to do!

A: if you want the user not to see meaningful things written in address bar, i am just now on it.

*

*in server you have to enable mod_rewrite (in apache)

*create an .htaccess file in www root folder and put these on there. 1st 3 lines are for real dirs and files.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.+)$ index.php?$1 [L]

*create i.e. index.php and put something like these in it. you can use any kind of 2 way encryption you want. I am using clean url too.
echo "link
echo "link
echo "link
$var1 = $_SERVER['QUERY_STRING'];
$var2 = base64_decode($var1);
$arr = explode("/",$var2);
$_GET["object"] = $arr[0];
$_GET["action"] = $arr[1];
$_GET["id"]     = $arr[2];
if ($_GET["object"] == "birinci") {
echo "a geldi!";
} else if ($_GET["object"] == "ikinci") {
echo "b geldi!";
}


text:
Q: IBM Bluemix disconnecting the MqttAndroidClient after sometime I am working on CC2650 sensortag and Bluemix(using IOT starter boilerplate) as a cloud solution.
The cc2650 android app uses MqttAndroidClient to connect to MQTT server provided by bluemix. The problem I am facing after sometime (around 7 mins) it get timedout.
Following exception is visible on the android studio console
d:2f7tpk:ti-sensortag2:B0B448C07886: Timed out as no activity, keepAlive=240,000 lastOutboundActivity=1,463,309,545,312 lastInboundActivity=1,463,309,275,609 time=1,463,309,785,352 lastPing=1,463,309,545,312
Please note that every 10 seconds I am publishing the data to server from my android client app. So not sure why it is saying no activity.
Keepalive interval is set to 120 seconds.
I confirmed it. It is IBM Bluemix which is disconnecting the client after approx 7 min. During this period client was continuously sending the data in 10 sec interval and that was also visible on the Bluemix device page.
Any idea why Bluemix is disconnecting it after 6-7 minutes (It is not fixed but out of 6 in 5 it got disconnected in 7 min and once it was around 6 min).
New observation:
The other observation is once it is disconnected then it takes 10-12 retries before I am able to reconnect to Bluemix server. From Mqttv3 client I get the exception "Unable to connect to server". But during this period I am able to ping to server through cmdline ping utility.

A: It was because phone cpu was going in sleep mode.
http://dalelane.co.uk/blog/?p=1599 explains in detail what all should be taken care in Android MQTT client.


text:
Q: iOS 15 NavigationLink pop automatically if destination is created dynamically This is a problem on iOS 15 RC only. It works all good on iOS 14.
The problem is if my destination on NavigationLink is created dynamically, it pop automatically if i try push a view via NavigationLink. Here is a bit code snippet
 NavigationLink(
     destination: (createSettingNavigationLink(name: nameAndImage[0])),
     label: {
         CellButton(title: nameAndImage[0], image: nameAndImage[1])
     }

func createSettingNavigationLink(name: String) -> some View {
        if name == "shop.Settings" {
            return ShopSettings()
        }
        if name == "shop.Goods" {
            return ShopGoodsManagementPage()
        }
        if name == "shop.Order" {
            return ShopOrderPage()
        }
        if name == "Customer Service" {
            return ServiceListPage(isStore: true)
        }
        if name == "shop.Performance" {
            return PerformanceManagementPage()
        }
        if name == "shop.Earnings" {
            return CommissionSummaryPage()
        }
        if name == "shop.Increase_sales" {
            return BCWebView(urlStr: Constants.increaseSalesGuide)
                    .navigationBarTitle(Text("Increase Sales Guide"), displayMode: .inline)
                    .navigationBarHidden(false)
            )
        }
        return EmptyView()
    }

)

By the way, the approach mentioned here SwiftUI Unexpectedly NavigationLink pops automatically does not help.

A: My final solution is to change the above function to struct view. I think it makes sense since the struct view seems to keep states while function is pure stateless.


text:
Q: Calculating time interval in iOS application I am developing an iOS application for iPod Touch in which my application displays the server time always. I always sync the application time with server time whenever the application comes to foreground by making a web service call to the server. If there is a connectivity loss between my server and client for few hours I wont be able to sync the application time. I read iOS does not support running a timer when the application is in background other than few limited cases mentioned below:

*

*Apps that play audible content to the user while in the background, such as a music player app

*Apps that keep users informed of their location at all times, such as a navigation app

*Apps that support Voice over Internet Protocol (VoIP)

*Newsstand apps that need to download and process new content

*Apps that receive regular updates from external accessories

So how can I keep track of application time? Whenever the user switches to my application he needs to look at the server time so I need to run a timer to update the last synced server time.

A: A combination of other answers, create a class in charge of obtaining the server time and maintaining the last time the application was synced to the server using a combination of NSDate* lastSync and applicationDidBecomeActive.  For example:
-(void)applicationDidBecomeActive:(UIApplication*)application {
  [ServerTimeSync sharedInstance] resync];
}

ServerTimeSync will maintain an NSDate* property with the last sync time (you'll want to convert what the server gives you to an NSDate*).

A: You can store the NSDate when the app goes into the background. When it resumes, get the current NSDate again, and add the difference to your stored server time.

A: You don't need a timer for this at all.
I would suggest that when you sync time with your server, you have it return its current UNIX timestamp.  You can then do:
[[NSDate date] timeIntervalSince1970];

...to get the device's current UNIX timestamp.  Then what you can do is store the difference between these two timestamps.  This is the clock skew between the server time and the device time.
You can now compute the server's approximate time by taking the device's current UNIX timestamp and adding the clock skew to it.  Adjust for time-zone when displaying it (if you want), and you're done.  Whenever you sync time with the server, you can just refresh the stored clock skew value.
If you want to get fancy, you can also attempt to measure and take network latency into account when determining the clock skew.
This approach should work much better than trying to store the server's absolute timestamp and then track how much time has elapsed using a timer (or any other mechanism).


text:
Q: Remove a randomly selected array from a list during a loop I'm currently trying to develop a kind of simulation game based of Counter Strike for fun and studies.
What I did:
I've created objects to each player, then I put them into an array for their respective teams, then I simulate some duels (randomly selecting which players face who in each round) with results based on their stats (previously declared in their objects properties_.
What I'm trying to do is:
Whenever someone wins a duel, I want them to be removed from the "round" to not have them repeatedly dueling after they "died".
for ( var i = 0; i < 5; i++ ) {
    getConsole = document.querySelector(".console");
    setTimeout( function timer(){
        getConsole.insertAdjacentHTML ("beforebegin", "
Round: " + rounds + "
" );
        calculateAim();
        rounds++
        console.log('rounds ' + rounds) }, i * 3000 );
    };
}

function calculateAim() {

    for ( var r = 0; r < 5; r++ ) {
        getConsole = document.querySelector(".console");
        let playerTeam = [player1, player2, player3]
        let enemyTeam = [player4, player5, player6],

        battle1 = playerTeam[Math.floor(Math.random() * playerTeam.length)];
        battle2 = enemyTeam[Math.floor(Math.random() * enemyTeam.length)];
        console.log("Player Team: " + battle1)
        console.log("Enemy Team: " + battle2)

        let min1 = 0;
        let max2 = 100;
        let EncounterRating = Math.floor(Math.random() * (+max2 - +min1)) + +min1;
        if (EncounterRating < 5) {
            getConsole.insertAdjacentHTML ("beforebegin", "The bomb has exploded and CT's saved their weapons.
");
            break;
        }

        else {

            if (battle1.aim > battle2.aim) {
                getConsole.insertAdjacentHTML ("beforebegin", battle1.name + " killed " + battle2.name + " because your aim is " + battle1.aim + " and his enemie's is " + battle2.aim + "
");
            }

            if (battle1.aim < battle2.aim) {
                getConsole.insertAdjacentHTML ("beforebegin",  battle2.name + " killed " + battle1.name  + " because your aim is " + battle2.aim + " and his enemie's is " + battle1.aim + "
");
            }

            if (battle1.aim == battle2.aim && battle1.luck > battle2.luck) {
                getConsole.insertAdjacentHTML ("beforebegin", battle1.name + " killed " + battle2.name + " with a lucky shot
");
            }

            if (battle1.aim == battle2.aim && battle2.luck > battle1.luck) {
                getConsole.insertAdjacentHTML ("beforebegin", battle2.name + " killed " + battle1.name + " with a lucky timing
");
            }

        }
    }

What I am getting with this code is even if they have lost the duel based on the result of the tests, they will continue in the "round".

A: The cleanest way to go about this would probably be to have a function to compare selected players from each team, remove the player that loses using .splice(), and re-provide the new, smaller arrays to the same function using recursion.

const getConsole = document.querySelector(".console");
let rounds = 1

const player1 = { name: 'Paul', aim: 1, luck: 6 },
  player2 = { name: 'Jim', aim: 2, luck: 5 },
  player3 = { name: 'Sally', aim: 3, luck: 4 },
  player4 = { name: 'Laura', aim: 4, luck: 3 },
  player5 = { name: 'Jim II', aim: 5, luck: 2 },
  player6 = { name: 'Karen', aim: 6, luck: 1 }

getConsole.insertAdjacentHTML("beforebegin", "
Begin battle
");

for (var i = 0; i < 5; i++) {
  setTimeout(function timer() {
    getConsole.insertAdjacentHTML("beforebegin", "
Round: " + rounds + "
");
    battleHelper();
    rounds++
    console.log('rounds ' + rounds)
  }, i * 3000);
}

function battleHelper() {
  let playerTeam = [player1, player2, player3]
  let enemyTeam = [player4, player5, player6]

  battle(playerTeam, enemyTeam);
}

function battle(playerTeam, enemyTeam) {
  // If either of the teams have no members, end the round
  if (!playerTeam.length || !enemyTeam.length) {
    return;
  }

  // Duplicate the input teams to modify them
  let playerTeamOutput = playerTeam
  let enemyTeamOutput = enemyTeam

  // Get the index for a random player from each team
  playerTeamIndex = Math.floor(Math.random() * playerTeamOutput.length)
  enemyTeamIndex = Math.floor(Math.random() * enemyTeamOutput.length)

  // Get the player from each team
  player = playerTeam[playerTeamIndex];
  enemy = enemyTeam[enemyTeamIndex];
  console.log("Player Team: " + player.name)
  console.log("Enemy Team: " + enemy.name)

  let min1 = 0;
  let max2 = 100;

  let EncounterRating = Math.floor(Math.random() * (+max2 - +min1)) + +min1;
  if (EncounterRating < 5) {
    getConsole.insertAdjacentHTML("beforebegin", "The bomb has exploded and CT's saved their weapons.
");
    // If the bomb is detonated, end the round
    return;
  } else {
    if (player.aim > enemy.aim) {
      getConsole.insertAdjacentHTML("beforebegin", player.name + " killed " + enemy.name + " because your aim is " + player.aim + " and his enemie's is " +enemy.aim + "
");
      enemyTeamOutput.splice(enemyTeamIndex, 1)

    } else if (player.aim < enemy.aim) {
      getConsole.insertAdjacentHTML("beforebegin", enemy.name + " killed " + player.name + " because your aim is " + enemy.aim + " and his enemie's is " + player.aim + "
");
      playerTeamOutput.splice(playerTeamIndex, 1)

    } else if (player.aim == enemy.aim && player.luck > enemy.luck) {
      getConsole.insertAdjacentHTML("beforebegin", player.name + " killed " + enemy.name + " with a lucky shot
");
      enemyTeamOutput.splice(enemyTeamIndex, 1)

    } else if (player.aim == enemy.aim && enemy.luck > player.luck) {
      getConsole.insertAdjacentHTML("beforebegin", battle2.name + " killed " + player.name + " with a lucky timing
");
      playerTeamOutput.splice(playerTeamIndex, 1)
    }
  }

  console.log(`Player Size: ${playerTeamOutput.length}`)
  console.log(`Enemy Size: ${enemyTeamOutput.length}`)

  // Immedietly recall the function to begin another battle
  return battle(playerTeamOutput, enemyTeamOutput)
}

Thanks for posting and let me know if you would like me to explain anything I did further!


text:
Q: Automatically add revision number to git in comments on github
Possible Duplicate:
Is it possible to add a version number using git / github

I host a git repository on github.
Is it possible to add the revision to the comments at the start of my script, so every time I commit a new version, this number is counted up?
Also the date of the last commit would be great, if it is shown in comments.


text:
Q: Does AWS charge for Fargate image pull from ECR in the same region? I have:

*

*Fargate container

*Private ECR repository

They're in the same account and region. Will AWS charge me for pulling images?
ECR pricing page says Data transferred between Amazon Elastic Container Registry and Amazon EC2 within a single region is free of charge (i.e., $0.00 per GB). Does it mean only EC2?

A: AWS container team member here. I have followed up with the ECR PM and they confirmed this is applicable to Fargate (and Lambda) in addition to EC2. I have asked the team to work on the documentation and update it to reflect this. Thanks for bringing this up.


text:
Q: Is the Geo URI uncertainty a radius or a diameter? Uncertainty is inherent in geospatial data... Maybe it's supposed to be obvious, and, some standards forget to define it.
The RFC 5870 — A Uniform Resource Identifier for Geographic Locations ('geo' URI) — has no clue about the uncertainty measurement definition:

The u ("uncertainty") parameter indicates the amount of uncertainty in the location as a value in meters.

The statistical/metrological uncertainty is a well-known measurement, and usually associated with a disk around the point, but the measurement could be defined as the radius or the diameter of the disk.

Note. If the RFC is really informal, perhaps any set of GIS "trusted books" (or scientific papers) could be used as evidence... It seems that radius is the most widely adopted.

A: That RFC refers to uncertainty in RFC5491, and a Wikipedia section on Uncertainty in Geo URIs assesses it to mean the radius of a Gaussian error model containing 95% of the total unit probability. https://en.wikipedia.org/wiki/Geo_URI_scheme#Uncertainty
I've not seen much adoption of the geo: URI so I am not surprised this hasn't really cropped up much.


text:
Q: Yet another "AJAX to update without blinking" question The code below is giving me the output I want, but the 'timing' is a little off.  I'm testing this in a local XAMPP instance; after the updateTotal function fires it IS updating output.txt, but the AJAX "refresh" is grabbing the old data I'm putting into it for testing. I can see it change from the "live data" to my junk data on the webpage, even as Notepad++ tells me output.txt has changed from junk data to live data.
What very little I know about AJAX is that it's a household cleaner and that it's used to refresh things without making it blink on-screen.  I think the if readyState and this.Status is there to make sure the HTML pull completes before updating the data, but I'm making two requests here -- one to call the .PHP file to update the text, and one to pull in the .txt file with the data I want you to see.
I'm just having a hard time understanding how to put the two things together. I'd put a readyState/thisStatus thing up with my PHP pull, but...I don't need it to DO anything there, other than run the PHP code, ya know?
Here's the code I've tried -- I haven't posted before so I'm not sure how it's going to combine the two sections of the form yet, so here goes lol


text:
Q: Store a set of numbers in Java I'm looking for a way to store a set of numbers in java
When I generate a new number, I have to look if that number exist in the set or not.
I used a Hashset declared like this:
HashSet<Integer> tempSet;
tempSet = new HashSet<Integer>();

but it's not working when I test like this:
int randomNumber = rand.nextInt(10);
while (tempSet.contains(randomNumber))
{
    randomNumber = rand.nextInt(10);
    System.out.println("randomNumber= " + randomNumber );
}

It mean that if an already number is generated and exist in the set, the test with the contains member function of the HashSet do not work
here is the complete code:
package ex1;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

public class Main {

    public static void main(String[] args) {

        //1- create 10 courses
           Course[] courseLists = new Course[10];

           for(int i=0; i<10; i++){
              //create
              Course course = new Course("course"+i, "courseId"+i, "", 60.0f, 0, 0.0f);
              courseLists[i]=course;
           }

         //2- create 7 professors
            Professor[] professorLists = new Professor[7];

            Random rand= new Random();

            int min=1;

            int max = 6;

            for(int i=0; i<7; i++){
                  //create
                  Professor professor = new Professor
                                    (
                                        "ProfessorFirstName"+i, "ProfessorLastName"+i,
                                        35, "MALE", "adress"+i, "professorId"+i
                                    );

                  courseLists[i].setAssignedProfessor("profId"+i);

                  professor.setCourseList(courseLists[i]);

                  professorLists[i] = professor;
           }

           rand= new Random();
           int randomNum1 = rand.nextInt((max - min) + 1) + min;
           int randomNum2 = rand.nextInt((max - min) + 1) + min;

           while ( randomNum2 == randomNum1 ) {
               randomNum2 = rand.nextInt((max - min) + 1) + min;
           }

           courseLists[8].setAssignedProfessor("profId"+randomNum1);
           professorLists[randomNum1].setCourseList(courseLists[8]);

           courseLists[9].setAssignedProfessor("profId"+randomNum2);
           professorLists[randomNum2].setCourseList(courseLists[9]);

           courseLists[7].setAssignedProfessor("profId"+1);
           professorLists[1].setCourseList(courseLists[7]);

          //3- create 30 students
           Student[] studentsLists = new Student[30];

           //--------------------
            boolean genderValue;

            //generate number of courses per student
            //randomNbrCourses: number of courses taken by the current student
            for(int i=0; i<30; i++){
                int minNbrCourses = 1;
                int maxNbrCourses = 6;
                int randomNbrCourses;
                rand= new Random();
                randomNbrCourses = rand.nextInt
                                  (
                                    (maxNbrCourses - minNbrCourses) + 1
                                  ) + minNbrCourses;

                //generate random age
                int minStudentAge=18;
                int maxStudentAge = 48;
                int randomAge = -1;
                rand= new Random();
                randomAge = rand.nextInt
                      (
                         (maxStudentAge - minStudentAge) + 1
                       ) + minStudentAge;

                //gender
                genderValue = Math.random() < 0.5;
                String gender;
                if (genderValue == false)
                    gender = "FEMALE";
                else
                    gender = "MALE";
                //****************************Here I have the HashSet *********//
                HashSet<Integer> tempSet;
                tempSet = new HashSet<Integer>();
                //****************************************************************//
                GradeBook gradeBook = new GradeBook();

                for ( int nbrCourse=0; nbrCourse<randomNbrCourses; nbrCourse++) {

                      Tuple tupleValue = new Tuple();

                      //generate one number , this number correspand to a course id...

                      //** Here I have to test if a new number exist in the set or not **//
                      int randomNumber = rand.nextInt(10);
                      while (tempSet.contains(randomNumber))
                      {
                          randomNumber = rand.nextInt(10);
                          System.out.println("randomNumber= " + randomNumber );
                      }
                      //*************************************************//

                      courseLists[randomNumber].setNbrEnrolledStudent(1);

                      float  minMark=0.0f;
                      float  maxMark=100.0f;
                      Random newRand= new Random();

                      //generate four random marks for the course....
                      float randomMark1 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
                      tupleValue.setMarkExam1(randomMark1);

                      float randomMark2 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
                      tupleValue.setMarkExam2(randomMark2);

                      float randomMark3 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
                      tupleValue.setMarkExam3(randomMark3);

                      float randomMark4 = newRand.nextFloat()*(100.0f-0.0f) + 0.0f;
                      tupleValue.setMarkExam4(randomMark4);

                      tupleValue.setFinalMark
                        (
                            (randomMark1+randomMark2+randomMark3+randomMark4)/4
                        );

                      tupleValue.setCourseName("course"+randomNumber);

                      tupleValue.setCourseId("courseId"+randomNumber);

                      gradeBook.setCourseLists(tupleValue);

                   }

                Student student = new Student
                                (
                                  "firstName_student"+i,"lastName_student"+i,
                                   randomAge, gender, "adress"+i, "idStudent"+i, gradeBook
                                  );
                studentsLists[i]=student;

                studentsLists[i].setNbrCourses(randomNbrCourses);
            }

            //we have to verify that there is no course with less than 3 student enrolled

           //print the list of courses
           getWholeCouces(courseLists, studentsLists);

           //print the professors and there assigned  courses
           getProfessorsAndAssignedCouces(professorLists);

           //print the list of all students and the courses enrolled in
           getStudentsWithEnrolledCourses(studentsLists);

    }
    /*
    static float getMinMarkCourse(){

    }

    static float getMaxMarkCourse(){

    }

    static float getGroupMarkCourse(){

    }*/

    //method to print the list of all students and the courses they are enrolled in
    static void getStudentsWithEnrolledCourses(Student[] student){
        System.out.println(" ");
        System.out.println("----------------------------------------------------------");
        System.out.println("list of all students and the courses they are enrolled in:");
        System.out.println("----------------------------------------------------------");
        for (int i=0; i<30;i++){
           System.out.print(student[i].getLastName());
           System.out.print("  "+student[i].getIdentificationNumber());

           GradeBook gb = student[i].getGradeBook();

           ArrayList<Tuple> tuple = gb.getCourseLists();

           for (int L=0; L< tuple.size(); L++)
           {
               System.out.println(" ");
               System.out.print("   "+tuple.get(L).getCourseId());
               System.out.print("  "+tuple.get(L).getFinalMark());
           }
           System.out.println(" ");
           System.out.println(" ");
        }

    }

    //method to get the professors and there assigned  courses
    static void getProfessorsAndAssignedCouces(Professor[] professor){
        System.out.println(" ");
        System.out.println("---------------------------------------");
        System.out.println("professors and there assigned  courses:");
        System.out.println("---------------------------------------");
        for(int i=0; i<7; i++){
              System.out.println("  ");
              System.out.print(professor[i].getFirstName());

              System.out.print("  "+professor[i].getIdentificationNumber());
              System.out.println(" ");

              System.out.println(" ");
              List<Course> courseList = professor[i].getCourseList();

              for (int k=0; k < courseList.size(); k++){
                  System.out.print("    "+courseList.get(k).getCourseId());
                  System.out.print("  "+courseList.get(k).getNbrEnrolledStudent());
                  System.out.print("  "+courseList.get(k).getAverageCourseMark());
                  System.out.println(" ");
              }
              System.out.println(" ");
         }
    }

    //method to get the list of all courses
    static void getWholeCouces(Course[] courseList,Student[] studentsList){
        System.out.println("----------------");
        System.out.println("list of courses:");
        System.out.println("----------------");
        // maxMark = max mark of the course
        // minMark = minimum mark of the course
        float maxMark = Float.MIN_VALUE;
        float minMark = Float.MAX_VALUE;

        float allMarks = 0.0f;
        float nbOfEnrolledStudent=0.0f;

        for(int i=0; i<10; i++){
              //create
              String courseName = courseList[i].getCourseName();

              //look for enrolled student
              for(int nbStudent=0; nbStudent<30; nbStudent++){
                  ArrayList<Tuple> temp =
                    studentsList[nbStudent].getGradeBook().getCourseLists();
                  for (int j=0;j< temp.size();j++){
                      if (temp.get(j).getCourseName().equals(courseName)){
                          if (temp.get(j).getFinalMark() > maxMark )
                              maxMark = temp.get(j).getFinalMark();

                          if (temp.get(j).getFinalMark() < minMark )
                              minMark = temp.get(j).getFinalMark();

                          allMarks += temp.get(j).getFinalMark();
                          nbOfEnrolledStudent+=1;
                      }
                  }
              }

              courseList[i].setAverageCourseMark((allMarks)/nbOfEnrolledStudent);

              System.out.print(courseName);
              System.out.print("  "+courseList[i].getCourseId());
              System.out.print("  "+courseList[i].getAssignedProfessor());
              System.out.print("  "+courseList[i].getNbrEnrolledStudent());
              System.out.print("  "+minMark);
              System.out.print("  "+maxMark);
              System.out.print("  "+(allMarks)/nbOfEnrolledStudent);
              System.out.println("  ");
        }
    }
}

A: You are not adding any numbers to the HashSet, so of course contains always returns false.
int randomNumber = rand.nextInt(10);
while (tempSet.contains(randomNumber))
{
    randomNumber = rand.nextInt(10);
    System.out.println("randomNumber= " + randomNumber );
}
tempSet.add(randomNumber); // add this

A: There is no need to use contains method here. add() method of set returns boolean if the element is already present inside it.
So, we can just do this:
if(!tempSet.add(randomNumber)){
//do something as the number is already present
}

This will save us from writing an else block as the element has already been added in if block.

A: Take advantage of the Collections (set)...
doing mySet.add returns false if the insertion fails, and sets dont allow duplicates...
A snippet as Example:
 Set<Integer> mySet = new HashSet<Integer>();
            for (int i = 0; i < 12; i++) {
                System.out.println(mySet.add(new Random().nextInt(4)));
            }
            System.out.println(mySet);

the output to this can be:
true
true
false
false
true
false
true
false
false
false
false
false
[0, 1, 2, 3]


text:
Q: Application design distorts In my Iphone application, when application running stage in  between skype call comes, the call details will show in status bar and status bar height automatically increase and my application design distorts
How can i solve this issue?
if skype call is not happening everything is perfect..


text:
Q: unable to parse specific value from a particular column of a csv file I am making a predictive model to predict revenue and trying to parse this 'cast' value from the data frame as it is not a list or a dict
x['cast']

And the output is
0    [{'cast_id': 4, 'character': 'Lou', 'credit_id...
1    [{'cast_id': 1, 'character': 'Mia Thermopolis'...
2    [{'cast_id': 5, 'character': 'Andrew Neimann',...
3    [{'cast_id': 1, 'character': 'Vidya Bagchi', '...
4    [{'cast_id': 3, 'character': 'Chun-soo', 'cred...
5    [{'cast_id': 6, 'character': 'Pinocchio (voice...
6    [{'cast_id': 23, 'character': 'Clyde', 'credit...
7    [{'cast_id': 2, 'character': 'Himself', 'credi...
8    [{'cast_id': 1, 'character': 'Long John Silver...
9    [{'cast_id': 24, 'character': 'Jonathan Steinb...
Name: cast, dtype: object

I need all the 'character' values in a list.
but when I try
x['cast'][0]['character']

It throws this error
TypeError: string indices must be integers

Help me out with this please.

A: First convert json to list of dictionaries and then get values from first list by key of dict:
import ast

mask = x['cast'].notna()

x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(ast.literal_eval)
#alternative
#x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(pd.io.json.loads)
x.loc[mask, 'cast'] = x.loc[mask, 'cast'].apply(lambda x: x[0].get('character', 'not match data'))

EDIT:
If still problem use Series.str.extract:
x = pd.DataFrame({'cast':[[{'cast_id': 4, 'character': 'Lou'}], np.nan]})

x['cat'] = x['cast'].astype(str).str.extract("'character': '([^'']+)'")
print (x)
                                   cast  cat
0  [{'cast_id': 4, 'character': 'Lou'}]  Lou
1                                   NaN  NaN


text:
Q: Stripe Webhook events Renewal of subscription I am using STRIPE for credit card payments in my Asp.net Application. Application have an monthly subscription plan. First time when user subscribe the webhook event 'customer.subscription.created' fired. my question is what happened which events will be fired when next month subscription is renewed ? Can anyone tell me the flow on subscription renewal webhook events?
Thanks

A: As well as customer.subscription.created you will also receive a invoice.created followed by invoice.payment_succeeded (or invoice.payment_failed)
From the documentation:

If you are using webhooks, Stripe will wait one hour after they have all succeeded to attempt to pay the invoice; the only exception here is on the first invoice, which gets created and paid immediately when you subscribe a customer to a plan.

So, this means, invoice.created event will also fire next month.
Stripe will then wait an hour before charging the customers card, then firing charge.succeeded  (if the charge is succeeded) or charge.failed (if the charge fails)
The hour wait is to allow invoice items to be added to the invoice if you so wish.
See my answer on this question for more information on why you might need to do that...

A: You would want to watch for a invoice.payment_succeeded event:
Have a look at: https://stripe.com/docs/api#event_types
This event is triggered any time an invoice is paid. A charge.succeeded event also occurs, but the difference is that invoice.payment_succeeded only occurs for payments on invoices, whereas charge.succeeded also occurs for standalone charges.
There is no event distinction between the first charge on a subscription and a recurring one, although the logic you store on your end (e.g., when the subscription was created, when it
expires, etc.) should help you disambiguate them.

A: The webhook 'invoice.payment_succeeded' actually does distinguish between the first charge of a new subscription and subsequent renewal charges.
The webhook sends an invoice object, which includes 'billing_reason' - the possible values of which are noted in the Stripe Docs - The Invoice object:
billing_reason
(string)
"Indicates the reason why the invoice was created.
subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_create indicates an invoice created due to creating a subscription. subscription_update indicates an invoice created due to updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint."
If billing_reason == 'subscription_cycle' the webhook is for a subscription
renewal.
If billing_reason == 'subscription_create' the webhook is for a brand new subscription.

A: Renewing Subscriptions:
When a customer's subscription is renewed in Stripe a number of things happen, each with a corresponding event:

*

*An invoice is created - invoice.created

*The subscription billing period is updated - customer.subscription.updated

*After an hour (giving you time to add any additional charges) Stripe attempts to charge the customer.

*Given payment is successful an invoice.payment_succeeded event is raised.

The way to handle these events within your own application is to register a webhook; a HTTP endpoint that Stripe will send details of the event to.

*

*Find the customer subscription using the Stripe identifier (included in the event payload).

*Retrieve the subscription details from the Stripe API.

*Update our subscription's CurrentPeriodStart and CurrentPeriodEnd with the Stripe subscription's period_start and period_end.

*Create a customer invoice using the details from the Stripe event.


text:
Q: Identifying sentence constituents In the following sentence I was asked to identify the sentence constituents: subject, verb, objects, complement and adverbial/adverb.
I really love dogs, but my wife loves cats.
I=subject, love=verb, dogs=object, really=adverb, my wife=subject, loves=verb and cats=object.
My question is: what is the function of the conjunction but in terms of the constituents listed above. My teacher says it acts as an adverb , but how?

A: Your teacher is wrong. In this sentence "but" a (coordinating) conjunction, not an adverb.
It's possible that your teacher is confused by the fact that "but" is sometimes an adverb, such as in the sentence

I have but one chance to get this right.

If we look at the Oxford English Dictionary we see both of these uses listed separately, as well as the note that "but" can be a preposition.
The OED defines "adverb" by saying that

An adverb is a word that's used to give information about a verb, adjective, or other adverb.

The only words that "but" could be modifying in your sentence are "really", "love", and "loves." It doesn't modify "really," because it in no way qualifies the extent to which you love dogs. But it also doesn't make sense to say that it modifies either "love" or "loves". It contrasts those two phrases, but doesn't give any information about how much you love dogs or how much your wife loves cats.
To try to understand your teacher's POV, maybe ask them what the role of the word "and" in the sentence "I love ice cream and my sister does too" is. Do they also think that that's an adverb? This might be a good starting point for a conversation with the teacher about the error.


text:
Q: Making program work on 32 bit Window OS I have written a program in Java on a 64 bit Window OS, but now I need my program to work on a 32 bit Window OS. How can I do this? (For making an exe file I used launch4j)

A: For Java, if the machine has the Java 32-bit is installed, then running the exe alone will be enough. If you want to provide redistributable, just use the java 32-bit redistributable.


text:
Q: How to convert webm video file to 3gp? Is any way to convert webm video file into 3gp using any Ubuntu package. My file size is above 55 mb so not supported by online conversion?

A: This can be done with ffmpeg
good to know:
The 3GP file format stores video streams as H.263 or H.264 codecs and various audio streams format are allowed.

Important limitation of this format is the resolution of the H.263 video stream. As 3GP format was developed to work on 3G mobile phones, it can work only with sizes of 128x96, 176x144, 352x288, 704x576 or 1408x1152 pixels.
Native valid 3GP format
ffmpeg -i inputVideo.avi \
  -f 3gp -vcodec h263 -vf scale=352x288 \
  -acodec amr_nb -ar 8000 -ac 1 \
outputVideo.3gp

-f 3gp : Output file format is 3GP.
-vcodec h263 : Output file will use H.263 codec for video stream.
-acodec amr_nb : Output file will use AMR_NB codec for audio stream.
-vf scale=352x288 : Resize the image to a supported resolution
-acodec amr_nb : Specifies output audio codec
-ar 8000 : Convert audio streams into 8000Hz audio streams. This is required by the AMR_NB encoder.
-ac 1 : Transform audio from stereo into mono. This is also required by the AMR_NB encoder.

Complicated?Yes, it is... With luck, 3GP has been extended to support H264 : no more image size limitation and a bunch of audio codecs supported.
Using H.264 video codec and AAC audio codec
ffmpeg -i inputVideo.avi -f 3gp -vcodec libx264 -acodec aac outputVideo.3gp

-f 3gp : output file will be using 3GP format.
-vcodec libx264 : use libx264 encoder to produce H.264 encoded streams.
-acodec aac : audio stream will be encoded using AAC encoder.


text:
Q: For each LOOP through JSON.Stringify EXIF data of an image I have a image where once i click on it it is displayed bigger with EXIF data next to it .
I am taking the EXIF data with JSON.strigify and after that i need to display whatever it is in that string to be added to the  tag with id='makeAndModel' in my HTML.
I want to do it with for each arrow function , but i am not sure how exactly .
   `

        ×

Make and model:

`

   <--Taking the src attribute and creating the images-->
    let $modal = $('.modal')
    let $img = $("#imageContainer img");
      $img.click(function(){
        $('.modal-content').attr('src', $(this).attr('src'));
        $modal.css('display', 'block')

      <--EXIF data-->
       var imgCurrent = document.getElementById('current');
       EXIF.getData(imgCurrent,function(){
         let result = $('#makeAndModel')
         let make= JSON.stringify(EXIF.getAllTags(this));

    });

    let $makeAndModel = $('#makeAndModel');
    $makeAndModel.text(`${make}`)
  })

`
currently in the console the output of let make is object
let make = {
    "Orientation":1,
    "YCbCrPositioning":1,
    "XResolution":72,
    "YResolution":72,
    "ResolutionUnit":2,
    "Make":"samsung",
    "Model":"SM-G965F",
    "Software":"G965FXXU2CSB9",
    "DateTime":"2019:03:18 18:29:28",
    "ExifIFDPointer":213,
    "GPSInfoIFDPointer":833,
    "ExposureTime":0.02,
    "FNumber":2.4,
    "ExposureProgram":"Normal program"
    ,"ISOSpeedRatings":160,
    "ExifVersion":"0220",
    "DateTimeOriginal":"2019:03:18 18:29:28",
    "DateTimeDigitized":"2019:03:18 18:29:28",
}
Expected output should look like
Make and Model :
Orientation:1,
YCbCrPositioning:1,
XResolution:72,
YResolution:72,
and so on  like when you click in the Properties->Details tab of an image

A: Something like this could work
let $modal = $('.modal')
let $img = $("#imageContainer img");
$img.click(function() {
  $('.modal-content').attr('src', $(this).attr('src'));
  $modal.css('display', 'block')
  var imgCurrent = document.getElementById('current');
  EXIF.getData(imgCurrent, function() {
    let result = $('#makeAndModel')
    let make = EXIF.getAllTags(this);
    let props = Object.entries(make).map(([property, value]) => {
      return `${property}: ${value}`;
    });
    result.text(props.join('\n'));
  });
})


text:
Q: I want to give radius to shadow shown inside a layout in android I want to give shadow inside a cardview and got solution like shown below :

but I also want to give radius to shadow as well which I'm not able to do,
Here's my code for the same :
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/yellow"/>
            <corners android:radius="@dimen/_20sdp"/>
        </shape>

    </item>
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:angle="180"
                android:centerColor="#00FF0000"
                android:centerX="0.97"
                android:centerY="0.5"
                android:endColor="#5C000000"
                android:startColor="#00FF0000" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:angle="270"
                android:centerColor="#00FF0000"
                android:centerY="0.1"
                android:endColor="#00FF0000"
                android:startColor="#6B000000" />
            <corners android:radius="@dimen/_20sdp" />
        </shape>
    </item>
</layer-list>

Can anyone help me with this?
Thanks in advance.

A: Take transfers image like a shadow you want the top layout.
or
create gradient drawable.
Try something like below
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:centerColor="#555994"
        android:endColor="#b5b6d2"
        android:startColor="#555994"
        android:type="linear" />

    <corners
        android:radius="0dp"/>

</shape>


text:
Q: ip route del does not delete entire table I have recently started using ip route commands for advanced routing stuff. Now I have come across something rather puzzling to me. A default route added to a table will be easily deleted whereas another route remains.
I add these two rules:
ip route add dev wlan0 default via 192.168.0.1 table 21
ip route add dev wlan0 192.168.0.0/24 table 21

Now if I do:
ip route show table 21

I see both of these rules present.
default via 192.168.0.1 dev wlan0
192.168.0.0/24 dev wlan0  scope link

If I then try to delete table 21, and show it again:
ip route del table 21
ip route show table 21

There is still that rule remaining.
192.168.0.0/24 dev wlan0  scope link

Can anyone explain this? The man page says that del is designed to delete a ROUTE, which also includes tables.

A: Maybe try:
ip route flush table 21

A: As @user3291010 has already pointed out, to delete a full table, use the following command:
This command deletes table 21:
ip route flush table 21

The command you tried is used to remove specific rules from a table. It wants a prefix to match on. When you didn't supply the prefix, it just deleted the first entry, which happened to be the default route.
To remove the second entry, and only the second entry, you could run this command:
ip route delete table 21 192.168.0.0/24

As far as I know, there is no way to delete all entries using the delete command.


text:
Q: Script to ssh and run a command doesn't work Below is the script.
I wanted to login several servers and check for the kernel version.
#!/bin/bash
#input server names line by line in server.txt
cat server.txt | while read line
do
sshpass -p password ssh root@$line << EOF
hostname
uname -r
EOF
done

I would expect output which goes like..
server1_hostname
kernel_version
server2_hostname
kernel_version

and so on..
I ran this script with about 80 servers in server.txt
And the output i got was like.....
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.

========================================================================
================================ WARNING ===============================
========================================================================
This system is solely for the use of authorized personnel. Individuals
using this system are subject to having some or all of their activities
monitored and recorded. Anyone using this system expressly consents to
such monitoring and is advised that any unauthorized or improper use of
this system may result in disciplinary action up to and including
termination of employment. Violators may also be subject to civil and/or
criminal penalties.
========================================================================

Warning: no access to tty (Bad file descriptor).
Thus no job control in this shell.
xxxxdev01
2.6.32-431.23.3.el6.x86_64
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.
Pseudo-terminal will not be allocated because stdin is not a terminal.

Here I got output for only 1 host, which is xxxxdev01 and that too comes with the ssh banner and other warning.
I need output of all other hosts and without ssh banner.. What is going wrong here?

A: Use the following code,
#!/bin/bash
#input server names line by line in server.txt
cat server.txt | while read line
do
  sshpass -p password ssh root@$line 'hostname;uname -r'
done

A: I can't tell you why you're not getting the expected output from the hostname and uname commands, but I can help with the extraneous text.
The "Pseudo-terminal" lines are being printed by ssh because it tries to allocate a TTY by default when no command to be executed was provided on the command line. You can avoid that message by adding "-T" to the ssh command:
sshpass -p password ssh -T root@$line

The "Warning: no access to tty" line is coming from the shell on the remote system. csh and tcsh will print that message under certain circumstances. It's possible that it's triggered by something in the .cshrc or similar file on the remote system, trying to access some feature which requires a TTY.

A: If your hosts are stored as follow in server.txt
host1.tld
host2.tld
....

You can
mapfile -t myhosts < server.txt; for host in "${myhosts[@]}"; do ssh username@"$host" 'hostname;uname -r'; done

A: The stdin is not accessible to your remote commands. What you can do is use "-s" flag of bash to read commands from the stdin:
From bash manual:
-s        If the -s option is present, or if no arguments remain after
          option processing, then commands are read from the standard
          input.  This option allows the positional parameters to be set
          when  invoking  an  interactive shell.

So this should do what you want:
#!/bin/bash
#input server names line by line in server.txt
cat server.txt | while read line
do
    sshpass -p password ssh root@$line bash -s << EOF
hostname
uname -r
EOF
done

See also:  https://stackoverflow.com/questions/305035/how-to-use-ssh-to-run-shell-script-on-a-remote-machine

A: This works great for me:
 # cat hostsname.txt
operation01  172.20.68.37 5fDviDEwew
ngx-gw01     172.20.68.36 FiPp2UpRyu
gateway01    172.20.68.35 KeMbe57zzb
vehicle01    172.20.68.34 FElJ3ArM0m

# cat hostsname.txt | while read hostname ipaddr passwd; do sshpass -p $passwd /usr/bin/ssh-copy-id $ipaddr;done

note that use -t -t instead of -T to avoid the error

Pseudo-terminal will not be allocated because stdin is not a terminal

A: I guess the ssh in the while eat up the rest to stdin. you may refer the Bash FAQ 89 for details. With a FileDescriptor, following codes should work as your expectation.
while read line <& 7
do
sshpass -p password ssh root@$line << EOF
hostname
uname -r
EOF
done 7< server.txt


text:
Q: SQLite won't throw error when inserting non-existing foreign key value I have a litte problem with my SQLite database, especially with the following tables:
CREATE TABLE foo (
  key INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);

CREATE TABLE bar (
  _id INTEGER PRIMARY KEY,
  key INTEGER NOT NULL,
  what TEXT NOT NULL,
  else TEXT,
  FOREIGN KEY (key) REFERENCES foo (key) DEFERRABLE INITIALLY DEFERRED
);

If I understand the SQLite documentation the right way, attempting to insert a row into bar that does not correspond to any row in the foo table should fail and thow an error or something.
Unfortunately the following command works, even if no key 42 existis in foo:
INSERT INTO bar (key, what, else) VALUES (42, "something", "else");

This will create a row in bar with the given values (key = 42), while there exists no row in foo with the key 42.
Is it me or what is wrong here?

A: As posted by @kijin on Does SQLite3 not support foreign key constraints?

In SQLite 3.x, you have to make the following query every time you connect to an SQLite database:
PRAGMA foreign_keys = ON;

Otherwise SQLite will ignore all foreign key constraints.
Why every time? Backwards compatibility with SQLite 2.x, according to the documentation.
In SQLite 4.x, FK constraints will be enabled by default.


text:
Q: loop through checkboxes by classname in jquery I need to loop through the all checkboxs to set the button disable or not. If one of the checkbox is checked, then the button is enable. However it looks like my code didn't loop through the checkbox. The alert inside the each function doesn't shown.I found the looping method on
How to loop through group of check boxes that have same class name?
There is my code:
function setButton() {

                alert('line 24');
                var blnDisable = true;

                //https://stackoverflow.com/questions/35506843/how-to-loop-through-group-of-check-boxes-that-have-same-class-name
                $('.chkItem').each(function (index, obj) {
                    if (obj.checked == true) {
                        alert('line 30');
                        blnDisable = false;
                    }

                });
                alert('disable=' + blnDisable);
                    $("#btnDownload").attr("disabled", blnDisable);

            }

A: This will make it check to see if any of the check boxes are checked.  If so, it will enable the check box, if not it will disable it.  Lastly, I assigned it to a function so it can be run on page load.  This is important so it will automatically check to see whether the download button should be enabled on page laod.
<input type="checkbox" class="chkItem" />one

<input type="checkbox" class="chkItem" />two

<input type="checkbox" class="chkItem" />three

<button id="btnDownload">download</button>


text:
Q: How to set the color of bars in bar chart based on certain condition in google sheet?
Hi everyone,
Is there any way to use another color for the bars where the count is more than Average count (cell E3)? Any help will be greatly appreciated!
Google sheet link:
https://docs.google.com/spreadsheets/d/1SO36KvggYE6NgGAbvpbbB0qrhRLfBWMivRSUuOs6hNM/edit#gid=0

A: You do it through a trick by splitting column C into two columns depending on the codition
E.g.

*

*Type into F3 =Arrayformula(IF(C3:C190>E3,C3:C190,"")) and into G3 =Arrayformula(IF(C3:C190<=E3,C3:C190,"")):

*Modify your graph by replacing the series C2:C190 by the two series E2:E190 and CF:F190:


text:
Q: Array's value is changed for no ostensible reason I'm trying to embed a very basic AI in a game of Tic Tac Toe and I'm running into a problem with the arrays that I use to discern the most suitable square to claim.
I have one array that represents the game grid in its current state and another that represents the way it would look if a certain square were claimed.
The AI kept making weird decisions, so I decided to have it report various information at certain milestones.
string[,] currentGrid;
string[,] hypotheticalGrid;

MessageBox.Show(currentGrid);

hypotheticalGrid = currentGrid;
hypotheticalGrid[x, y] = "O";

MessageBox.Show(currentGrid);

Bear in mind that the above is a very simplified version of the actual code.

The arrays are assigned values along the line and the message boxes are set to display currentGrid as a sequence of its contained values.
Everything works properly except the code between the message boxes.
The problem is that the two message boxes display different results even though the latter is a copy of the former and no changes to currentGrid are specified in the space between the two.
The two lines in between are copied directly from the source code and should only affect the hypothetical grid. As should be obvious, these lines are supposed to reset the hypothetical grid and then add an "O" to the square in question.
However, the "O" also gets placed in the current grid for some reason.
What am I doing wrong?

A: The line hypotheticalGrid = currentGrid; does not make a copy of currentGrid, instead both variables point to the same array. So any change made in hypotheticalGrid will be seen in currentGrid too.
You should have hypotheticalGrid be a copy of currentGrid:
hypotheticalGrid = (string[,])currentGrid.Clone();

In this case, Clone() will work, because strings are immutable in .NET. In other cases, Clone might not be good enough, just something to be aware of.

A: The problem is that your assignment:
hypotheticalGrid = currentGrid;

is merely a reference assignment, meaning that now they both point to the same array in memory, so any changes to the hypothetical grid will affect the current grid as well.
You'd need a full item copy in order for them to not interfere with each other.

A: Keep in mind, that arrays are reference types. Your assignment copies the reference but does not create a duplicate of the array. After the assignment both array variables point to the same array!
You can create an array duplicate like this:
string[] hypotheticalGrid = new string[currentGrid.Length];
Array.Copy(currentGrid, hypotheticalGrid, currentGrid.Length);

Note that this does not create a duplicate of the items contained in the array, but this is not a problem, since strings are immutable. I.e. if you manipulate a string in one of the arrays, this creates a new string and therefore has no effect on the second array.

EDIT:
By looking at the other posts I see that it can be done easier with the Clone method:
string[] hypotheticalGrid = currentGrid.Clone();


text:
Q: Can I pass props to a child component and use the data in the parent component in Vue I would like to pass data to a child component and render that same data in the parent components. Also I would like to use the data in a function and not simply render it in the child. When I pass the props in this example it no longer renders the  tags with the data
 <template>

{{section.name}}

{{section.type}}

</template>

A: You can't use the same word/property name (sections in your case) for data and props.

A: I assume your code is the parent component:
// parent.vue
<template>

{{section.name}}

{{section.type}}

    <my-child-component :sections="sections" />

</template>

// MyChildComponent.vue
<template>

{{section.name}}

{{section.type}}

</template>

Take a look in the vue guide about component: https://v2.vuejs.org/v2/guide/components.html


text:
Q: Matching between comment lines I'm trying to match
Some HTML content
Using preg_match
\<\!\-\- FOR (\d+) \-\-\>(.*)\<\!\-\- END FOR \-\-\>

Doesn't work since they are on different lines.

A: First you need to learn that < ! - > are not special characters. Escaping them with backslashes makes you look a bit silly.
Then learn about the /x and /s flags. One of them is what you need. The other is me trying to trick you into learning something unrelated.
Then test your regular expression with some HTML content that contains two or more of those FOR/END FORs and see what happens.
Also, you need to look into how to make your capturing conditions "greedy" or "non greedy". By default, matches will be greedy. So a condition such as "A(.)B" with the string "A1B A2B A3B" would find one match "1B A2B A3" - everything form the first "A" to the last "B". If you wanted to find all the values between each set of A/B, then you need make the match non-greedy - "A(.?)B"


text: Q: Axioms of Newtonian Mechanics Axiomatically speaking, could Newton's laws be derived (as theorems) from the conservation of momentum and energy -- along with a few suitable definitions of things like an inertia frame and force?  Is there a book which takes this axiomatic viewpoint?


text:
Q: Replace @Value property within @Configuration during Spring Boot test Scenario
I've got a Spring Boot application with a @Configuration annotated Spring configuration class which contains some @Value annotated fields. For testing I want to replace these field values with custom test values.
Unfortunately these test values cannot be overridden using a simple properties file, (String) constants or similar, instead I must use some custom written property resolving Java class (e.g. TargetProperties.getProperty("some.username")).
The problem I have is that when I add a custom PropertySource to the ConfigurableEnvironment within my test configuration, it's already too late because this PropertySource will be added after the e.g. RestTemplate has been created.
Question
How can I override @Value annotated fields within a @Configuration class with properties obtained programmatically via custom Java code before anything else gets initialized?
Code
Production Configuration Class
@Configuration
public class SomeConfiguration {

    @Value("${some.username}")
    private String someUsername;

    @Value("${some.password}")
    private String somePassword;

    @Bean
    public RestTemplate someRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.getInterceptors().add(
            new BasicAuthorizationInterceptor(someUsername, somePassword));

        return restTemplate;
    }

}

Test Configuration Class
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {

    @SpringBootConfiguration
    @Import({MySpringBootApp.class, SomeConfiguration.class})
    static class TestConfiguration {

        @Autowired
        private ConfigurableEnvironment configurableEnvironment;

        // This doesn't work:

        @Bean
        @Lazy(false)
        // I also tried a @PostConstruct method
        public TargetPropertiesPropertySource targetPropertiesPropertySource() {
            TargetPropertiesPropertySource customPropertySource =
                new TargetPropertiesPropertySource();
            configurableEnvironment.getPropertySources().addFirst(customPropertySource);
            return customPropertySource;
        }
    }
}

A: You can use constructor injection in production cases, which allows it to set the configuration manually:
@Configuration
public class SomeConfiguration {

    private final String someUsername;
    private final String somePassword;

    @Autowired
    public SomeConfiguration(@Value("${some.username}") String someUsername,
       @Value("${some.password}") String somePassword) {
       this.someUsername = someUsername;
       this.somePassword = somePassword;
    }
...
)
}

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {

    private SomeConfiguration config;

    @Before
    public init() {
      config = new SomeConfiguration("foo", "bar");
    }
}

A: You can override properties directly in the @SpringBootTest annotation using the properties parameter:
@SpringBootTest(properties = {"some.username=user", "some.password=pwd"},
                webEnvironment = SpringBootTest.WebEnvironment.NONE)

A: You can use @TestPropertySource
@TestPropertySource(
    properties = {
        "some.username=validate",
        "some.password=false"
    }
)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
    //...
}


text:
Q: How to pass variable of type "Type" to generic parameter I'm trying to do this:
Type type = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil.GetColumnasGrid<type>();

but it's not working, do you have any idea how I could do this?

A: If it is an instance method instead of a static method, then you pass the variable to Invoke(the second parameter null is for an array of parameters that you would usually pass to the method, in the case of null is like calling a method with no parameters .GetColumnAsGrid()):
Type genericTypeParameter = Type.GetType(string.Format("Gestor.Data.Entities.{0}, Gestor.Data", e.Item.Value));
MetaDataUtil someInstance = new MetaDataUtil();

var returnResult =
    typeof(MetaDataUtil)
    .GetMethod("GetColumnsAsGrid")
    .MakeGenericMethod(new [] { genericTypeParameter })
    .Invoke(someInstance, null);//passing someInstance here because we want to call someInstance.GetColumnsAsGrid<...>()

If you have ambiguous overload exception it's probably because GetMethod found more than one method with that name.  In which case you can instead use GetMethods and use criteria to filter down to the method you want.  This can be kind of fragile though because someone might add another method similar enough to your criteria that it then breaks your code when it returns multiple methods:
var returnResult =
    typeof(MetaDataUtil)
    .GetMethods().Single( m=> m.Name == "GetColumnsAsGrid" && m.IsGenericMethod
        && m.GetParameters().Count() == 0 //the overload that takes 0 parameters i.e. SomeMethod()
        && m.GetGenericArguments().Count() == 1 //the overload like SomeMethod<OnlyOneGenericParam>()
    )
    .MakeGenericMethod(new [] { genericTypeParameter })
    .Invoke(someInstance, null);

This isn't perfect because you could still have some ambiguity.  I'm only checking the count and you'd really need to iterate through the GetParameters and GetGenericArguments and check each one to make sure it matches the signature that you want.

A: You need to use reflection for this.
var method =
    typeof(MetaDataUtil)
    .GetMethod("GetColumnasGrid")
    .MakeGenericMethod(new [] { type })
    .Invoke(null, null);


text:
Q: Serving Python (Flask) REST API over HTTP2 I have a Python REST service and I want to serve it using HTTP2. My current server setup is nginx -> Gunicorn. In other words, nginx (port 443 and 80 that redirects to port 443) is running as a reverse proxy and forwards requests to Gunicorn (port 8000, no SSL). nginx is running in HTTP2 mode and I can verify that by using chrome and inspecting the 'protocol' column after sending a simple GET to the server. However, Gunicorn reports that the requests it receives are HTTP1.0. Also, I coulnt't find it in this list:
https://github.com/http2/http2-spec/wiki/Implementations
So, my questions are:

*

*Is it possible to serve a Python (Flask) application with HTTP2? If yes, which servers support it?

*In my case (one reverse proxy server and one serving the actual API), which server has to support HTTP2?

The reason I want to use HTTP2 is because in some cases I need to perform thousands of requests all together and I was interested to see if the multiplexed requests feature of HTTP2 can speed things up. With HTTP1.0 and Python Requests as the client, each request takes ~80ms which is unacceptable. The other solution would be to just bulk/batch my REST resources and send multiple with a single requests. Yes, this idea sounds just fine, but I am really interested to see if HTTP2 could speed things up.
Finally, I should mention that for the client side I use Python Requests with the Hyper http2 adapter.

A:
Is it possible to serve a Python (Flask) application with HTTP/2?

Yes, by the information you provide, you are doing it just fine.

In my case (one reverse proxy server and one serving the actual API), which server has to support HTTP2?

Now I'm going to tread on thin ice and give opinions.
The way HTTP/2 has been deployed so far is by having an edge server that talks HTTP/2 (like ShimmerCat or NginX). That server  terminates TLS and HTTP/2, and from there on uses HTTP/1, HTTP/1.1 or FastCGI to talk to the inner application.
Can, at least theoretically, an edge server talk HTTP/2 to web application? Yes, but HTTP/2 is complex and for inner applications, it doesn't pay off very well.
That's because most web application frameworks are built for handling requests for content, and that's done well enough with HTTP/1 or FastCGI. Although there are exceptions, web applications have little use for the subtleties of HTTP/2: multiplexing, prioritization, all the myriad of security precautions, and so on.
The resulting separation of concerns is in my opinion a good thing.

Your 80 ms response time may have little to do with the HTTP protocol you are using, but if those 80 ms are mostly spent waiting for input/output, then of course running things in parallel is a good thing.
Gunicorn will use a thread or a process to handle each request (unless you have gone the extra-mile to configure the greenlets backend), so consider if letting Gunicorn  spawn thousands of tasks is viable in your case.
If the content of your requests allow it, maybe you can create temporary files and serve them with an HTTP/2 edge server.

A: It is now possible to serve HTTP/2 directly from a Python app, for example using Twisted. You asked specifically about a Flask app though, in which case I'd (with bias) recommend Quart which is the Flask API reimplemented on top of asyncio (with HTTP/2 support).
Your actual issue,

With HTTP1.0 and Python Requests as the client, each request takes ~80ms

suggests to me that the problem you may be experiencing is that each request opens a new connection. This could be alleviated via the use of a connection pool without requiring HTTP/2.