Q: Mimic HTML5 form validation default styling I have a simple HTML5 form with required fileds. When the page loads the fields have no styling. When I click on the required field, type something and then erase the text I just typed and exit the field, it shows me pink box-shadow outside the invalid field in Firefox.
Now I need yellow box-shadow, while retaining the same behavior. That's how I did:
In HTML
<input name="email_address" id="email_address_uuid_479823574" type="email"
       placeholder="ex. example@domain.com" title="Email address" required />

       -------
       -------

<input name="model_number" id="model_number_uuid_479823574" type="text"
       placeholder="ex. oxpd-983s" title="Equipment model number" required />

In CSS
input:required:invalid {box-shadow: 1px 2px 9px yellow};

Result: The page loads with all the fields with yellow box-shadow! Rather wait for user to make the mistake onblur and onsubmit like the default behavior.
How to override the default box-shadow of invalid field without changing the behavior?

A: Try:
input:required:-moz-ui-invalid {box-shadow: 1px 2px 9px yellow};

See https://developer.mozilla.org/en/CSS/:invalid


Q: Laravel Model Restore Event So I have 2 Models Users & Staff. They have one to one relationship with one another.
User.php 'hasOne' Staff
AND
Staff.php 'belongsTo' User
When I Soft Delete a User I want to soft delete Staff entry as well, I have achieved this using(Works Perfectly):
static::deleting(function ($user) {
    $user->staff()->delete();
});

Now I want to restore the staff when I restore the User for that I have tried using this(Not working):
static::restoring(function ($user) {
    $user->staff()->restore();
});

But this is not working. The User Entry is deleted but the Staff entry still remains soft deleted.

*

*Can someone help me understand what I am doing wrong here?

*Also, Is this the best way to get this done? Or is there some other way this should be done?
PS: I'm using Laravel 5.5

A: It isn't working because $user->staff() doesn't fetch deleted staff. That's how relationships work by default.
Just replace it with this:
static::restoring(function ($user) {
    $user->staff()->withTrashed()->restore();
});

A: "static::restoring" event is never triggered when restoring a batch of models.
If you're doing something like:
Yourmodel::whereIn('id', [1,2,3])->restore();

It will restore your models but "static::restoring or restored" will never be triggered, instead you could do something like this:
$models = Yourmodel::whereIn('id', [1,2,3])->get();
foreach($models as $model) {
   $model->restore();
}


Q: Django translation without request object I'm translating my Django app, in which I have a push notification module. From that module, I send a text field to user's mobile devices. Since the trigger of those notifications is not a proper HTTP request (with its "request" object), the default Django way of translating strings doesn't work.
I have a field on every user profile with its preferred language, so I think I should write some kind of middleware which would match that field with its correct translation.
Is there any way of doing that?

A: You are looking for translation.override context manager:
language = user.get_language()
with translation.override(language):
    # Translate your message here.


Q: Passing value from aspx.cs page to stored procedure I have a line in my aspx.cs page that-
cmd.CommandText="INSERT INTO [dbo].[Table] (No_Entered) Values ("+i+")";

My question is : what should be its corresponding stored procedure look like?
Thank you in advance :-)

A: cmd.CommandText = "YourStoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@No_Entered",i); //@No_Entered is parameter name in SP

Stored Procedure
CREATE PROCEDURE dbo.YourStoredProcedureName
@No_Entered int
AS
INSERT INTO TABLENAME (No_Entered) VALUES (@No_Entered)
GO

A: You have to create the stored procedure yourself.  It doesn't magically exist on its own.
https://msdn.microsoft.com/en-us/library/ms187926.aspx


Q: How to find match accros multiple lines? I have a file that looks like this:
#% text_encoding = utf8

:xy_name1   Text

:xy_name2   Text text text to a text.

Text and text to text text, text and

text provides text text text text.

:xy_name3   Text

And I want to get each entry (:ENTRY_NAME (tab \t) ENTRY_DESCRIPTION).
Im using r'^([a-zA-Z0-9:_\|!\.\?%\-\(\)]+)[\s\t]+(.*)$' regex but it doesn't work with entries that have multiline descriptions.
How can I do that?

A: The following code will do the trick:
import re

data = '''
#% text_encoding = utf8

:xy_name1   Text

:xy_name2   Text text text to a text.

Text and text to text text, text and

text provides text text text text.

:xy_name3   Text
'''

print(re.findall(r'^:(\S+)\s+([\S\s]*?)(?=\n:|\Z)',data,re.M))

The last parameter in the re.findall is a flag that makes the search a multi-line search.
^:(\S+) will match the beginning of any line followed by a colon and at least one non-space character
\s+ then consumes the tab and spaces before the description
([\S\s]*?) matches the description beginning with the first non-space character and including everything in its way - newlines inclusive. You can not use . here because in a multi-line search the . is not matching the newline character. That is why I used [\S\s] which matches all non-space characters and all space characters. The ? at the end makes the * non-greedy. Otherwise that group would consume everything all the way to the end of the data.
(?=\n:|\Z) marks the end of the description. This group is a positive look-ahead which matches either a newline followed by a colon (\n:) or the end of the data (\Z). A look-ahead does not consume the newline and the colon therefore they will be available for the next match of the findall.
The output of above code is
[('xy_name1', 'Text\n'), ('xy_name2', 'Text text text to a text. \n\nText and text to text text, text and \n\ntext provides text text text text.\n'), ('xy_name3', 'Text\n')]

Try it out here!

A: You can use capture the ENTRY_NAME in group 1.
For the ENTRY_DESCRIPTION in group 2 you can match the rest of the line, followed by all lines that do not start with the entry name pattern.
^:([\w:|!.?%()-]+)\t(.*(?:\n(?!:[\w:|!.?%()-]+\t).*)*)

Regex demo | Python demo
Example
import re

pattern = r"^:([\w:|!.?%()-]+)\t(.*(?:\n(?!:[\w:|!.?%()-]+\t).*)*)"

s = ("#% text_encoding = utf8\n\n"
            ":xy_name1  Text\n\n"
            ":xy_name2  Text text text to a text. \n\n"
            "Text and text to text text, text and \n\n"
            "text provides text text text text.\n\n"
            ":xy_name3  Text")

print(re.findall(pattern, s, re.MULTILINE))

Output
[
  ('xy_name1', 'Text\n'),
  ('xy_name2', 'Text text text to a text. \n\nText and text to text text, text and \n\ntext provides text text text text.\n'),
  ('xy_name3', 'Text')
]


Q: plane calculation in point cloud with lm() in R I have some 3D points and I want to have the better plane which minimize the distance between the plane and the point cloud. I used lm() to extract the 3 values I need.
x<-sample(1:100, 100)
y<-sample(1:100, 100)
z<-sample(1:100, 100)
plot3d(x, y, z, type = "s", col = "red", size = 1)
my.lm <- #I tried different combination of lm: lm(x ~ y + z)/lm(y ~ x + z)/lm(z ~ y + x)
#lm fct     Intercept   1st after ~   2nd after ~
#lm(x~y+z) 43.45653      0.17151     -0.03203
#lm(y~x+z) 40.66175      0.17159      0.02322
#lm(z~x+y) 50.95859     -0.03298      0.02390
planes3d(-1, 0.17151, -0.03203, 43.45653, alpha=0.5) #function use a b c and d of the ax+by+cz+d=0 equation
planes3d(0.17159, -1, 0.02322, 40.66175, alpha=0.5)
planes3d(-0.03298, 0.02390, -1, 50.95859, alpha=0.5)

I thought that the 3 planes extracted from the 3 lm() would be the same but they are very different. So I think that the reference axis chosen in the lm() function define the priority of research.
So how can I have the better plane which fit with my point cloud and that independantly (I don't want to affect the output when I choose which axis I put before the ~)
Where am I wrong? How can it be independant?
When I apply my algorithm with lm(x~y+z) I see that the plane is sometimes orthogonal compared to what I expected.

A: I think that your code is correct, but maybe the question that you are trying to solve is not clear in the sense of the output that you expect.
In the example of a cloud of homogeneously distributed unlabelled 3D points, there is no unique way to perform a dichotomy, separating the points with a unique, "ideal" surface. You can do this for the individual Cartesian components of the set of points though, and this is what your code achieves.
The first plane, shown in red color in the panel on the left in the figure below, separates the points in a linearly optimal way by a plane that only considers the x-coordinate of the points as a function of their position, leading to a function of the type x=f(y,z).
The second plane (green, on the right) is the result of a linear fit of the y-component of the points, y=g(x,z); and the third (shown in blue, in the middle) is a linear fit of the z-component of the points in the set z=h(x,y).
The three planes are certainly different, because they represent fits to different values. Hence, I don't think that there is anything wrong with your code and with your result.

Unlike the case described here, it is often possible to define meaningful (hyper-)planes separating different types of points, (like points with a certain value, e.g., temperature; or points with different attributes like "yellow" and "purple" points). It then depends on the distribution of these points in space whether they are linearly separable or not. In the latter case there are often solutions, too, but they are more complicated. For more information on such cases you may want to read about Support Vector Machines (SVM). Several R packages provide algorithms for SVMs such as, e.g., e1071 or the popular caret library.


Q: Initializing new Fragment in Tabhost/Viewpager construct not working I have an activity holding a sidebar navigation and a place holder for my fragments. (-> on clicking the sidemenu I switch fragments ...)
One of those fragments (called TabFragment) uses tabs, which are populated with (List)fragments (similar to http://developer.android.com/reference/android/support/v4/view/ViewPager.html example, but I dont use Actionbar Tabs, but the old ones).
The first time I show the TabFragment, everything works. The TabFragment is called, there I "populate the tabs" (--> like in the example above I actually just populate the viewpager) with my ListFragments (there onCreateView etc. is called). It works.
Then I try to put another instance of the TabFragment on the screen (I need to show different lists and want to be able to use the back button -> backstack), the TabFragment is called, I add the Fragments to the TabsAdapter, but no lifecycle methode of the ListFragments is called ... why?
[I know that this isn't the best way to go and there are plenty of options to rewrite this to get the same effect, but since it works the first time I'd really like to know where this is going wrong]
Activity Code
     Fragment search1 = new MainListFr();
     Bundle test1 = new Bundle();
     test1.putInt(Constants.FRAGMENT_SEARCH_ID, 1);
     g1.setArguments(test1);

     m_fragmentTransaction = m_fragmentManager.beginTransaction();
     m_fragmentTransaction.add(R.id.main_fragment_container, search1, "search1");
     m_fragmentTransaction.addToBackStack("search1");
     m_fragmentTransaction.commit();

     m_layout.toggleSidebar();

MainListFr (=TabFragment)
public class MainListFr extends Fragment {
   TabHost m_tabHost;
   ViewPager m_viewPager;
   TabsAdapter m_tabsAdapter;

   @Override
   public View onCreateView(final LayoutInflater inflater,
         final ViewGroup container, final Bundle savedInstanceState) {
      final View view = inflater.inflate(R.layout.stub_main, null);

      m_tabHost = (TabHost) view.findViewById(android.R.id.tabhost);
      m_tabHost.setup();

      m_viewPager = (ViewPager) view.findViewById(R.id.main_pager);

      m_tabsAdapter = new TabsAdapter(getActivity(), m_tabHost, m_viewPager);

      View v1 = inflater.inflate(R.layout.tab_left, null);
      View v2 = inflater.inflate(R.layout.tab_right, null);

      Bundle args = getArguments();

      m_tabsAdapter.addTab(m_tabHost.newTabSpec("topsearch").setIndicator(v1),
            SearchListFr.class, args);
      m_tabsAdapter.addTab(m_tabHost.newTabSpec("topsuggestion").setIndicator(v2),
            SuggestionListFr.class, args);

      if (savedInstanceState != null) {
         m_tabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
      }

      return view;
   }
}

SearchListFr (=ListFragment)
   private ListView m_list = null;
   private View m_progress = null;
   private View m_noRes = null;

   SearchAdapter m_searchAdapter = null;
   private Vector<SearchItem> m_searchList = null;

   private int m_searchId = 0;

   @Override
   public View onCreateView(final LayoutInflater inflater,
         final ViewGroup container, final Bundle savedInstanceState) {

      final View view = inflater.inflate(R.layout.fr_videolist, null);

      m_list = (ListView) view.findViewById(R.id.fr_videolist_list);
      m_progress = view.findViewById(R.id.progress_root);
      m_noRes = view.findViewById(R.id.noresult_root);

      m_list.setVisibility(View.GONE);
      m_noRes.setVisibility(View.GONE);
      m_progress.setVisibility(View.VISIBLE);

      Bundle args = getArguments();
      if (args != null) {
         m_searchId = args.getInt(Constants.FRAGMENT_SEARCH_ID);
      }

      // load the content here (asynctask)
      new LoadSearchList().execute();

      return view;
   }

   @Override
   public void onActivityCreated(Bundle _savedInstanceState) {
      super.onActivityCreated(_savedInstanceState);

      m_searchAdapter = new SearchAdapter(getActivity());
      m_list.setAdapter(m_searchAdapter);
      m_list.setItemsCanFocus(true);
      m_list.setOnItemClickListener(this);
   }

TabsAdapter
/**
 * This is a helper class that implements the management of tabs and all
 * details of connecting a ViewPager with associated TabHost.  It relies on a
 * trick.  Normally a tab host has a simple API for supplying a View or
 * Intent that each tab will show.  This is not sufficient for switching
 * between pages.  So instead we make the content part of the tab host
 * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
 * view to show as the tab content.  It listens to changes in tabs, and takes
 * care of switch to the correct paged in the ViewPager whenever the selected
 * tab changes.
 */
public class TabsAdapter extends FragmentPagerAdapter
        implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
    private final Context mContext;
    private final TabHost mTabHost;
    private final ViewPager mViewPager;
    private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

    static final class TabInfo {
        private final Class<?> clss;
        private final Bundle args;

        TabInfo(String _tag, Class<?> _class, Bundle _args) {
            clss = _class;
            args = _args;
        }
    }

    static class DummyTabFactory implements TabHost.TabContentFactory {
        private final Context mContext;

        public DummyTabFactory(Context context) {
            mContext = context;
        }

        @Override
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }

    public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
        super(activity.getSupportFragmentManager());
        mContext = activity;
        mTabHost = tabHost;
        mViewPager = pager;
        mTabHost.setOnTabChangedListener(this);
        mViewPager.setAdapter(this);
        mViewPager.setOnPageChangeListener(this);
    }

    public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
        tabSpec.setContent(new DummyTabFactory(mContext));
        String tag = tabSpec.getTag();

        TabInfo info = new TabInfo(tag, clss, args);
        mTabs.add(info);
        mTabHost.addTab(tabSpec);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mTabs.size();
    }

    @Override
    public Fragment getItem(int position) {
        TabInfo info = mTabs.get(position);
        return Fragment.instantiate(mContext, info.clss.getName(), info.args);
    }

    @Override
    public void onTabChanged(String tabId) {
        int position = mTabHost.getCurrentTab();
        mViewPager.setCurrentItem(position);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        // Unfortunately when TabHost changes the current tab, it kindly
        // also takes care of putting focus on it when not in touch mode.
        // The jerk.
        // This hack tries to prevent this from pulling focus out of our
        // ViewPager.
        TabWidget widget = mTabHost.getTabWidget();
        int oldFocusability = widget.getDescendantFocusability();
        widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        mTabHost.setCurrentTab(position);
        widget.setDescendantFocusability(oldFocusability);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}


Q: How to properly loop without eval, parse, text=paste("... in R So I had a friend help me with some R code and I feel bad asking because the code works but I have a hard time understanding and changing it and I have this feeling that it's not correct or proper code.
I am loading files into separate R dataframes, labeled x1, x2... xN etc.
I want to combine the dataframes and this is the code we got to work:
assign("x",eval(parse(text=paste("rbind(",paste("x",rep(1:length(toAppend)),sep="",collapse=", "),")",sep=""))))

"toAppend" is a list of the files that were loaded into the x1, x2 etc. dataframes.
Without all the text to code tricks it should be something like:
x <- rbind(##x1 through xN or some loop for 1:length(toAppend)#)

Why can't R take the code without the evaluate text trick? Is this good code? Will I get fired if I use this IRL? Do you know a proper way to write this out as a loop instead? Is there a way to do it without a loop? Once I combine these files/dataframes I have a data set over 30 million lines long which is very slow to work with using loops. It takes more than 24 hours to run my example line of code to get the 30M line data set from ~400 files.

A: If these dataframes all have the same structure, you will save considerable time by using the 'colClasses' argument to the read.table or read.csv steps. The lapply function can pass this to read.* functions and if you used Dason's guess at what you were really doing, it would be:
 x <- do.call(rbind, lapply(file_names, read.csv,
                                colClasses=c("numeric", "Date", "character")
               ))   # whatever the ordered sequence of classes might be

The reason that rbind cannot take your character vector is that the names of objects are 'language' objects and a character vector is ... just not a language type. Pushing character vectors through the semi-permeable membrane separating 'language' from 'data' in R requires using assign, or do.call eval(parse()) or environments or Reference Classes or perhaps other methods I have forgotten.


Q: How to print the sum of the number of times a certain integer returns? Heres the code:
I want to be able to print something like "Buy! = ???" or "Sell! = ???" or "Hold! = ???".
list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1
        cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    elif list_A[x] < list_B[x]:
        num_sells += 1
        cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)

    else:
        num_holds += 1
        cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Recommendations are greatly appreciated.

A: Well then just print the answer outside the loop. If I'm getting your doubt correctly.
list_A = []
list_B = []

num_sells = 0
num_buys = 0
num_holds = 0

for x in range(10000):
    list_A.append(np.random.randint(0,10))
    list_B.append(np.random.randint(0,10))

    if list_A[x] > list_B[x]:
        num_buys += 1

    elif list_A[x] < list_B[x]:
        num_sells += 1

    else:
        num_holds += 1

cprint("Buy!", 'green', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Sell!", 'red', attrs=['bold', 'reverse', 'blink'], file=sys.stderr)
cprint("Hold!", attrs=['bold', 'reverse', 'blink', 'dark'], file=sys.stderr)

Like the above.


Q: Hello world hibernate Trying to run simple java project with SQLight Hybernate. Got exception:
Deleting Doc
Hibernate: delete from Doc
Updating document, DocID = 2, Name = doc 2
Hibernate: update Doc set DocName=?, Job=? where Id=?
exception Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
Jun 15, 2016 3:30:03 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions
SEVERE: Could not synchronize database state with session
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
    at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:47)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2574)
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2478)
    at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2805)
    at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:114)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:259)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:179)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:375)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at hyberntst.Db2.close(Db2.java:46)
    at hyberntst.Db2.saveDoc(Db2.java:75)
    at hyberntst.HybernTst.main(HybernTst.java:19)

I have empty table Doc in data.db
CREATE TABLE `Doc` (
    `Id`    INTEGER PRIMARY KEY AUTOINCREMENT,
    `DocName`   TEXT,
    `Job`   TEXT
)

Hybernate config - hybernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">hyberntst.SQLiteDialect</property>
    <property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
    <property name="hibernate.connection.url">jdbc:sqlite:data.db</property>
    <property name="hibernate.connection.pool_size">1</property>
    <property name="hibernate.show_sql">true</property>
    <!--property name="hibernate.current_session_context_class">thread</property-->
    <!--property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property-->
    <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <mapping resource="hyberntst/Doc.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Class responsible for dealing with DB:
package hyberntst;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Db2 {

    private SessionFactory sessionFactory;
    private Session session;

    Db2() {

        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    //------------------------------------------------------------------------------------------------------------------
    private void open() {
        session = sessionFactory.openSession();
        session.beginTransaction();
    }

    private List query(String hql) {
        Query query = session.createQuery(hql);
        return query.list();
    }

    private void executeUpdate(String hql) {
        Query query = session.createQuery(hql);
        query.executeUpdate();
    }

    private void close() {
        session.getTransaction().commit();
        session.close();
    }

    public void deleteDoc() {
        try {
            open();

            log.finer("Deleting Doc");
            executeUpdate("delete Doc");

            close();
        } catch (Exception ex) {
            log.logExept(ex);
        } catch (Error err) {
            log.warning(err.toString());
        }
    }

    public void saveDoc(Doc doc) {
        try {
            open();
            log.finer("Updating document, DocID = " + doc.getId() + ", Name = " + doc.getDocName());
            session.saveOrUpdate(doc);

            close();
        } catch (Exception ex) {

            log.logExept(ex);
        }

    }

}

Doc class for writing to DB:
public class Doc {
     private Integer id;

    public Integer getId()
    {
        return this.id;
    }

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

    private String docName;

    public String getDocName()
    {
        return this.docName;
    }

    public void setDocName(String docName)
    {
        this.docName = docName;
    }

    private String job;

    public String getJob()
    {
        return this.docName;
    }

    public void setJob(String job)
    {
        this.job = job;
    }

}

"main" code:
Doc d = new Doc();
d.setId(new Integer(2));
d.setDocName("doc 2");
d.setJob("job 2");

Db2 db2 = new Db2();
db2.deleteDoc();
db2.saveDoc(d);

There you can see libs I use:

Looks like delete from database works fine, but what is wrong with insertion?
And what is question marks parmas in log file?
Hibernate: update Doc set DocName=?, Job=? where Id=?

A: In general, if entity id is not null, hibernate will perform update.
More information here:

saveOrUpdate() does the following:

*

*if the object is already persistent in this session, do nothing if
another object associated with the session has the same identifier,
throw an exception

*if the object has no identifier property, save() it

*if the object's identifier has the value assigned to a newly instantiated object, save() it

*if the object is versioned by a  or , and the version property value is the same value assigned to a newly
instantiated object, save() it

*otherwise update() the object

You have to call save() explicitly or leave id null


Q: What is a clean way to write a localized FtpReply to an FtpSession in a Ftplet? I would like to avoid hardcoding reply messages in a Ftplet, how can I call LocalizedFtpReply org.apache.ftpserver.impl.LocalizedFtpReply.translate(FtpIoSession session, FtpRequest request, FtpServerContext context, int code, String subId, String basicMsg) or equivalent, in a clean way?
public class NotifyFtplet extends DefaultFtplet {

    @Override
    public FtpletResult onUploadStart(FtpSession session, FtpRequest request) throws FtpException, IOException {
        session.write(new DefaultFtpReply(FtpReply.REPLY_150_FILE_STATUS_OKAY, "File status okay; about to open data connection."));
        return FtpletResult.SKIP;
    }

}


Q: Tests running locally but no test generation on jenkins ‘Publish JUnit test result report’ failed: No test report files were found I have been writing unit tests for my angular app and they run pretty well on jasmine . However when putting them on jenkins the build doesn't get completed and I have no report generated, I get the following error .
[32m28 07 2019 12:52:27.841:INFO [karma]: [39mKarma v1.7.1 server started at http://0.0.0.0:9876/
[32m28 07 2019 12:52:27.844:INFO [launcher]: [39mLaunching browser ChromeHeadless with unlimited concurrency
[32m28 07 2019 12:52:27.875:INFO [launcher]: [39mStarting browser ChromeHeadless
[31m28 07 2019 12:52:46.448:ERROR [karma]: [39m{ inspect: [Function: inspect] }
Build step 'Execute shell' marked build as failure
Recording test results
ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?
Finished: FAILURE

What I tried to do is making two separate jenkins projects . In each one I put a different test file ( in total they're two tests files) .
One of the projects run pretty well but the second one sends back the mentionned Error , I get the same error when putting both test files in the same jenkins project .
This is the project (website folder)
https://github.com/testing-angular-applications/testing-angular-applications.git
The tests are the two .spec files inside chapter03 (inside the same git)
At least I should get the report file but the build didn't go to that point ( no report has been generated)

A: Resolved !
I had to downgrade to Jasmine core 2.4.1 .


Q: converting 2D mouse coordinates to 3D space in OpenGL ES I want to convert mouse's current X and Y coordinates into the 3D space I have drawn in the viewport. I need to do this on the OpenGL ES platform. I found following possible solutions implemented in OpenGL, but none fits what I am looking for.

*

*I found NeHe's tutorial on doing exactly this, but in traditional OpenGL way. It uses gluUnProject.
http://nehe.gamedev.net/data/articles/article.asp?article=13
Although gluUnProject is not available in OpenGL ES, its implementation seems simple enough to port back. But before calling it, we need to call glReadPixels with GL_DEPTH_COMPONENT and that is not possible in OpenGL ES. (The reason I found in this thread: http://www.khronos.org/message_boards/viewtopic.php?f=4&t=771)

*What I want to do is similar to picking, except that I don't want to select the object but I want exact coordinates so that I can recognize particular portion of the object that is currently under mouse cursor. I went through the Picking tutorials in this answer.
https://stackoverflow.com/posts/2211312/revisions
But they need glRenderMode, which I believe is absent in OpenGL ES.
If you know how to solve this problem in OpenGL ES, please let me know.
Thanks.

A: I think the general solution is to figure out where in world space the clicked coordinate falls, assuming the screen is a plane in the world (at the camera's location). Then you shoot a ray perpendicular to the plane, into your scene.
This requires "world-space" code to figure out which object(s) the ray intersects with; the solutions you mention as being unsuitable for OpenGL ES seem to be image-based, i.e. depend on the pixels generated when rendering the scene.

A: With OpenGL ES 2.0 you could use a FBO and render the depth values to a texture. Obviously, this wouldn't be exactly cheap (just a way around the restriction of glReadPixels)...
Further, since - as I understand it - you want to pick certain parts of your object you might want to do some sort of color-picking where each selectable portion of the object has an unique color (note that the Lighthouse 3D tutorial only shows the general idea behind color-picking, your implementation would probably be different). You could optimize a little by performing a ray/bounding-box intersection beforehand and only rendering the relevant candidates to the texture used for picking.


Q: Setting up Rocket-chip for Questasim and getting error while compiling jtag_vpi.c I have downloaded Rocket-chip from GIT, installed RISC-V tools and Generated the verilog files for Rocket core. Now I want to run the assembly tests that are given but I dont have VCS instead I have Questasim. I modified the Makefile to use Questasim but the two C++ files that needs to be compiled SimDTM.cc and jtag_vpi.c are giving error.
In Questa we cant compile C files along with verilog files instead we need to compile this separately and generate *.so file and link with -pli while simulating.
Here when I'm compiling jtag_vpi.c I'm getting and error saying invalid conversion from 'void*' to 'PLI_INT32. I'm compiling it with the below command and the error I'm getting is also pasted below.

g++ jtag_vpi.c -I $RISCV/include -I $MTI_HOME/questasim/include -std=c++11 -W -shared -Bsymblic -fPIC

.
.

riscv/rocket-chip/csrc/jtag_vpi.c:398:2: error: invalid conversion from ‘void*’ to ‘PLI_INT32 (*)(t_cb_data*) {aka int (*)(t_cb_data*)}’ [-fpermissive]

Line 398:2 is just an end of a function and the error is shown at the end of each such function.
Any help will be useful.
Thanks in advance.


Q: swift 3 using layers to reveal an image by drawing "clear" lines * Update  Shortly after posting I found this which looks to have all my answers. Not yet worked it out for myself but this might help anyone else with similar issue. Scratch Card effect in Swift 3  End Update *
This is my first question to Stack so apologies if it's a bit 'noob'. My question kind of has two parts. I've used a couple of tutorials which have shown me how to draw lines over an image in an imageView, but I'm struggling to achieve my goal of revealing an image beneath an overlayer by drawing a "clear" line on the layer. Imagine a scratch card... that is the effect I'm after.
I have used the following Stack question/answer to help guide me initially Draw a line realtime with Swift 3.0; but my end goal is being thwarted further by the confusion of image/view bounds.
The tutorial above works great for initial drawing, except when I touch the screen, the position of my finger is converted to the imageView coordinates, so the line never appears where I place my finger. I would really like someone to help my convert the coords so the line draws exactly where I place my finger. I've tried changing the bounds in the 'Draw line' func, but I get strange behaviour from the image and the drawing stops working completely.
If anyone is able to help on either issue I'd be really grateful. And if I need to split the questions then I will do so. I've attached my code if it helps. Thanks for looking...
class ViewController: UIViewController {

    @IBOutlet weak var myImageView: UIImageView!

    var layer: CALayer {
        return myImageView.layer
    }

    var lastPoint = CGPoint.zero
    var red: CGFloat = 0.0
    var green: CGFloat = 0.0
    var blue: CGFloat = 0.0
    var brushWidth: CGFloat = 10.0
    var opacity: CGFloat = 1.0
    var swiped = false

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        swiped = false
        if let touch = touches.first {
            lastPoint = touch.location(in: self.view)
        }
    }

    func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)

        myImageView.image?.draw(in: view.bounds)

        let context = UIGraphicsGetCurrentContext()

        context?.move(to: fromPoint)
        context?.addLine(to: toPoint)

        context?.setLineCap(CGLineCap.round)
        context?.setLineWidth(brushWidth)
        context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
        context?.setBlendMode(CGBlendMode.normal)
        context?.strokePath()

        myImageView.image = UIGraphicsGetImageFromCurrentImageContext()
        myImageView.alpha = opacity
        UIGraphicsEndImageContext()
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        swiped = true
        if let touch = touches.first {
            let currentPoint = touch.location(in: view)
            drawLine(from: lastPoint, to: currentPoint)

            lastPoint = currentPoint
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if !swiped {
            // draw a single point
            self.drawLine(from: lastPoint, to: lastPoint)
        }
    }

    func setUpLayer() {
        layer.backgroundColor = UIColor.clear.cgColor
        layer.borderWidth = 10.0
        layer.borderColor = UIColor.red.cgColor
        layer.shadowOpacity = 0.7
        layer.shadowRadius = 10.0
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        myImageView.image = UIImage(named: "8BitGirls.png")

        setUpLayer()
    }
}

A: The UIResponder Touches methods are returning coordinates in your UIViewController.view's coordinates, but you need to draw in your imageViews coordinates.  UIView has multiple methods to help you with this.  try this one:
myImageView.convert(fromPoint, from: view)


Q: Where is statement counter incremented for reporting coverage within Go source code? I am looking into the Golang source code and want to understand how does it calculate coverage. I understand that each block of code has it's own statement counter; however, where is that statement counter being incremented?
Here is a link for the cover.go: https://github.com/golang/go/blob/master/src/cmd/cover/cover.go

A: Realized that you are unable to see where the counters are incremented;; the counters are boolean statements at the end of each block of code and are set to true/false during buildtime.


Q: debug node js chaincode ...? This link gives tutorial on debugging javascript chaincode in hyperledger fabric. I was able to debug my chaincode following it but recently I updated to fabric 1.2 and the peer channel list command
CORE_PEER_LOCALMSPID=Org1MSP CORE_PEER_MSPCONFIGPATH=/home/bct/fabric-samples/basic-network/crypto-config/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp peer channel list

fails with:

Fatal error when initializing core config : error when reading core
  config file: Unsupported Config Type ""

I tried to go back to v1.1 but the problem persists. Can someone give me the complete list of configuration steps that may have been missed in tutorial video (which I was following) that make the debugging chaincode work.
Thanks in advance.

A: Finally, figured out that fabric sdk (https://github.com/hyperledger/fabric-sdk-node) has to be downloaded and configured before following the video tutorial in the question.


Q: Properly writing a hexadecimal value to an address in x86 machine language I'm trying to learn how to write x86 machine code as hexadecimal (as part of putting text to the monitor on a qemu cold start.) My guess from reading a few sites was that the proper instruction to write 0x78073807 to 0xB8000  should be something along the lines of C7 00 80 0B 00 07 38 07 78 00 00 00 00 00 00 00. However, when putting this into a disassembler, the information it returns appears to indicate that this syntax is wrong. What am I missing here?
Thank You!

A: The code is missing the modr/m byte between the opcode C7 and the displacement and immediate.
mov dword [0x000B8000], 0x78073807

C7, 05, 00, 80, 0B, 00, 07, 38, 07, 78


Q: Obtain a link to a specific email in GMail How can I obtain a link (a URL) to a specific email in GMail? I want to click that link and open the specific email.

A: To clarify on the answer provided by Kevin Patel you can get the link directly from your browser, however you must have the reading pane set to "No split", otherwise you get a generic URL.

A: I don't know about a specific "email", but you can view a specific thread (which is usually one email) by clicking in the URL bar and copying that. Then, change the label to "all".
So if the url is "https://mail.google.com/mail/u/0/#inbox/abc123def456", you would change "#inbox" to say "#all" like this: "https://mail.google.com/mail/u/0/#all/abc123def456"
Now the link will work, even after you archive it and it's not in your inbox.

A: Since Google introduced the integration of Google Tasks and Gmail a few weeks ago, one way you can get the URL of a specific Gmail email us:

*

*Turn a given Gmail email into a Google Task;

*Open the task editing window (you can't perform the next task from the task display, it only seems to work when the task editing function is invoked);

*Hover over the link to the originating Gmail email in the next task you just created (the link is at the bottom of the task display);

*Use that URL to access the specific Gmail email by clicking on the link in the corresponding Google task or just pop the URL into the URL bar of any browser or other workflow (of course, the session must be logged in to the relevant Google account).

Enjoy!

A: If you are happy with a bookmarklet that copies a link to the current email to your clipboard, you can try adding this to your bookmarks:
javascript:(function()%7Basync%20function%20copyPermalink()%20%7Btry%20%7BsearchURL%20%3D%20'https%3A%2F%2Fmail.google.com%2Fmail%2Fu%2F0%2F%23search%2Fmsgid%253A'%3BmessageId%20%3D%20document.querySelector('div%5Bdata-message-id%5D').getAttribute('data-message-id').substring(7)%3Bawait%20navigator.clipboard.writeText(searchURL%20%2B%20messageId)%3Bconsole.log('Mail%20message%20permalink%20copied%20to%20clipboard')%3B%7D%20catch%20(err)%20%7Bconsole.error('Failed%20to%20copy%3A%20'%2C%20err)%3B%7D%7DcopyPermalink()%7D)()

It essentially searches the currently focussed email for its data-message-id attribute, and then converts that into a search url using the msgid predicate (this doesn't seem to be documented, but was quite guessable.). The full link is then copied to your clipboard.
Caveat: Seems to work with or without a preview pane, but this hasn't been extensively tested.

A: I don't think Gmail can show one email, it always shows a thread. You can look for one message, but still will see the whole thread.
If this is OK for you, the URL is
https://mail.google.com/mail/u/0/#search/rfc822msgid:

followed by the message ID (can be found by looking at "show original").
See this question for some more details.

A: Gmail Sharable Link Creator
Site Link: GmailLink.GitHub.io
Steps to Follow to generate the Link

*

*Get the Message ID Of Mail Thread (Mail > 3 dot menu in Right side (⋮) > Click on Show Original > See the MessageID).

*Copy the Message-Id

*Use the MessageId & click On Submit to generate the Mail Sharable Link.
https://stackoverflow.com/a/61849710/7950511

A: You can specify the inbox email address in the link to open the email in the correct inbox.
if INBOX@EMAIL.COM is your inbox email
Create the link as follows
https://mail.google.com/mail/u/INBOX@EMAIL.COM/#all/YOUR_EMAIL_ID

A: You can open up an email that you want in Gmail and after that, you can simply copy the link location from the search bar of your browser. It will create a unique weblink for every single email. It is as simple as that.

A: You just have to click on "show original" and copy the URL.

A: Actyally, get a single email link, without the full thread, seems not to be directly supported;
apart from manual url rewriting or coding tricks, that require time or specific skills, the faster workarounds I know are:
Copy the URL from the tab that opens clicking on one of these 2 entry on the email menu:

*

*print - CONS: It also open the print popup, that you have to dismiss

*show original - CONS: The email is not formatted, you see original sources, so images and formatting are missed, and messy code are added

A: How about this Chrome Extension
https://chrome.google.com/webstore/detail/gmail-message-url/bkdmmijcdflpcjchjglegcipjiabagei/related


Q: C# Generics containing generics? T I got lost implementing a interface where I need TKey, TValue and TMessageListener
public interface IHelper<TKey, TValue, TMessageListener>

but my TMessageListener is TMessageListener<TValue> how can I declare this at the interface layer?

A: It could be achieved with type constraints as follows.
public interface IHelper<TKey,TValue,TMsgLst> where TMsgLst : TMessageListener<TValue>


Q: Contact cursor returning duplicate rows My application requires contacts to integrate. I am writing a query to get the contacts from the native. I get all the rows but with the duplicate rows. Duplicate are coming if Whatsapp, skype and other accounts are linked.
Below is the query
String isPhoneType = "(" + Data.MIMETYPE + "='" + CommonDataKinds.Phone.CONTENT_ITEM_TYPE
            + "' AND " + CommonDataKinds.Phone.NUMBER + " IS NOT NULL ) ";

    String query = Contacts.DISPLAY_NAME + " IS NOT NULL "
            + " AND (" + isPhoneType + ")" ;

    String[] projection;
    if (Compatibility.isCompatible(11)) {
        projection = new String[] {
                Data._ID,
                Data.CONTACT_ID,
                Data.DATA1,
                Data.DISPLAY_NAME,
                Data.PHOTO_ID,
                Data.LOOKUP_KEY,
                Data.PHOTO_URI
        };
    } else {
        projection = new String[] {
                Data._ID,
                Data.CONTACT_ID,
                Data.DATA1,
                Data.DISPLAY_NAME,
                Data.PHOTO_ID,
                Data.LOOKUP_KEY
        };
    }

    Cursor resCursor = ctxt.getContentResolver().query(uri,
            projection, query,
            null, Data.DISPLAY_NAME + " ASC");

Please help in getting the unique rows based on the phone numbers.
Thanks

A: Add unique to phone number column in sqlite database and you will not get same contact twice.
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT UNIQUE," + KEY_IMAGE + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}


Q: Using overriden function in base class constructor for derived class I'm very new to C++ programming so I wanted to write some simple code to get used to the syntax. I have deliberately ignored pointers and references for the moment.
During coding, I was practising inheritance and I wanted to create a class Hand which represents a hand of cards. The base class has a function called update(), which is used to initialize the "total" and "notation" properties upon construction. Moreover it is possible to add cards to the hand using the add() function which adds a card to the hand and triggers update() to update the properties appropriately.
#include<vector>

class Hand
{
public:
    std::vector<int> cards;
    int total;
    std::string notation; // Abbreviated notation of the object
    // Constructor
    Hand(std::vector<int> cards);
    void update();
    void add(int card);
}

Hand::Hand(std::vector<int> cards)
{
    this->cards = cards;
    update();
}

void Hand::update()
{
    total = 0;
    notation += "{ ";
    for (int card: cards)
    {
        total += card;
        notation += std::to_string(card) + " ";
    }
    notation += "}";
}

void Hand::add(int card)
{
    cards.push_back(card);
    update();
}

Next, I wanted to create a more specific class of Hand called StandHand, which does all the same things as Hand but it also has a variable that changes when the total reaches a particular value.
Initially I thought I could just write the subclass as shown below, but alas.
class StandHand : public Hand
{
public:
    int stand;
    StandHand(std::vector<int> cards, int stand);
    void update();
}

StandHand::StandHand(std::vector<int> cards, int stand) : Hand(cards)
{
    this->stand = stand;
    updateHand();
}

void StandHand::update()
{
    Hand::update();
    notation += stand <= total ? " (stand)" : "";
}

But when I invoke the add() method on a StandHand object, it does not use the StandHand::update() method, rather it uses the base update() method. How can I make sure that the add() method, when used in a subclass of Hand, uses the update() function of that subclass?

A: For starters in the code there is no overloaded functions. The declaration of update in the derived class hides the declaration of the function with the same name in the base class.
As the member function add is declared in the base class then the name of the function update also is searched in the base class.
Declare the function update as a virtual function.
class Hand
{
public:
    // ...
    virtual void update();
};

class StandHand : public Hand
{
public:
    // ///
    void update() override;
};

A: There are two issues in your code, first void update(); in the base class needs to be declared virtual, so that compiler will know that derived classes might override it and use it.
virtual void update();
// add "=0;" if there is no base version of update()

And in the derived class write
void update() override;
//override is unnecessary but recommended
//it verifies that you do indeed overload a method from a base class

Second problem, you cannot call methods from derived class in constructor of its base class. What happens is that calling virtual base method results in calling the base version instead of the derived version. Think of it: the derived object isn't constructed yet but you already call one of its methods? It doesn't make any sense.


Q: Google Foobar challenge "Find the access codes" SOLVED
I was sorting the list when in reality the prompt was asking for the order in which the numbers were given. Not going to delete the post in case someone else makes the same mistake.
I would like to preface this by saying that I have already read over other answers to this conundrum, but to no avail. I even tried copying the provided solutions, just to see if they actually worked, and they failed more test cases than the code I used.
Original Prompt

"Write a function answer(l) that takes a list of positive integers l and counts the number of "lucky triples" of (li, lj, lk) where the list indices meet the requirement i < j < k. The length of l is between 2 and 2000 inclusive. The elements of l are between 1 and 999999 inclusive. The answer fits within a signed 32-bit integer. Some of the lists are purposely generated without any access codes to throw off spies, so if no triples are found, return 0.
A "lucky triple" is a tuple (x, y, z) where x divides y and y divides z, such as (1, 2, 4).
For example, [1, 2, 3, 4, 5, 6] has the triples: [1, 2, 4], [1, 2, 6], [1, 3, 6], making the answer 3 total."

At this point, I'm not even asking for a solution so I can pass to the next level, because I would feel that I am cheating at that point, however, I have no idea why I am failing test cases 3-5 (and obviously the test cases aren't publicly available, but I'm just asking if anyone can find flaws in my programming).
Like I'm sure most people did, I began by creating a triple for-loop that iterated over every possible "triple," but seeing as it was O(n^3), it took too long. I am, however, using that as a "base solution" for my code to compare answers to more complicated cases.
My code (in python)
I apologize if the code is a bit messy, but I am new to python, and mainly did this challenge for the learning opportunity, and just to work my brain.
The function takes a list, l, and then I sort it into descending order. I then create a list which I initialize all values to 0. For the first while-loop set, I am counting the amount of "doubles" where l[y] divides l[x] evenly, then count the amount of factors that l[x] has. I.e if there were a list [1,2,3,4] then this loop checks [3%2] , [3%1], [2%1].
The next while-loop set checks the first 2 numbers ([4%3] , [4%2] , [3%2]). Both of these loops are verified in my (local) code with print statements, and those are the operations occurring. If the mod in the second while set is true, then it increments the counter by the amount of factors that the 'Y' value had (in this case, only [4%2] is true and then it would go to the l_count list and increment the count variable by the value in the array that corresponds to 2. In this case, it is 1, because the only true case for the number "2" in the first while loop is [2%1]). I would have included comments in my code, but I did not think I would be having this issue in the first place.
Anyway, any help would be greatly appreciated! Thanks
l.sort()
l = l[::-1]

length = len(l)

count = 0

l_count = []
for x in range(len(l)):
    l_count.append(0)

x = 1
while x < (length - 1):
    y = x + 1
    while y < length:
        if l[x] % l[y] == 0:
            l_count[x] = l_count[x] + 1
        y = y + 1
    x = x + 1

x = 0
while x < (length - 2):
    y = x + 1
    while y < (length - 1):
        if l[x] % l[y] == 0:
            count = count + l_count[y]
        y = y + 1
    x = x + 1

return count

A: The first thing you do is already a mistake: Sorting. That'll make you report that [6, 5, 4, 3, 2, 1] has three such triples (same as the example) when in reality it doesn't have any.
(Given that you pass two of five tests, I can imagine this is your only mistake. Maybe those tests are already sorted so you're not messing those up.)


Q: Difference between a data warehouse and a MOLAP server What is the difference between a data warehouse and a MOLAP server?
Is the data stored at both the data warehouse and on the MOLAP server?
When you pose a query, do you send it to the data warehouse or the MOLAP server?
With ROLAP, it kind of makes sense that the ROLAP server pose SQL queries to the data warehouse (which store fact and dimension tables), and then do the analysis. However, I have read somewhere that ROLAP gathers its data directly from the operational database (OLTP), but then, where/when is the data warehouse used?

A: The 'MOLAP' flavour of OLAP (as distinguished from 'ROLAP') is a data store in its own right, separate from the Data Warehouse.
Usually, the MOLAP server gets its data from the Data Warehouse on a regular basis. So the data does indeed reside in both.
The difference is that a MOLAP server is a specific kind of database (cube) that precalculates totals at levels in hierarchies, and furthermore structures the data to be even easier for users to query and navigate than a data warehouse (with the right tools at their disposal).
Although a data warehouse may be dimensionally modelled, it is still often stored in a relational data model in an RDBMS.
Hence MOLAP cubes (or other modern alternatives) provide both performance gains and a 'semantic layer' that makes it easier to understand data stored in a data warehouse.
The user can then query the MOLAP server rather than the Data Warehouse. That doesn't stop users querying the Data Warehouse directly, if that's what your solution needs.
You're right that when the user queries a ROLAP server, it passes on the queries to the underlying database, which may be an OLTP system, but is more often going to be a data warehouse, because those are designed for reporting and query performance and understandability in mind. ROLAP therefore provides the user-friendly 'semantic layer' but relies on the performance of the data warehouse for speed of queries.


Q: ConcatRelated function and the fifth argument I'm trying to achieve the following:
If you have:
ItemNo   DocumentNo    Quantity
AB1         WS1           10
AB1         WS2           10

I want:
 ItemNo   DocumentNo    Quantity
AB1         WS1 | WS2          10

I'm not quite understanding how to use the fifth argument. I continue to get errors, stating that "|" is not valid.
Here's the code.
SELECT DISTINCT Query3.ItemNo,  ConcatRelated("Query3.DocumentNo", "Query3", "Query3.ItemNo = " & [Query3.ItemNo] & " | " )
FROM Query3;

Here's the website:
http://allenbrowne.com/func-concat.html

A: I can't tell, but my DJoin function found here and this query:
SELECT
    ItemNo,
    DJoin("[DocumentNo]","[Query3]","[ItemNo] = '" & [ItemNo] & "'"," | ") AS DocumentNos,
    Quantity
FROM
    Query3
GROUP BY
    ItemNo,
    Quantity
HAVING
    Count(*) >=2;

will provide this output:


Q: Assigning to slices of 2D NumPy array I want to assign 0 to different length slices of a 2d array.
Example:
import numpy as np

arr = np.array([[1,2,3,4],
                [1,2,3,4],
                [1,2,3,4],
                [1,2,3,4]])

idxs = np.array([0,1,2,0])

Given the above array arr and indices idxs how can you assign to different length slices. Such that the result is:
arr = np.array([[0,2,3,4],
                [0,0,3,4],
                [0,0,0,4],
                [0,2,3,4]])

These don't work
slices = np.array([np.arange(i) for i in idxs])
arr[slices] = 0

arr[:, :idxs] = 0

A: You can use broadcasted comparison to generate a mask, and index into arr accordingly:
arr[np.arange(arr.shape[1]) <= idxs[:, None]] = 0

print(arr)
array([[0, 2, 3, 4],
       [0, 0, 3, 4],
       [0, 0, 0, 4],
       [0, 2, 3, 4]])

A: This does the trick:
import numpy as np

arr = np.array([[1,2,3,4],
               [1,2,3,4],
               [1,2,3,4],
               [1,2,3,4]])
idxs = [0,1,2,0]
for i,j in zip(range(arr.shape[0]),idxs):
  arr[i,:j+1]=0

A: Here is a sparse solution that may be useful in cases where only a small fraction of places should be zeroed out:
>>> idx = idxs+1
>>> I = idx.cumsum()
>>> cidx = np.ones((I[-1],), int)
>>> cidx[0] = 0
>>> cidx[I[:-1]]-=idx[:-1]
>>> cidx=np.cumsum(cidx)
>>> ridx = np.repeat(np.arange(idx.size), idx)
>>> arr[ridx, cidx]=0
>>> arr
array([[0, 2, 3, 4],
       [0, 0, 3, 4],
       [0, 0, 0, 4],
       [0, 2, 3, 4]])

Explanation: We need to construct the coordinates of the positions we want to put zeros in.
The row indices are easy: we just need to go from 0 to 3 repeating each number to fill the corresponding slice.
The column indices start at zero and most of the time are incremented by 1. So to construct them we use cumsum on mostly ones. Only at the start of each new row we have to reset. We do that by subtracting the length of the corresponding slice such as to cancel the ones we have summed in that row.

A: import numpy as np

arr = np.array([[1, 2, 3, 4],
                [1, 2, 3, 4],
                [1, 2, 3, 4],
                [1, 2, 3, 4]])

idxs = np.array([0, 1, 2, 0])

for i, idx in enumerate(idxs):
    arr[i,:idx+1] = 0


Q: alternatives for website accesibility testing Any suggestions for free tools to test website accessibility (508+). We used to use http://wsspg.dequecloud.com/worldspace/wsservice/eval/checkCompliance.jsp for this purpose and this site is no longer available.

A: Try Google Accessibility Developer Tools Extension for Chrome. It runs an accessibility audit on individual pages, making assertions based on WCAG 2.0.
If you have a Rails project, you can run the assertions from the Google Extension as part of an Rspec integration test suite using capybara-accessible, a rubygem that defines a Selenium based webdriver for Capybara and makes accessibility assertions on page loads. That way you can automate testing across your site and also get failures in CI.

A: Try Wave, which is free to use. But not sure if it has full functionality. Check it out yourself and let me know if its the right one for you.

A: As Felipe said, no automated testing should be relied upon. Specifically if you need to test for Section 508, it states that you have to test with AT. WAVE and Deque WorldSpace does not satisfy this requirement. WAVE is a fine tool to catch low hanging fruit. Maybe the Google Plug-in does as well, but would not rely upon it due to how Chrome handles and reports things to MSAA and other APIs.
I have heard numbers thrown around how well automated testers are. Personally, I set them around the 50% mark, particially due to the "full functionality" aspect that Felipe mentions in Mohammad's answer. In terms of Section 508, this phrase is called "equivalent facilitation", which is covered in 1194.31, which no automated tester can cover. Subpart 1194.31 is the functional standards, which apply to all activities if Section 508 is applicable. The same goes with 1194.41.
FelipeAls said:

[Section 508] outdated and W3C/WAI WCAG 2.0 is a way better resource for improving accessibility nowadays (but of course if you must be compliant with 508, then also test for 508)

While I will say Section 508 is rough around the edges, I wouldn't say it is useless as some market it as. In my experience people pushing this, have limited experience actually dealing with Section 508, or they work behind a product that does testing. Their biggest arguement is usually "heh look, if Section 508 is so good, why doesn't it require headings (<h1>)?" Well, Section 508 was derived from WCAG 1.0, which didn't have it either, so that argument is weak in my opinion. Also, remember how I said people don't realise that 1194.31 is applicable? Let's look at 1194.31(a):

(a) At least one mode of operation and information retrieval that does not require user vision shall be provided, or support for assistive technology used by people who are blind or visually impaired shall be provided.

You can read that as: code a page so that AT can find specific parts of/on a page. What's a good way to allow people to jump around? Headings, and now WAI-ARIA Landmarks.
Section 508 is also being worked on to adopt WCAG 2.0.


Q: Wrap wkhtmltoimage to xvfb-run How can I use wkhtmltoimage to run by default with xvfb?
/usr/bin/xvfb-run --server-args="-screen 0, 1024x1024x24"

I've to create bash file like this wkhtmltoimage
/usr/bin/xvfb-run --server-args="-screen 0, 1024x1024x24" /usr/local/bin/wkhtmltoimage-64 $*

But in this case, other programs (gem imgkit) do not work correctly with wkhtmltoimage. It put addition debug info to the file.

A: You can create a wrapper script as I done that:
wkhtmltoimage:
xvfb-run --server-args="-screen 0, 1024x680x24" wkhtmltoimage.bin -q --use-xserver $*

where wkhtmltoimage.bin is original binary.


Q: How do I stop sound on mouseout when hovering over an image?
var Start = new Audio("MySound.mp3");

When hovering over the image the sound plays correctly but when I mouseout the sound continues playing? Not too sure why that is.

A: Change from onmouseout="Start.pause;"> to onmouseout="Start.pause();">. You missed the parenthesis in the pause function


Q: Persisting data on disk using Hazelcast I have installed HazelCast 2.5. I want to persist my records into disk. I learned that MapStore does this job. However i'm not sure how to implement MapStore.
Code I've written so far:
public class MyMaps implements MapStore<String,String> {

    public static Map<Integer, String> mapCustomers = Hazelcast.getMap("customers");

    public static void main(String[] args) {
        {
            mapCustomers.put(1, "Ram");
            mapCustomers.put(2, "David");
            mapCustomers.put(3, "Arun");

        }
    }
}

How do i put all these entries into disk.
Is it necessary to have a back-end like MySQL or PostgreSQL to use this class?
I believe the following function can be used:
public void delete(String arg0);
public void deleteAll(String arg0);
public void store(String arg0);
public void storeAll(String arg0);

I need a sample snippet of how to implement MapStore.
Please provide me with sample code.

A: Yes, you can use MapStore and MapLoader to persist file to local storage. Read official documentation here.
https://docs.hazelcast.org/docs/latest/manual/html-single/#loading-and-storing-persistent-data

A: Hazelcast has two types of distributed objects in terms of their partitioning strategies:

*

*Data structures where each partition stores a part of the instance, namely partitioned data structures.

*Data structures where a single partition stores the whole instance, namely non-partitioned data structures.
Partitioned Hazelcast data structures persistence data to local file system is not supported,need a centralized system that is accessible from all hazelcast members,like mysql or mongodb.
You can get code from hazelcast-code-samples.


Q: In C#, Loading large file into winform richtextbox I need to load a - 10MB range text file into a Winform RichTextBox, but my current code is freezing up the UI. I tried making a background worker do the loading, but that doesnt seem to work too well either.
Here's my several loading code which I was tried. Is there any way to improve its performance? Thanks.
    private BackgroundWorker bw1;
    private string[] lines;
    Action showMethod;
    private void button1_Click(object sender, EventArgs e)
    {
        bw1 = new BackgroundWorker();
        bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
        string path = @"F:\DXHyperlink\Book.txt";
        if (File.Exists(path))
        {
            string readText = File.ReadAllText(path);
            lines = readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            bw1.RunWorkerAsync();

        }
    }

    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        Invoke((ThreadStart)delegate()
        {
            for (int i = 0; i < lines.Length; i++)
            {
                richEditControl1.Text += lines[i] + "\n";
            }
        });
    }

I Also Try:
Action showMethod = delegate()
            {
                for (int i = 0; i < lines.Length; i++)
            {
                richEditControl1.Text += lines[i] + "\n";
            }
            };

A: It's about how you're invoking the UI update, check the AppendText bellow.
private BackgroundWorker bw1;

private void button1_Click(object sender, EventArgs e)
{
    bw1 = new BackgroundWorker();
    bw1.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw1.RunWorkerCompleted += bw_RunWorkerCompleted;
    bw1.RunWorkerAsync();
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string path = @"F:\DXHyperlink\Book.txt";
    if (File.Exists(path))
    {
        string readText = File.ReadAllText(path);
        foreach (string line in readText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            AppendText(line);
            Thread.Sleep(500);
        }
    }
}

private void AppendText(string line)
{
    if (richTextBox1.InvokeRequired)
    {
        richTextBox1.Invoke((ThreadStart)(() => AppendText(line)));
    }
    else
    {
        richTextBox1.AppendText(line + Environment.NewLine);
    }
}

In addition to that reading the whole file text is very inefficient. I would rather read chunk by chunk and update the UI. i.e.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string path = @"F:\DXHyperlink\Book.txt";
    const int chunkSize = 1024;
    using (var file = File.OpenRead(path))
    {
        var buffer = new byte[chunkSize];
        while ((file.Read(buffer, 0, buffer.Length)) > 0)
        {
            string stringData = System.Text.Encoding.UTF8.GetString(buffer);

            AppendText(string.Join(Environment.NewLine, stringData.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)));
        }
    }
}

A: You don't want to concatenate strings in a loop.

A System.String object is immutable. When two strings are
  concatenated, a new String object is created. Iterative string
  concatenation creates multiple strings that are un-referenced and must
  be garbage collected. For better performance, use the
  System.Text.StringBuilder class.

The following code is very inefficient:
for (int i = 0; i < lines.Length; i++)
{
    richEditControl1.Text += lines[i] + "\n";
}

Try instead:
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    // Cpu intensive work happens in the background thread.
    var lines = string.Join("\r\n", lines);

    // The following code is invoked in the UI thread and it only assigns the result.
    // So that the UI is not blocked for long.
    Invoke((ThreadStart)delegate()
    {
        richEditControl1.Text = lines;
    });
}

A: why do you want to split lines and join them again?
strings  are immutable witch means cant be changed. So every time you do Text+= "..." it has to create new string and put it in Text. So for 10 mb string its not ideal way and it may take Centuries To complete such task for Huge strings.
You can see What is the difference between a mutable and immutable string in C#?
If you really want to split Them and Join them again. then StringBuilder is the right option for you.
        StringBuilder strb = new StringBuilder();

        for (int i = 0; i < lines.Length; i++)
        {
            strb.Append(lines[i] + "\n");
        }

        richEditControl1.Text = strb.ToString();

You can see String vs. StringBuilder
Structure of StringBuilder is List of characters. Also StringBuilder is Muttable. means can be changed.
Inside Loop you can do any extra task with string and Add the final result to the StringBuilder. Finally after the loop Your StringBuilder is Ready. You have to convert it to string and Put it in Text.

A: It took me a while to nail this one..
Test one & two:
First I created some clean data:
string l10 = " 123456789";
string l100 = l10 + l10 + l10 + l10 + l10 + l10 + l10 + l10 +l10 + l10;
string big = "";
StringBuilder sb = new StringBuilder(10001000);
for (int i = 1; i <= 100000; i++)
    // this takes 3 seconds to load
    sb.AppendLine(i.ToString("Line 000,000,000 ") + l100 + " www-stackexchange-com ");
     // this takes 45 seconds to load !!
    //sb.AppendLine(i.ToString("Line 000,000,000 ") + l100 + " www.stackexchange.com ");
big = sb.ToString();

Console.WriteLine("\r\nStringLength: " + big.Length.ToString("###,###,##0") + "  ");

richTextBox1.WordWrap = false;
richTextBox1.Font = new System.Drawing.Font("Consolas", 8f);
richTextBox1.AppendText(big);
Console.WriteLine(richTextBox1.Text.Length.ToString("###,###,##0") + " chars in RTB");
Console.WriteLine(richTextBox1.Lines.Length.ToString("###,###,##0") + " lines in RTB ");

Displaying 100k lines totalling in around 14MB takes either 2-3 seconds or 45-50 secods.
Cranking the line count up to 500k lines brings up the normal text load time to around 15-20 seconds and the version that includes a (valid) link at the end of each line to several minutes.
When I go to 1M lines the loading crashes VS.
Conclusions:

*

*It takes a 10+ times longer to load a text with links in it and during that time the UI is freezing.

*Loading 10-15MB of textual data is no real problem as such.
Test three:
string bigFile = File.ReadAllText("D:\\AllDVDFiles.txt");
richTextBox1.AppendText(bigFile);

(This was actually the start of my investigation..) This tries to load a 8 MB large file, containing directory and file info from a large number of data DVDs. And: It freezes, too.
As we have seen the file size is not the reson. Nor are there any links embedded.
From the first looks of it the reason are funny characters in some of the filenames.. After saving the file to UTF8 and changing the read command to..:
string bigFile = File.ReadAllText("D:\\AllDVDFiles.txt", Encoding.UTF8);

..the file loads just fine in 1-2 seconds, as expected..
Final conclusions:

*

*You need to watch out for wrong encoding as those characters can freeze the RTB during loading.

*And, when you add links you must expect for the loading to take a a lot (10-20x) longer than the pure text.  I have tried to trick the RTB by preparing a Rtf string but it didn't help. Seems that analyzing and storing all those links will always take such a long time.

So: If you really need a link on every line, do partition the data into smaller parts and give the user an interface to scroll & search through those parts.
Of course appending all those lines one by one will always be way too slow, but this has been mentionend in the comments and other answers already.


Q: Custom contour plot in MATLAB I want to create a contour plot in MATLAB, as in the second example on this page:
ContourPlot[Cos[x] + Cos[y] == 1/2, {x, 0, 4 Pi}, {y, 0, 4 Pi}]

As you can see, they are plotting only the lines for which f(X, Y) == some_value. Another issue I have is that I do not really have the function f, but only a collection of points of type [x, y, z] (read from a file), and some_value of course.
Is it possible to do such a plot in MATLAB?

A: Simply use the contour function with a 2nd argument of desired values (it is a vector of 2 elements instead of a scalar, to distinguish the function call from another mode):
some_value = .5;
[x y] = meshgrid(linspace(0,4*pi,30),linspace(0,4*pi,30));
z = cos(x)+cos(y);
contour(x, y, z, [some_value, some_value])

A: It helped me.
contourf(aX, aY, NM(:, :, k+1), 'ShowText','on', 'LevelStep', 0.4);


Q: Stripping text from one point to another in python I have a file textfile.txt:
[X:Y:Z]

How would I strip "X:" and ":Z" so that I am left with "Y"?

A: Using str.strip and str.split:
>>> '[X:Y:Z]'.strip('[]')
'X:Y:Z'
>>> '[X:Y:Z]'.strip('[]').split(':')
['X', 'Y', 'Z']
>>> '[X:Y:Z]'.strip('[]').split(':')[1]
'Y'

UPDATE
As Blender commented, stripping the brackets off is not necessary.
>>> '[X:Y:Z]'.split(':')
['[X', 'Y', 'Z]']
>>> '[X:Y:Z]'.split(':')[1]
'Y'

A: Y = "[X:Y:Z]".split(':')[1]
That's a quick one liner for it.

A: There are dozens of ways you could achieve this for the single example you've posted, e.g.:
full_string = '[X:Y:Z]'
first, middle, last = full_string.split(':')
print(middle)
Out[5]: 'Y'

To narrow down what will or won't work, you may have to post some more examples that make clearer how your data format looks, and what pieces of information you need to extract from it.


Q: Two arrays defining 2D coordinates, as array indices I have a 2D array, call it A.  I have two other 2D arrays, call them ix and iy. I would like to create an output array whose elements are the elements of A at the index pairs provided by ix and iy.  I can do this with a loop as follows:
for i=1:nx
    for j=1:ny
        output(i,j) = A(ix(i,j),iy(i,j));
    end
end

How can I do this without the loop?  If I do output = A(ix,iy), I get the value of A over the whole range of (ix)X(iy).

A: This is the one-line method which is not very efficient for large matrices
reshape(diag(A(ix(:),iy(:))),[ny nx])

A clearer and more efficient method would be to use sub2ind. I've incorporated yuk's comment for situations (like yours) when ix and iy have the same number of elements:
newA = A(sub2ind(size(A),ix,iy));

Also, don't confuse x and y for i and j in notation - j and x generally represent columns and i and y represent rows.

A: A faster way is to use linear indexing directly without calling SUB2IND:
output = A( size(A,1)*(iy-1) + ix )

... think of the matrix A as a 1D array (column-wise order)


Q: ClassCastException when try to use loaded class Java Version: 6
I have build an aotuloader which loads Classes out of a JAR and instances them. SO i get an ArrayList of all Instances which match to the specific path and Abstract Class.
package com.geNAZt.RegionShop.Util;

import com.geNAZt.RegionShop.RegionShopPlugin;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Loader {
    public static <T> ArrayList<T> loadFromJAR(RegionShopPlugin plugin, String path, Class interf) {
        ArrayList<T> returnObjects = new ArrayList<T>();

        try {
            String pathToJar = Loader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            JarFile jarFile = new JarFile(pathToJar);
            Enumeration e = jarFile.entries();

            URL[] urls = { new URL("jar:file:" + pathToJar +"!/") };
            ClassLoader cl = URLClassLoader.newInstance(urls);

            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();

                if(je.isDirectory() || !je.getName().endsWith(".class") || !je.getName().substring(0,je.getName().length()-6).replace("/", ".").contains(path +".")){
                    continue;
                }

                try {
                    String className = je.getName().substring(0,je.getName().length()-6);
                    className = className.replace('/', '.');
                    Class<?> c = cl.loadClass(className);

                    if(!c.getSuperclass().getName().equals(interf.getName())) {
                        continue;
                    }

                    Constructor[] cons = c.getDeclaredConstructors();

                    for(Constructor con : cons) {
                        try {
                            returnObjects.add((T)con.newInstance(plugin));
                            break;
                        } catch (InvocationTargetException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (InstantiationException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (IllegalAccessException e1) {
                            e1.printStackTrace();
                            continue;
                        } catch (IllegalArgumentException e1) {
                            e1.printStackTrace();
                            continue;
                        }
                    }
                } catch(ClassNotFoundException er) {
                    er.printStackTrace();
                    continue;
                }

            }
        } catch(IOException e) {
            e.printStackTrace();

            return null;
        }

        return returnObjects;
    }
}

It works fine an i get the right Objects with:
private ArrayList<ShopCommand> loadedCommands = new ArrayList<ShopCommand>();
loadedCommands = loadFromJAR(pl, "com.geNAZt.RegionShop.Command.Shop", ShopCommand.class);

If i make a log all Objects seem to be fine:

12:24:40 [INFO] [RegionShop] Loaded ShopCommands: [com.geNAZt.RegionShop.Command.Shop.ShopAdd@3b39c41d, com.geNAZt.RegionShop.Command.Shop.ShopBuy@4d7a6a4b, com.geNAZt.RegionS
  hop.Command.Shop.ShopDetail@1fd889aa, com.geNAZt.RegionShop.Command.Shop.ShopEquip@4136083b, com.geNAZt.RegionShop.Command.Shop.ShopList@42567aef, com.geNAZt.RegionShop.Comman
  d.Shop.ShopName@3ba102ef]

But then i want to use them. In case to use them i wanted to cast them into the ShopCommand Class. But then i get this error:

12:24:40 [SCHWERWIEGEND] Error occurred while enabling RegionShop v1.1.0b3 (Is it up to date?)
  java.lang.ClassCastException: com.geNAZt.RegionShop.Command.Shop.ShopAdd cannot be cast to com.geNAZt.RegionShop.Command.ShopCommand
          at com.geNAZt.RegionShop.Command.ShopExecutor.(ShopExecutor.java:40)
          at com.geNAZt.RegionShop.RegionShopPlugin.onEnable(RegionShopPlugin.java:80)
          at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:217)
          at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:457)
          at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:383)
          at org.bukkit.craftbukkit.v1_5_R3.CraftServer.loadPlugin(CraftServer.java:305)
          at org.bukkit.craftbukkit.v1_5_R3.CraftServer.enablePlugins(CraftServer.java:287)
          at net.minecraft.server.v1_5_R3.MinecraftServer.j(MinecraftServer.java:310)
          at net.minecraft.server.v1_5_R3.MinecraftServer.e(MinecraftServer.java:289)
          at net.minecraft.server.v1_5_R3.MinecraftServer.a(MinecraftServer.java:249)
          at net.minecraft.server.v1_5_R3.DedicatedServer.init(DedicatedServer.java:152)
          at net.minecraft.server.v1_5_R3.MinecraftServer.run(MinecraftServer.java:388)
          at net.minecraft.server.v1_5_R3.ThreadServerApplication.run(SourceFile:573)

Is it possible to cast the Objects into the abstract class so i get the api from the Class ? Or is there another way to get the API from the Class ?

A: This exception is the result of class identity crisis . You cannot cast between class loaders. As mentioned this site:

Other types of confusion are also possible when using multiple class
  loaders. Figure 2 shows an example of a class identity crisis that
  results when an interface and associated implementation are each
  loaded by two separate class loaders. Even though the names and binary
  implementations of the interfaces and classes are the same, an
  instance of the class from one loader cannot be recognized as
  implementing the interface from the other loader.

EDIT
Although the solution is found out by the OP but I would like to give my two cents.
The confusion which is leading to the nonrecognition of instance of the class from other ClassLoader could easily be resolved if that class is moved into the System class loader's space. And making System Class Loader to be the parent of newly created ClassLoaders. This would cause the different ClassLoaders to share the same class. This could be achieved by URLClassLoader(URL[] urls,ClassLoader parent) in following way:
URL[] urls = { new URL("jar:file:" + pathToJar +"!/") };
ClassLoader cl = new URLClassLoader(urls,ClassLoader.getSystemClassLoader());


Q: Converting floats to and displaying Binary Numbers in C So I'm just diving into C during my first few days of classes. My professor proposed a question/ more of a challenge for us so I thought I'd propose it here.
float x,y,z;
x = 0.0;
y = 1.0;
z = -2.5;

He wanted us to display these numbers in binary and hexadecimal without using %x etc. He also hinted to use a union:
union U {
float y;
unsigned z;
};

Thank you for your time in advance. I'm just looking for help/ an explanation on how to develop such conversion.

A: The correct way, not violating the strict aliasing rule would be to alias the float with a char array, which is allowed by the C standard.
union U {
  float y;
  char c[sizeof (float)];
};

This way you will be able to access the individual float y; bytes using the c array, and convert them into binary/hex using the very simple algorithm that can be easily found around (I will leave it up to you, as it is your assignment).


Q: Qt: How to know when a QMdiSubWindow is closed? Is there any way I can get notified when a user closes a QMdiSubWindow? I cannot find any signal in QMdiArea nor in QMdiSubWindow that suggests I can.
I think my only chance is by subclassing QMdiSubWindow and overriding the close event, but is there any other way?

A: Yes, there is another way : you can install an event-filter on the QMdiSubWindow you create :
MdiSubWindowEventFilter * p_mdiSubWindowEventFilter;

...

QMdiSubWindow * subWindow = mdiArea->addSubWindow(pEmbeddedWidget);
subWindow->installEventFilter(p_mdiSubWindowEventFilter);
subWindow->setAttribute(Qt::WA_DeleteOnClose, true); // not mandatory, depends if you manage subWindows lifetime

with
bool MdiSubWindowEventFilter::eventFilter(QObject * obj, QEvent * e)
{
    switch (e->type())
    {
        case QEvent::Close:
        {
            QMdiSubWindow * subWindow = dynamic_cast<QMdiSubWindow*>(obj);
            Q_ASSERT (subWindow != NULL);

            //
            // do what you want here
            //

            break;
        }
        default:
            qt_noop();
    }
    return QObject::eventFilter(obj, e);
}

A: I had the same trouble, but in my case the task was more specific: "How to hide a subwindow when I press the close button instead of closing". So I solved this with the following:
subwindow->setAttribute(Qt::WA_DeleteOnClose, false);

Perhaps it's not a relevant answer but it may be useful for someone.

A: I don't think there is any other way than as you describe (overriding the close event) to do precisely what you're asking.
There might be other ways of achieving what you want without doing that depending on why you want to know when its closed.  Other options could be the use of the destroyed signal, checking QApplication::focusWidget(), or perhaps having the parent inspect its children.
Edit in response to comment:
Signals and slots are disconnected automatically upon destruction of QObjects, and I would suggest looking at using QSharedPointers or QScopedPointers to handle your QObjects' lifespans instead.  By applying these techniques, you shouldn't need a signal from a closed window.

A: Here is what I ended coding.
#ifndef __MYSUBWINDOW_H
#define __MYSUBWINDOW_H

#include <QMdiSubWindow>
#include <QCloseEvent>
#include <QDebug>

class MyQMdiSubWindow : public QMdiSubWindow
{
    Q_OBJECT

signals:
    void closed( const QString );

protected:
    void closeEvent( QCloseEvent * closeEvent )
    {
        emit closed( this->objectName() );
        closeEvent->accept();
    }
};
#endif

Note that for my problem I need a way to identify which subwindow user is closing, and objectName does the work for me.

A: You can create QWidget based class like:
class CloseWatcher : public QWidget
{
  Q_OBJECT

private:
  QString m_name;

signals:
  void disposing( QString name );

public
  CloseWatcher( QWidget * p )
    : QWidget( p )
    , m_name( p->objectName() )
  {}

  ~CloseWatcher()
  {
    emit disposing( m_name );
  }
};

and just use it:
// anywhere in code
QMdiSubWindow * wnd = getSomeWnd();
CloseWatcher * watcher = new CloseWatcher( wnd );

connect( watcher, SIGNAL( disposing( QString ) ), reveiver, SLOT( onDispose( QString ) ) );


Q: Unexpected parameter: id While writing the Python code for Twitter extraction in Jupyter notebook I am getting the error as Unexpected parameter: id. Can anyone please help me with it?

A: You need to provide the relevant code and/or full traceback for anyone to know what exactly is going on, but that's likely just a warning that you're passing an id parameter to an API method that doesn't expect it.
Tweepy v4.0.0 changed many API methods to no longer accept id parameters.

A: You need to use screen_name instead of id parameter.


Q: Chef Configuration setting I am trying to configure for copying  files  through chef.However,we have a requirement to push  configuration only  for couple of servers. Is there any parameter or setting for that ?
Elaborated a little more .....
Our standard deployment through Chef requires that the latest build be deployed to all servers.
However, individual developers also submit experimental builds that are deployed to 1-2 servers per developer only as opposed to the entire stack.
Our objectives are as follows:
1.  Be able to deploy experimental builds through Chef to a specified set of servers.
2.  Prevent experimental builds from being deployed to the servers that already host experimental builds – perhaps have the Chef server mark those servers as unavailable somehow(?)
3.  Be able to deploy full builds to either all servers or only those servers that are not used for experimental builds at the moment.
I’m sure it’s a fairly common scenario and would  like to know if there is an elegant/effective/dynamic  way to keep Chef server informed of where each build/experiment should be  deployed to.

A: If you use a cloud provider, the answer is to use Packer to create an image for each build, and then deploy images as needed.  If you use bare metal, then you can easily use either normal attributes or roles to setup the versions.  I'd suggest attributes.

*

*Set node['myapp']['test_version'] = 'some version' on the nodes to be updated

*In your recipe, check the value of that attribute.  If set, then install that version, otherwise install your master version.

To remove a node from the experiment, you can just reset that attribute to nil on the node.  The next chef run will result in that node going back to the master version.
If you want a way to install the master version on ALL nodes, including ones that are in experiments, you can either write a second recipe that ignores the setting, or you can add an override attribute like node['myapp']['force_master'] or such.  You could then set that on the environment to override the experiments.  But you'd need to remember to reset it at a later time.


Q: ModelForm and Model validation playing together I have the following Model :
class Advertisement(models.Model):

    slug = models.UUIDField(default=uuid4, blank=True, editable=False)

    advertiser = models.ForeignKey(Advertiser)
    position = models.SmallIntegerField(choices=POSITION_CHOICES)
    share_type = models.CharField(max_length=80)
    country = CountryField(countries=MyCountries, default='DE')
    postal_code = models.CharField(max_length=8, null=True, blank=True)

    date_from = models.DateField()
    date_to = models.DateField()

Based on Advertiser, position, type country and postal code this stores adverisements with range date_from and date_to.
advertiser, position, share_type, country and postal_code

are coming from the request and are fetched in
class CreateAdvertisment(LoginRequiredMixin, CreateView):

    # Some usefull stuff

    def dispatch(self, request, *args, **kwargs):

        self.advertiser = Advertiser.objects.get(user=self.request.user)
        self.share_type = self.kwargs.get('share_type', None)
        self.country = self.kwargs.get('country', None)
        self.postal_code = self.kwargs.get('postal_code', None)
        self.position = int(self.kwargs.get('position', None))
        self.position_verbose = verbose_position(self.position)

        ret = super(CreateAdvertisment, self).dispatch(request, *args, **kwargs)

        return ret

Without any validation for checking date_from, date_to. I can simply do
def form_valid(self, form):

    form.instance.advertiser = self.advertiser
    form.instance.share_type = self.share_type
    form.instance.country = self.country
    form.instance.postal_code = self.postal_code
    form.instance.position = self.position

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

and I am done. Unfortunatly I cannot do this as I do have to check for valid time Frames for the Advertisment to avoid Double Bookings of the same time. I do this in the model with the following :
def clean(self):
    ret = super(Advertisement, self).clean()
    print ("country [%s] position [%s] share_type [%s] postal_code [%s]" % (self.country,
           self.position, self.share_type, self.postal_code))
    if self.between_conflict():
        raise ValidationError("Blocks between timeframe")
    elif self.end_conflict():
        raise ValidationError("End occupied")
    elif self.during_conflict():
        raise ValidationError("Time Frame complete occupied")
    elif self.start_conflict():
        raise ValidationError("Start Occupied")
    return ret

def start_conflict(self):

    start_conflict = Advertisement.objects.filter(country=self.country,
                                                  position=self.position,
                                                  share_type=self.share_type,
                                                  postal_code=self.postal_code).filter(
        date_from__range=(self.date_from, self.date_to))

    return start_conflict

This works well and I filter out any Conflict for the given period. Problem is that I do not have the instance variables as they are set in view.form_valid() and model.clean() is called by the form validation process.
I do have an chicken egg problem here. I am thinking about setting the requests parameters to the form kwargs in
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    kwargs['advertiser'] = self.advertiser
    kwargs['position'] = self.position
    ....

and then putting them into the form instance in form.init()
def __init__(self, *args, **kwargs):
    advertiser = kwargs.pop('advertiser')
    position = kwargs.pop('position')
    # .. and so on
    super(AdvertismentCreateForm, self).__init__(*args, **kwargs)

For some reasons I do not think this is very pythonic. Does anybody have a better idea? I will post my solution.

A: I think that overriding get_form_kwargs is ok. If all the kwargs are instance attributes, then I would update the instance in the get_form_kwargs method. Then you shouldn't have to override the form's __init__, or update the instance's attributes in the form_valid method.
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()
    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()
    kwargs['instance'].advertiser = self.advertiser
    ...
    return kwargs

In the model's clean method, you can now access self.advertiser.

A: alasdairs proposal works fine I have the following now :
def get_form_kwargs(self, **kwargs):
    kwargs = super(CreateAdvertisment, self).get_form_kwargs()

    if kwargs['instance'] is None:
        kwargs['instance'] = Advertisement()

    kwargs['instance'].advertiser = self.advertiser
    kwargs['instance'].share_type = self.share_type
    kwargs['instance'].country = self.country
    kwargs['instance'].postal_code = self.postal_code
    kwargs['instance'].position = self.position

    return kwargs

def form_valid(self, form):

    ret = super(CreateAdvertisment, self).form_valid(form)
    return ret

Of course there is no need to override form_valid anymore. I have just included here in order to display that we do not set the instance fields anymore as this is done in get_form_kwargs() already


Q: How to check if items repeat in pandas column with multiple lists? I have this pandas df:
                                               Name
0                      [MARCIO, HAMILTON, FERREIRA]
1                    [NILSON, MARTINIANO, FERREIRA]
2                         [WALTER, MALIENI, JUNIOR]
3                  [CARLOS, ALBERTO, ARAUJO, NETTO]

If one of the items appear in another list I want to tag it. In this case the output should be like this:
                                               Name       Check
0                      [MARCIO, HAMILTON, FERREIRA]        True
1                    [NILSON, MARTINIANO, FERREIRA]        True
2                         [WALTER, MALIENI, JUNIOR]       False
3                  [CARLOS, ALBERTO, ARAUJO, NETTO]       False

Is there a pythonic way to do that or I will need to apply a set of for sentences? (for i in object: for k in list...). Since my file is quite large I'm afraid it will be very heavy.

A: We can do explode then do transform with nunqiue find the index duplicated with same value
s=df.Name.explode().reset_index()
v=(s.groupby('Name')['index'].transform('nunique')>1).groupby(s['index']).any()
Out[465]:
index
0     True
1     True
2    False
3    False
Name: index, dtype: bool
df['Check']=v

A: Similar to Ben's answer but using duplicated instead of groupby().nunique():
s = series.explode().reset_index()
df['Check'] = (s.drop_duplicates()
                .duplicated('Name', keep=False)
                .groupby(s['index']).any()
              )

Output:
                               Name  Check
0      [MARCIO, HAMILTON, FERREIRA]   True
1    [NILSON, MARTINIANO, FERREIRA]   True
2         [WALTER, MALIENI, JUNIOR]  False
3  [CARLOS, ALBERTO, ARAUJO, NETTO]  False


Q: how to reload the current page when twitter bootstrap modal's cancel button clicked? Is it possible to reload/refresh the current page when clicking on the twitter bootstarp modal popup window?

A: Assuming you're using the standard Bootstrap modal markup, you could handle the modal 'hidden' event like this..
$('#myModal').on('hidden', function () {
  document.location.reload();
})

Demo: http://www.bootply.com/62174

A: For BS3 it Should be something like
$('body').on('hidden.bs.modal', '.modal', function () {
   document.location.reload();
});


Q: How to logging all queries after execution in codeigniter? I have try to insert all codeigniter queries after execute the mysql query. Unable to insert all query anyone can help me resolve this issue

A: Try this for logging specific query in log file:
Create a logFile.log file then write your query in this file.
$sql_query = "insert into tablename (column1, column2) values(value1, value2)";
file_put_contents('logFile.log', json_encode($sql_query , true), FILE_APPEND);

Hope this will help you a bit.
Or you can follow the duplication question here: logging all queries after execution in codeigniter