text:
Q: How is sort for std::deque implemented? Not so far I've learned how std::deque is implemented under the hood, and discovered that it's something like an array of pointers to n-byte arrays, where the data is actually stored. So now I have a couple of questions related to deques.
A picture that describes my current knowledge about it's structure:
The questions are:

*

*When a push_front operation is being performed and there is no free space in Data Block 0, a new Data Block is allocated on heap and a pointer to this freshly allocated memory is inserted into 'Map' array like in ordinary array -- in O(number_of_blocks) time, yes?

*How to sort this beast? Can't imagine anything better then copy all the data into array, sort it, and then put it back. But this approach requires O(n) auxiliary memory... But! std::sort provides similar interface for sorting both std::vector and std::deque. How are different algoritms for different data structures implemented? Using a template specialization? If so, why std::list can't be sorted using std::sort?
Or, maybe, std::sort doesn't care about internal structure of this containers and just uses iterators and methods, that are similar in both std::vector and std::deque (like operator[], size(), etc)? This idea sounds reasonable and an answer to "why can't std::sort sort std::list?" becomes evident.

*How are the sizes of data blocks being chosen? You'll say "It's implementation dependent", but please tell more about different implementations and motivation behind solutions.
Need clarifications here.
Thanks.

A: To answer to your first question, yes, that's pretty much how it works. One can note that this approach can be extended into a multi-level hierarchical structure. But practical implementations usually stick to two-level structure, exactly as shown in your picture.
For your second question, if you  are talking about std::sort, then std::sort works without any knowledge about the mechanics of the actual container. If works on a range of random-access iterators. Since std::deque's iterators are random-access iterators, std::sort can be applied to std::deque. And one can actually argue that random access to elements of such data structure is rather efficient. It is not as efficient as random access in a vector, but it is still pretty efficient to make sense in the context of std::sort.
You cannot use std::sort with std::list because std::list's iterators are not random access iterators. If you wish, you can implement your own trivial (slow) version of random-access iterator for std::list. You will be able to apply std::sort to a range of such iterators and thus sort an std::list with std::sort. But for obvious reasons it will be prohibitively inefficient.
In case of std::deque random access iterators are more than adequately efficient.
I'm not prepared to answer the third question. In fact I wouldn't be surprised to find out that these sizes are chosen empirically, based on a bunch of experiments. And, of course, there's probably no "one size fits all" solution.


text:
Q: Python Numpy unknown Syntax Error while defining function I'm creating a non-visual tic tac toe game with numpy, and I have no idea what is wrong with this:
def possibilities(board):
    un_occupied = np.where(board == 0)
    return list(zip(not_occupied[0], not_occupied[1]))

possibilities(board)

The Error:
File "", line 5
    possibilities(board):
                         ^
SyntaxError: invalid syntax

A: The example code you have provided has perfect syntax. The error is being triggered by some other part of your code before the line 5. Check the lines 1-4 for any mistakes.
For example, the following piece of code would return syntax error similar to yours. Notice that the mistake is on the first line, where the print-function does not have a closing bracket. A good text editor will highlight the bug at the correct location.
print(
def foo(bar):
    return bar

output:
File "test.py", line 2
  def foo(bar):
  ^
SyntaxError: invalid syntax

redpajama_set_name: RedPajamaStackExchange


text:
Q: conditional iterators in Python: How can I pick out a particular iteration? In django templates I accomplish this with {% if forloop.first %} but im not sure how to do this in regular 'ole python without writing a clunky counter to count up as my conditional iterates. Is their an easy way out?

A: Take a look at enumerate.

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series ...

>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
...     print i, season
0 Spring
1 Summer
2 Fall
3 Winter


text:
Q: Parallel.ForEach Error showing dbcontext this method - doDayBegin(item.BranchId) is taking long time to execute. so i am using Parallel.ForEach to execute it parallel. when i am using normal foreach loop its working fine but when i am using Parallel.ForEach it showing this error

The context cannot be used while the model is being created  Parallel.ForEach
 public ActionResult Edit([DataSourceRequest] DataSourceRequest request)
        {
            try
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                List<DB0010020Vm> _listDB0010020Vm = new List<DB0010020Vm>();

                string dataDB0010020vm = Request.Form["griddetailsvm"];
                if (!string.IsNullOrEmpty(dataDB0010020vm))
                {
                    _listDB0010020Vm = js.Deserialize<List<DB0010020Vm>>(dataDB0010020vm).
                    Where(d => d.IsValid == "YES").ToList();
                }
                DateTime start = DateTime.UtcNow;

                Parallel.ForEach(_listDB0010020Vm, item =>
                {
                    doDayBegin(item.BranchId);
                });

                DateTime end = DateTime.UtcNow;
                TimeSpan duration = end - start;
                return Json(new
                {
                    success = true,
                    message = "Day Begin Process Completed Successfully!" + duration
                });
            }
            catch (Exception e)
            {
                return Json(new
                {
                    success = false,
                    message = e.Message
                });

            }
        }

 public void doDayBegin(int BranchId)
        {

            using (var dbThread = new NeoSampleDBEntities()) // new db connection
            {

                EBS.DAL.Model.DB0010020 branchDetails = _idDB0010020Repository.FindOne(d => d.BranchId == BranchId);
            if (branchDetails == null)
            {
                ModelState.AddModelError("", "Branch not found!");
            }
            else
            {
                branchDetails.LastOpenDate = Convert.ToDateTime(Request.Form["LastOpenDate"]);

                OperationStatus status = _idDB0010020Repository.UpdateAndSave(branchDetails);
                if (status != null && !status.Status)
                    ModelState.AddModelError("Updation failed", status.ExceptionMessage);
            }

            EBS.DAL.Model.DB0010044 dayBegin = new DB0010044();
            dayBegin.BankId = 1;
            dayBegin.BranchId = BranchId;
            dayBegin.DayBeginFlag = 1;
            dayBegin.DayDate = Convert.ToDateTime(Request.Form["LastOpenDate"]);
            dayBegin.DayEndFlag = 0;
            dayBegin.DayEndStage = 1;
            dayBegin.DayReopenFlag = 0;
            OperationStatus status2 = _idDB0010044Repository.AddAndSave(dayBegin);
            if (status2 != null && !status2.Status)
                ModelState.AddModelError("Updation failed", status2.ExceptionMessage);
            else
            {
                CreateInwardSessionsForBranch(BranchId);
                CreateOutwardSessionsForBranch(BranchId);
            }
            }
        }

this is error

what will be the issue?

A: My guess it's that _listDB0010020Vm has not been calculated yet when the parallel.foreach is called.   If you step through the code in a standard non parallel foreach, it would show this by skipping the .where selection line,  going into the foreach, then when it needs the list value,  step next will show it jump back to the where selector.  I believe List.ToArray will force it to calculate.  Try paying that result to the parallel loop.

A: You create a new instance of the NeoSampleDBEntities DbContext in the doDayBegin method, but you use an existing (and as far as I can tell, single) instance of the repository _idDB0010020Repository, presumably encapsulating its own instance of DbContext or a pre-existing DbContext instance that was passed in on construction.
The error you're seeing is the result of a second thread's call to <repo>.FindOne making a DbContext method call while the model is being generated as a result of the first thread's call to <repo>.FindOne.  Even if the model creation finished, you'll more than likely run into conflicts as DbContext is not thread safe.
From what you've posed, my suggestion would be to create a new repo in the using statement of the doDayBegin method instead of a new instance of the NeoSampleDBEntities DbContext.


text:
Q: iPhone: problems with translucent black uistatusbar with view layout I am having some issues with my status bar.  This is an iPhone app, not an iPad app.  I would like to have a Black Translucent status bar everywhere in the app.
I have set the status bar style in the app plist.  It is set to black translucent.
My understanding is that when this is set, the layout of all the views will start at 0,0 and not 0,20 like it does when you have an opaque status bar.  This is why IB gives you the option to specify a hint of what sort of status bar you will be using so it can simulate it and display it correctly in IB.  (And yes ALL my views in IB are set to show a black translucent status bar).  The layout is done from 0,0 so that the status bar will overlay your view to show something through.  And in IB it works fine.  But in my app it does not.
My app is a tab bar based app and only one of the views looks correct, even though they are all set up the same. And to get that one view to work, I have to set the background view image to be at 0,-20 with the main view set to NOT clip subviews.  So it appears the layout with black translucent is not working right.    In addition, all my other tabs views are set the same way, NOT to clip subviews and the main background view set to 0,-20.  But only in the 1st tab does this actually "work".
Here are some pictures:
How it should look (but still having to set background to 0,-20):

Another tab, with the exact same settings, looks like this:
To make sure that it was a blacl translucent status bar without a background to overlay, I tried it with no background:
and an alternative background (alternative is straight blue and not with slight brushed effect):
Because the status bar on all three not working examples (no background, actual, and alternative) looks exactly the same, I assume the status bar is correct sort, black translucent, but with nothing behind it to show through.
Several of my tabs all have this problem, and all views that cycle through in the tab with a navigation controller, have this problem.  And they are all set the same as the "working" tab with "Clip Subviews" set to NO and the origin of the background set to 0,-20
I think the "working" one is not working but just looks like it is due to the negative offset in the background view.  I think it should actually be set to 0,0 and work.   But the main IB supplied view has its origin set to 0,20 and it is grayed out so I cannot change it.
Furthermore, I have another problem on one tab, a Settings tab where I use a different look and feel (more iPhone looking), the black translucent is not even taking effect.  I start with a programmatically constructed view and it shows a gray status bar:

And drilling down to nib backed views they look the same:
And the views are laid out as if it were a gray statusbar, down 20 pix (where they were set to black translucent in IB so I laid them out 20 pix higher)
I have tried setting the statusbar style programmatically in addition to the app plist entry but it had no effect (on any of these tabs).
I have been researching this (Google, stackoverflow, apple.com) for several weeks, off and on. but have found no indication of what I should be doing.
ETA:  wantsFullScreenLayout solved one of the questions, so I am marking this as solved.  I have opened a new question with updated issue on one of the two problems originally presented here, with new pics, description, etc and with more applicable title since the problem is not the uistatusbar itself.  The new question is at
new problem

A:
"My understanding is that when this is set, the layout of all the views will start at 0,0 and not 0,20 like it does when you have an opaque status bar."

Where did you get that? The frame of the application's window will stay exactly as it was, by default its at (0,0) and it will stay there - it doesn't care how the status bar looks.
Now the view controller's view, is another thing. By default their frame is set as the applicationFrame property of UIScreen (in other words, the bounds of the screen minus the area occupied by the status bar). That's why you can't get the background color to show behind the translucent status bar.
Try setting the wantsFullScreenLayout property to YES of each view controller that makes up your tab bar. It will bring the frame up to (0,0) as you need it to be.


text:
Q: I want to delete value from Firebase Realtime Databse by value i don't have it's key I want to  delete value from firebase realtime database by value I don't have it's key
I have database like:
-root
  |
   --fittingHeight
     |
      --"timeStamp1":"1.1"
     |
      --"timeStamp2":"2.1"

I want to delete 1.1 in this database but without key (timestamp1)

A: You need to query the collection and then order it by its key
 Query dbQuery = myRef.orderByKey();

Then you will need to add it a listener and use for loop on the results
dbQuery.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot dst : dataSnapshot.getChildren()){
            if(...)
                myRef.child(dst.getKey()).removeValue();
                    }
            }
       }

This will remove all the values in that key so if you want to remove a specific value inside that key, add another for loop on its results.

A:
I want to delete 1.1 in this database but without key (timestamp1)

There is no way you can use a query based on a property field which is dynamic. This is happening because, in order to delete a value, you need to know it's key.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("fittingHeight").orderByChild("timeStamp1").equalTo("1.1");

In Firebase Realtime Database there is no concept of wildcards. So you always need to specify the name of the property. It's true that you can get the content of the entire fittingHeight object and do the filtering on the client but this solution isn't practical at all. A solution might be to change the database schema to have fixed properties, in a way that the above query can work.


text:
Q: Windows Open file dialog search wildcards Using Windows 7 standard Open file dialog (e.g. IE9>Ctrl+O>Browse... or Excel>Ctrl+O or Firefox>Ctrl+O), it is possible to search for files within the current directory - using the File Name box and pressing ENTER, e.g.:
*.txt
*2012*xls
*20??-12*

Is this feature documented?
I cannot find any documentation for the wildcard syntax or any official (or unofficial) tutorial or tips&hints page to give a link to users.
I tried googling https://www.google.co.uk/search?q=windows+open+file+search and the like, but I only got:
- programming tips for OpenFileDialog (does not count as a user-friendly tutorial)
- windows search feature (different syntax than in open file dialog)
- tech support when this feature does not work
- forums with broken links

A: The use of ? and * as wildcards for matching file names is not new to Windows by any means. The wildcard matching algorithm used in Windows is based on that of MS-DOS, which of course inherited it from CP/M.
See for example Raymond Chen's article titled How did wildcards work in MS-DOS? for details.


text:
Q: How to understand Duhamel's principle? I have difficulty about the explanation of Duhamel's principle on my book. Here is what's written on my book:
Take wave equation as an example. Consider the equation:
\begin{cases}
\frac{\partial^2u}{\partial t^2} = a^2\frac{\partial^2u}{\partial x^2} + f(t,x) &t>0, -\infty < x < +\infty\\
u|_{t=0} = 0, \frac{\partial u}{\partial t}|_{t=0} = 0
\end{cases}
where $f(t,x)$ is the external force over a unit of mass of the string. $u(t,x)$ is the displacement at time $t$. By independent action principle, $u(t,x)$ is the summation of displacement $w(t,x;\tau)d\tau$ caused by the impulse $f(\tau, x)d\tau\ (0\leq\tau\leq t)$, thus $u(t,x) = \int_{0}^{t}w(t,x;\tau)d\tau$. Clearly, when $t<\tau$, $w(t,x;\tau) \equiv 0$. When $t>\tau$, the instantaneous impulse at time $\tau$ is the increase of momentum from $t=\tau-0$ to $t=\tau+0$. So $w(t,x;\tau)$ should satisfy the equation:
\begin{cases}
\frac{\partial^2w}{\partial t^2} = a^2\frac{\partial^2w}{\partial x^2} &t>\tau, -\infty < x < +\infty\\
w|_{t=\tau} = 0, \frac{\partial w}{\partial t}|_{t=\tau} = f(\tau,x)
\end{cases}
and
$$
u(t,x) = \int_{0}^{t}w(t,x;\tau)d\tau
$$
I checked that such $u$ is the solution to the inhomogeneous equation. But I just cannot understand the derivation of the Duhamel's principle. In the explanation, $w$ is also the displacement, its dimension is length. $\tau$ is the time. Why $u(t,x) = \int_{0}^{t}w(t,x;\tau)d\tau$? The dimension of $u$ becomes length times the time?
Actually I didn't quite understand other parts. Could anyone help me understand Duhamel's principle by explaining it in more detail?
Any help is appreciated!

A: *

*A linear system of DEs with higher time-derivatives can be converted to a linear system
$$u_t -Lu ~=~ f, \qquad u|_{t=0}~=~0, \tag{1}$$
of DEs with only first-order time derivatives by introducing more variables in the standard fashion, so it is enough to study the latter, cf. the Wikipedia page for Duhamel's principle.
Here the active variable $u$ is a velocity profile in spacetime $(t,x)$;  the external source $f$ is a force; and $L$ is a differential operator that only involves $x$. (Mass is set to 1 in this picture.)

*Instead of solving the inhomogeneous problem (1), we can solve the corresponding homogeneous problem
$$ w_t -Lw ~=~ 0, \qquad w|_{t=s}~=~f|_{t=s} ,\tag{2}$$
for the acceleration profile $w$.
For fixed fiducial time $s$, the acceleration profile $w$ is the retarded solution, evaluated at time $t$, representing the effect, at the later time $t$, of an infinitesimal impulse $f ( x , s ) d s$   administered at an earlier time $s$.

*The velocity profile for the inhomogeneous problem (1) can be reconstructed as
$$u ~=~\int_0^t ds~w ,\tag{3}$$
because of the superposition principle for linear systems. One may check that eqs. (2) & (3) lead to a solution to (1).


text:
Q: Book about teenage boy who finds out he's part alien, is good at gymnastics and helps with an alien invasion Early 2000s is when I read it. The book was about a teenage boy who turns out to be part alien (I think). He was really good at gymnastics his eyes did this crazy dilating thing that would freak out his friend and he had a motorcycle by the end of the book. An invasion occurs and he finds out he's part alien.

A: That sounds like "Invasion America". David Carter, Earth teen, discovers he is the half alien son of an alien ruler that is on the run from a coup.  His human mom hid his father after he crashed landed on Earth, and they fell in love.    He was very good at gymnastics, and he also was given a a motorbike that was enhanced with alien technology so it could fly.  He also received a silver glove that was a weapon only usable by royalty, which gave him kind of telekinetic abilities.  It was actually a cartoon originally, but there was a novelization of it by Christie Golden in 1998.

A: I think you might be thinking of The Dark Side of Nowhere. Published by Neal Shusterman in 1997. The Protagonist is named Jason and he begins the story depressed over the recent death of his friend Ethan. Jason finds that Ethan is still alive but hiding because he is an alien who has lost his ability to maintain a human like form and goes on to find out that he, his family and many other people in his hometown are also aliens who were sent ahead of an invasion force.
The story uses the term "warrior fools" to refer to the aliens and "fragile people" to refer to the humans. The looming invasion that drives the plot is often referred to as the "ten thousand ships".
They also had gloves that functioned as energy weapons.
https://en.wikipedia.org/wiki/The_Dark_Side_of_Nowhere
978-0-316-78907-3


text:
Q: How to return return object(s) that gives me document as well as reports details I have multiple documents and each document has multiple supporting reports. How do i return object(s) that provides me information of both document and the report
One solution is to return all the document objects and iterate over reports for each object (slow). What I am currently doing is returning document object and I have a separate page which loads onclick and returns the corresponding reports
models.py looks like this:
class Document(models.Model):
    code = models.CharField(max_length = 50)
    path = models.CharField(max_length = 500)
    date_of_submission = models.CharField(max_length = 50)
    type = models.CharField(max_length = 50)
    title = models.CharField(max_length = 200)
    department = models.CharField(max_length = 50)
    subject = models.CharField(max_length = 100)

 class Report(models.Model):
    document_code = models.ForeignKey(Document, on_delete = models.CASCADE)
    title = models.CharField(max_length = 200)
    path = models.CharField(max_length = 500)
    type = models.CharField(max_length = 50)

Expected:
object(s) that has information for both report objects and document object.

A: You can use ManyToManyField in your models.
Check this Link please.
 class Report(models.Model):
    document_code = models.ManyToManyField(Document)
...


text:
Q: Allow access only from mobile and tablet devices My client has very specific request. He wants to block all "classic" computers (desktop/notebook).
So if I access the website from iPhone, Android or tablet it displays everything (the different resolutions I can hadle via responsive design). But when somebody from Mac or Windows or Linux (I know that Android is also based on gnu/linux ;) ) access the web, he gets only a message that "this web is only for mobile devices"or something like taht.
But I am not sure how to "ban" mac os, win, linux etc.
Could javascript(jQuery) library e.g. Modernizr or other do such specific condition "just mobile devices"?
What about Windows 8 :(  ?
i am really thankful for any advice, because I have never had such request before?

A: I think you could do this in several ways.
Either you check via javascript, but then you if somebody would turn off javascript you would be screwed again because they could take a look at the website:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // some code..
}

or you could check it via modernizr, but I don't know exactly how to do it in modernizr and you would also have the problem of turned off javascript code,
or you could download a script that is suitable for your case via:
http://detectmobilebrowsers.com/
another thing you could do is checking the screen resolution but, then we are back at the javascript case.

A: According to MSDN, Windows adds Tablet PC to the browser user agent if it is a tablet.
I suggest not doing this via javascript, because as states above: if javascript is disabled, people will be able to visit your site.


text:
Q: Foreign Key reference in mysql innodb Simply put: I have a table with 2 columns: one is username and other is nickname.
I have another table where I have 2 columns: one is username and other is countNicknames.
I want countNicknames to contain the number of nicknames each user has (and whenever I insert a new nickname to the table1, the value under table2.countNicknames will automatically update.
Can you please write down how to construct the second table to reference the first one?

A: Why not just count when you need the value?

A: Well, @Lasse's suggestion is better, but ... there is two other another options...

*

*Does MySql have triggers?  If it does, then you would add an Insert, Update, Delete trigger on the first table that updates (or inserts or deletes as necessary)  the second table's CountNickNames attribute every time a record is inserted, Updated or deleted from the first table...
Create Trigger NickNameCountTrig On NickNameCountTable
  For Insert, Update, Delete
  As
     Update nct Set
        CountNickNames =
             (Select Count() From FirstTable
              Where Name = nct.Name)
     From NickNameCountTable nct
     Where Name In (Select Distinct Name from inserted
                    Union
                    Select Distinct Name From deleted)
     -- -----------------------------------------------
     Insert NickNameCountTable (Name, CountNickNames)
     Select name, count() from FirstTable ft
     Where Not Exists
          (Select * From NickNameCountTable
           Where Name = ft.Name)
     -- ------ This is optional -----------------------
     Delete NickNameCountTable
     Where CountNickNames = 0

*Does MySql have indexed views (or some equivilent)?  apparently not - so never mind this option ....

A:
I want countNicknames to contain the number of nicknames each user has (and whenever I insert a new nickname to the table1, the value under table2.countNicknames will automatically update.

This is effectively what a view will do.
CREATE OR REPLACE VIEW user_nickname_count AS
    SELECT t.username,
           COUNT(*) 'countNicknames'
      FROM TABLE t
  GROUP BY t.username

A view looks like a table, so you cah join to it if needed.  And the only overhead is that it effectively is just a SELECT query being run - the values are calculated on demand, rather than having to setup triggers.
For more info on views, see the documentation.


text:
Q: Difference between Active Model, Active Record and Active Resource Is there anyone who can help me by defining the exact difference between Active Model, Active Record and Active Resource. I have done enough googling in order to find the exact difference, but didn't get anything concrete which can tell the exact difference between them. Right now they all look same to me. So please give me the appropriate answer with some concrete points.

A: ActiveModel https://github.com/rails/rails/tree/master/activemodel
Think of a super model who is in constant need of validation.
ActiveModel can be used for many things, but mostly recognized for adding validation support to models / db records.

ActiveRecord https://github.com/rails/rails/tree/master/activerecord
Think record as in table record.
Sets up a mapping between a new class and an existing table in a database.
In the context of an app, these classes are commonly referred to as models. Models can also be connected to other models; this is done by defining associations.
  class Firm < ActiveRecord::Base
    has_many   :clients
    has_one    :account
    belongs_to :conglomerate
  end

In the background, rails uses ActiveRecord for schema management and defining properties for your records, acting as an ORM (object relational mapper):

"ORM: An object that wraps a row in a database table or view, encapsulates
  the database access, and adds domain logic on that data."

A schema outlines the properties for a record.

ActiveResource https://github.com/rails/activeresource
Think resource like the R in URL or of the resource routing that powers many rails backends.
Allows you to do things like Create, Retrieve, Update, or Destroy (CRUD) via HTTP.
  tyler = Person.find(1)

When a request is made to a resource route, a RESTful request maps itself its corresponding HTTP verbs and their database interactions
  GET    => Person.find(1)
  POST   => Person.new(:name => 'Tyler', :favorite_page => 'stackoverflow')
  PUT    => tyler.save
  DELETE => tyler.destroy

A: What I understand:
ActiveModel + Database Support = ActiveRecord
ActiveModel via WebService API = ActiveResource

A: Rails 3 is designed with modularity in mind.  Each module has its own purpose and functionality.
ActiveModel: This component was created in Rails 3.  They took all the model related parts that did not have a database requirement of Rails 2 ActiveRecord and moved it into ActiveModel.  So ActiveModel includes things like validations.  More information: http://www.rubyinside.com/rails-3-0s-activemodel-how-to-give-ruby-classes-some-activerecord-magic-2937.html
ActiveRecord: This is the component that associates a class to the database.  This will give the class functionality such as methods that make it easy to pull records from the database (An example is the find method).
ActiveResource: Similar to ActiveRecord.  However, instead of being backed by a database, an ActiveResource object is backed by another application through a web service API.  More information: http://ofps.oreilly.com/titles/9780596521424/activeresource_id59243.html
(Couldn't figure out about ActiveBase... where did you hear it from?)


text:
Q: processor usage (force full usage) First of all, I did not study computer science, and I teached programming my self, said that;
I have a C# program that runs heavy power flow simulations for very large demand profiles.
I use a laptop with an intel i7 processor (4 cores -> 8 threads) under windows 7.
When I run the simulations the processor ussage is arround 32%.
I have read other threads about process prority, and I have more or less clear that when something runs on the OS, it runs at full speed, but the OS keeps the interfaces responsive (is this correct?)
Well I want to "completely flood the processor" with the simulation; get a 100% of usage (if possible) ?
Thanks in advance.
Ref#1: Is there a way of restricting an API's processor resource in c#?
Ref#2: Multiple Processors and PerformanceCounter C#
EDIT: piece of code that calls the simulations after removing the non relevant stuff
while ( current_step < sim_times.Count ) {

    bool repeat_all = false;
    power_flow( sim_times[current_step] );

    current_step++;
}

I know it is super simple, and it is a while becausein the original code I may want to repeat a certain number of steps.
The power_flow() function calls a third party software, so I guess is this third party software the one that should do the multy threading, isn't it?

A: You can't really force full usage - you need to provide more work for the processor to do.  You could do this by increasing the number of threads to process more data in parallel.  If you provide your samples of your source code we could provide specific advice on how you could alter your code to achieve this.
If you are using a third party piece of software for data processing, this often makes it difficult to split into multiple threads.  One tactic that's often helpful is to split up your input data, then start a new thread for each data set.  This requires domain specific knowledge to know what you can split up.  For simulations, once you have split up one run as much as possible, an alternative is to process multiple runs in parallel.
The Task Parallel Library can be really useful to break down your code into multiple threads without much refactoring. Particularly the data parallelism section.
One big note of caution - you need to make sure what you're doing is thread-safe.  I'll provide some further reading for you.  The basic principal is that you need to made sure if you're sharing data between threads then you need to be very careful they don't affect one another - this can cause bizarre problems!
As for your question regarding interfaces - within your process you can allocate thread priority to each thread.  An interface thread is just a thread like any other.  Usually a UI thread is given the highest priority to remain responsive, whereas a long background process is given a normal/below normal priority as it can be processed during idle time. You can set the priority manually, the default for any new thread is Normal.

A: You should process these simulations in parallel so that you use as many CPUs as possible. Do this by creating a Task for each simulation run.
using System.Threading.Tasks;

...

List<Task> tasks = new List<Task>();

for(;current_step < sim_times.Count; current_step++)
{
    var simTime = sim_times[current_step]; //extract the sim parameter
    Task.Factory.StartNew(() => power_flow(simTime)); //create a 'hot' task - one that is immediately scheduled for execution
}

Task.WaitAll(tasks.ToArray()); //wait for the simulations to finish so that you can process results.

Data Parallelism (Task Parallel Library)


text:
Q: Factor $(a^2+b^2+c^2)^2-2(a^4+b^4+c^4)$ to get $(b+c-a) (a+b-c) (a-b+c) (a+b+c)$
Is there an easy way to factor $(a^2+b^2+c^2)^2-2(a^4+b^4+c^4)$ to get $(b+c-a) (a+b-c) (a-b+c) (a+b+c)$?

I have tried various methods such as completing the square, but I wasn't able to figure it out as it became very messy.

A: Expand and notice that it's "trying to be" $-(\pm a^2 \pm b^2 \pm c^2)^2$
for some choice of $\pm$ signs.  None of the sign choices quite works, but they're each off by a square, e.g.
$$
(a^2+b^2+c^2)^2-2(a^4+b^4+c^4) = 4a^2b^2 - (a^2+b^2-c^2)^2.
$$
So you can factor it as the difference of two squares, and then each factor is itself a difference of two squares and thus splits further into linear forms, giving the desired factorization.
Note that the factored form is within a constant factor $16$ of Heron's formula for the square of a triangle of side lengths $a,b,c$.

A: View the expression as a polynomial in $a$. Plug in $a=b+c$. If the polynomial vanishes $(b+c-a)$ is a factor of the polynomial. Repeat for other factors. As the degree of the polynomial is $4$, it can't have more than $4$ linear factors and you're done.
Note: This method is often used to factor multivariate polynomials and is only as good as your guess.


text:
Q: call multiple methods of local services I want to create an app wich connects to one server with an https connection from different activities. So I thought, it would make sense to use a service which holds the https connection and i would call it from different activities to get different sites from that server... But after searching a long time (and reading an android book) I didn't find out, how to call different methods of a service from an activity. (only way that seemed possible was aidl with .asInterface, but that never worked for me, as one can see in my other question)
Is there a good tutorial, how I can do this?
Thanks in advance,
Tyde

A: The way I would do this is to have one package that does the http calls, internally it may use  HTTPUrlConnection or AndroidHTTPClient, and throughout the codebase I will just call the helper methods (which I will write, basically wrapper methods) of this class/package to make the calls. Note that for me the http connections are either handled as subclasses of DataHandler to be run on seperate threads, or as async tasks, the point being we dont lock the main UI thread with it.
On a side note look at this blog post too. Android developer blog have good posts on this topic.
I havent seen http calls managed by a service, the Async task/Data Handler mechanism seems more simpler to me. Hope this helps.


text:
Q: Solution change from ASP.NET MVC 2 to? I have been working on an ASP.NET MVC 2 app similar to SQL MDS. The app which we call as ADMIN app is for implementors to setup non transactional customer data to bring them on board.
The app was however built for targetting a SQL DB on a single environment UAT/LIVE/QA etc. In a nutshell the app is deployed together with DB.
The new requirement is - app should target multiple DBs. In other words a customer data keyed in should be staged/migrated to UAT & subsequently to LIVE environment. This will ensure customer data does not have to be keyed in multiple times. This new requirement has caught me offguard.
I cannot go with single site targetting multiple DBs coz the environments are seggregated and no cross env network access is allowed. Which is fair.
Another approach I was thinking was to export the entitties objectgraph as a package (since I am using LINQ2SQL) to be imported into the next environment using serialize/deserialize. However I am afraid I might run into issues with IDs and referential integrity. Has anyone tried this?
As I use DI/IoC so the architecture is loosely coupled.  What other solutions could I try without much recourse to development efforts? Should I go with a Winform approach and mandate implementors to have network access to all the SQL servers?
Any thoughts will be very much appreciated...
Daks

A: If I understand your issue correctly, I think you could consider using ETL to transfer the data between different databases whenever it is updated.  Rhino ETL is a good tool for moving the data around.
Here is a link about usage and here is a link to the git repository.

A: Do all the databases have the same schema? If so, can't you simply change connection strings on the fly and connect to which ever database you need to?


text:
Q: How to disable the display of duplicate image? This is the script that collects all images uploaded to the page from wordpress admin panel and puts them in the slider.

Javascript
function setCurrent(first) {
    $('#current').html(first);
}

$(document).ready(function () {
    // set images to preview and remove big images
    $('#content').find('img').each(function () {

        var photoSrc = $(this).attr('src'),
            photoImg = '';

        $('#all-photos').append('
' + photoImg + '
');
        $(this).remove();
    }); // end each

    // set first image preview to current box
    var firstPhoto = $('#all-photos').find('div.photo-template:first').html()
    setCurrent(firstPhoto);

    // click handler
    $('div.photo-template').on('click', function () {
        var selected = $(this).html();
        setCurrent(selected);
    });
});

It works well, when I add few photos to a page (example http://beardhouse.com.ua/knizhka-divan/millenium), but when I add only one photo - it duplicates in to the box whith small images(example http://beardhouse.com.ua/beskarkasnue-mjagkie-divany/lado)
How to disable the display of duplicated image when it is only one image published on a page?

A: Try adding this to you Javascript, it should find the number of images in the bottom and then if it finds that there is more than 1, it will remove the container.
if($('#all-photos .photo-template img').length < 2) {
    $('#all-photos').hide();
}

Hope this helps.


text:
Q: what does this notation mean
If $p_1, p_2, ⋯, p_n$ are $n$ propositions, explain why
$$\bigwedge_{i=1}^{n-1}\bigwedge_{j=i+1}^n(\lnot{p_i}\lor\lnot{p_j})$$
is true iff at most one of $p_1, p_2, ⋯, p_n$ is true.

My questions are:

*

*the two continous $\wedge$ symbols looks strange,what does it mean

*what's the expansion of this notation

A: This is just like sigma notation. It means conjunction.
Like $$\sum_{i=0}^n a_i = a_0 + a_1 + a_2 + \dots + a_n$$ here we don't have addition but conjunction (and)
$$\bigwedge_{i=1}^{n} P_i = P_1 \wedge P_2 \wedge P_3 \wedge \dots \wedge P_n$$
For sums and products, the conventional notations Sigma ($\Sigma$) and Pi ($\Pi$) are used. For other associative operations, we just use upscaled versions of the operator.
Other such examples are: disjunction $\bigvee$, union $\bigcup$, intersection $\bigcap$, disjoint union $\bigsqcup$.

A: The first question had been well explained by @Stefan Octavian, for your second question:

*what's the expansion of this notation?

\begin{align}
&\bigwedge_{i=1}^{n-1}\bigwedge_{j=i+1}^n(\lnot{p_i}\lor\lnot{p_j})\\
\equiv&\bigwedge_{j=2}^n(\lnot{p_1}\lor\lnot{p_j})\land\dots\land\bigwedge_{j=n}^n(\lnot{p_{n-1}}\lor\lnot{p_j})\\
\equiv&\hspace{2.5ex}(\lnot{p_1}\lor\lnot{p_2})\land\dots\land(\lnot{p_1}\lor\lnot{p_n})\\
&\land(\lnot{p_2}\lor\lnot{p_3})\land\dots\land(\lnot{p_2}\lor\lnot{p_n})\\
&\hspace{8.5ex}\vdots\\
&\land(\lnot{p_{n-1}}\lor\lnot{p_n})
\end{align}
Now why this is true if and only if that at most one of $p_1,p_2,\dots,p_n$ is true?
Hint:
Suppose for $i\neq j$ in $\{1,2,\dots,n\}$ we have that both $p_i,p_j$ is true, then $(\lnot p_i\lor \lnot p_j)$ is false, and we know that any clause of a conjunction is false then the whole conjunction is false.
Similarly if the whole conjunction is false, then at least one clause must be false,   but for any clause $(\lnot p_i\lor \lnot p_j)$ to be false, it follows that $p_i,p_j$ are both true.
This would be the general idea of your proof.


text:
Q: Why are simple SELECTs on InnoDB 100x slower than on MyISAM? I have quite an annoying problem. I want to use INNODB as my main database engine and give up on MyISAM as I need the former for using galera-cluster for redundancy.
I copied (description follows) the newbb_post table to a new table called newbb_innopost and changed that to InnoDB. The tables currently hold 5,390,146 entries each.
Running these selects on a freshly started database (so no caching is involved at this point!) the database yields the following results (omitting the complete output, please note that I do not even ask the database to sort the results):

SELECT post.postid, post.attach FROM newbb_post AS post WHERE post.threadid = 51506;

.
.
| 5401593 |      0 |
| 5401634 |      0 |
+---------+--------+
62510 rows in set (0.13 sec)

SELECT post.postid, post.attach FROM newbb_innopost AS post WHERE post.threadid = 51506;
.
.
| 5397410 |      0 |
| 5397883 |      0 |
+---------+--------+
62510 rows in set (1 min 22.19 sec)

0.13 seconds to 86.19 seconds (!)
I am wondering why this is happening. I did read some answers here on Stackexchange involving InnoDB and some are suggesting increasing innodb_buffer_pool size to 80% of installed RAM. This won't solve the problem, that the initial query to a particular ID will take at least 50x longer and stalling the whole websever, queueing up connections and queries for the database. Afterwards the cache/buffer might kick in, but there are over 100.000 threads in this database, so it is very likely that the cache will never hold all the relevant queries to be served.
The queries above are simple (no joins), and all keys are used:

EXPLAIN SELECT post.postid, post.attach FROM newbb_innopost AS post WHERE post.threadid = 51506;
+------+-------------+-------+------+-----------------------------------------------+----------+---------+-------+--------+-------+
| id   | select_type | table | type | possible_keys                                 | key      | key_len | ref   | rows   | Extra |
+------+-------------+-------+------+-----------------------------------------------+----------+---------+-------+--------+-------+
|    1 | SIMPLE      | post  | ref  | threadid,threadid_2,threadid_visible_dateline | threadid | 4       | const | 120144 |       |
+------+-------------+-------+------+-----------------------------------------------+----------+---------+-------+--------+-------+

This is the MyISAM-Table:

CREATE TABLE `newbb_post` (
  `postid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `threadid` int(10) unsigned NOT NULL DEFAULT '0',
  `parentid` int(10) unsigned NOT NULL DEFAULT '0',
  `username` varchar(100) NOT NULL DEFAULT '',
  `userid` int(10) unsigned NOT NULL DEFAULT '0',
  `title` varchar(250) NOT NULL DEFAULT '',
  `dateline` int(10) unsigned NOT NULL DEFAULT '0',
  `pagetext` mediumtext,
  `allowsmilie` smallint(6) NOT NULL DEFAULT '0',
  `showsignature` smallint(6) NOT NULL DEFAULT '0',
  `ipaddress` varchar(15) NOT NULL DEFAULT '',
  `iconid` smallint(5) unsigned NOT NULL DEFAULT '0',
  `visible` smallint(6) NOT NULL DEFAULT '0',
  `attach` smallint(5) unsigned NOT NULL DEFAULT '0',
  `infraction` smallint(5) unsigned NOT NULL DEFAULT '0',
  `reportthreadid` int(10) unsigned NOT NULL DEFAULT '0',
  `importthreadid` bigint(20) NOT NULL DEFAULT '0',
  `importpostid` bigint(20) NOT NULL DEFAULT '0',
  `converted_2_utf8` int(11) NOT NULL,
  `htmlstate` enum('off','on','on_nl2br') NOT NULL DEFAULT 'on_nl2br',
  PRIMARY KEY (`postid`),
  KEY `threadid` (`threadid`,`userid`),
  KEY `importpost_index` (`importpostid`),
  KEY `dateline` (`dateline`),
  KEY `threadid_2` (`threadid`,`visible`,`dateline`),
  KEY `converted_2_utf8` (`converted_2_utf8`),
  KEY `threadid_visible_dateline` (`threadid`,`visible`,`dateline`,`userid`,`postid`),
  KEY `ipaddress` (`ipaddress`),
  KEY `userid` (`userid`,`parentid`),
  KEY `user_date` (`userid`,`dateline`)
) ENGINE=MyISAM AUTO_INCREMENT=5402802 DEFAULT CHARSET=latin1

and this is the InnoDB Table (it's exactly the same):

CREATE TABLE `newbb_innopost` (
  `postid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `threadid` int(10) unsigned NOT NULL DEFAULT '0',
  `parentid` int(10) unsigned NOT NULL DEFAULT '0',
  `username` varchar(100) NOT NULL DEFAULT '',
  `userid` int(10) unsigned NOT NULL DEFAULT '0',
  `title` varchar(250) NOT NULL DEFAULT '',
  `dateline` int(10) unsigned NOT NULL DEFAULT '0',
  `pagetext` mediumtext,
  `allowsmilie` smallint(6) NOT NULL DEFAULT '0',
  `showsignature` smallint(6) NOT NULL DEFAULT '0',
  `ipaddress` varchar(15) NOT NULL DEFAULT '',
  `iconid` smallint(5) unsigned NOT NULL DEFAULT '0',
  `visible` smallint(6) NOT NULL DEFAULT '0',
  `attach` smallint(5) unsigned NOT NULL DEFAULT '0',
  `infraction` smallint(5) unsigned NOT NULL DEFAULT '0',
  `reportthreadid` int(10) unsigned NOT NULL DEFAULT '0',
  `importthreadid` bigint(20) NOT NULL DEFAULT '0',
  `importpostid` bigint(20) NOT NULL DEFAULT '0',
  `converted_2_utf8` int(11) NOT NULL,
  `htmlstate` enum('off','on','on_nl2br') NOT NULL DEFAULT 'on_nl2br',
  PRIMARY KEY (`postid`),
  KEY `threadid` (`threadid`,`userid`),
  KEY `importpost_index` (`importpostid`),
  KEY `dateline` (`dateline`),
  KEY `threadid_2` (`threadid`,`visible`,`dateline`),
  KEY `converted_2_utf8` (`converted_2_utf8`),
  KEY `threadid_visible_dateline` (`threadid`,`visible`,`dateline`,`userid`,`postid`),
  KEY `ipaddress` (`ipaddress`),
  KEY `userid` (`userid`,`parentid`),
  KEY `user_date` (`userid`,`dateline`)
) ENGINE=InnoDB AUTO_INCREMENT=5402802 DEFAULT CHARSET=latin1

Server, with 32GB RAM:

Server version: 10.0.12-MariaDB-1~trusty-wsrep-log mariadb.org binary distribution, wsrep_25.10.r4002

If you need all of the innodb_ variables setting, I can attach that to this post.
Update:
I dropped ALL indexes apart from the primary index, afterwards the result looked like this:

.
.
| 5402697 |      0 |
| 5402759 |      0 |
+---------+--------+
62510 rows in set (29.74 sec)

EXPLAIN SELECT post.postid, post.attach FROM newbb_innopost AS post WHERE post.threadid = 51506;
+------+-------------+-------+------+---------------+------+---------+------+---------+-------------+
| id   | select_type | table | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
+------+-------------+-------+------+---------------+------+---------+------+---------+-------------+
|    1 | SIMPLE      | post  | ALL  | NULL          | NULL | NULL    | NULL | 5909836 | Using where |
+------+-------------+-------+------+---------------+------+---------+------+---------+-------------+
1 row in set (0.00 sec)

After this I just added one index back to the mix, threadid, the results were the following:

.
.
| 5402697 |      0 |
| 5402759 |      0 |
+---------+--------+
62510 rows in set (11.58 sec)

EXPLAIN SELECT post.postid, post.attach FROM newbb_innopost AS post WHERE post.threadid = 51506;
+------+-------------+-------+------+---------------+----------+---------+-------+--------+-------+
| id   | select_type | table | type | possible_keys | key      | key_len | ref   | rows   | Extra |
+------+-------------+-------+------+---------------+----------+---------+-------+--------+-------+
|    1 | SIMPLE      | post  | ref  | threadid      | threadid | 4       | const | 124622 |       |
+------+-------------+-------+------+---------------+----------+---------+-------+--------+-------+
1 row in set (0.00 sec)

Strange it is, that without any relevant indexes, the full scan only took 29 seconds compared to the 88 seconds using indexes (!).
With only one perfectly tailored index it is still taking 11 seconds by to complete - still far too slow for any real world usage.
Update 2:
I setup MySQL (5.5.38-0ubuntu0.14.04.1 (Ubuntu)) on another server with the exact same hardware configuration and exactly the same database/tables.
The results are nearly the same, first the MyISAM Table:

.
.
| 5401593 |      0 |
| 5401634 |      0 |
+---------+--------+
62510 rows in set (0.14 sec)

And this is the result of the InnoDB table

.
.
| 5397410 |      0 |
| 5397883 |      0 |
+---------+--------+
62510 rows in set (1 min 17.63 sec)

UPDATE 3:
the contents of my.cnf

# MariaDB database server configuration file.
#
# You can copy this file to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc_messages_dir = /usr/share/mysql
lc_messages = en_US
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1
#
# * Fine Tuning
#
max_connections     = 100
connect_timeout     = 5
wait_timeout        = 600
max_allowed_packet  = 16M
thread_cache_size       = 128
sort_buffer_size    = 4M
bulk_insert_buffer_size = 16M
tmp_table_size      = 32M
max_heap_table_size = 32M
#
# * MyISAM
#
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched. On error, make copy and try a repair.
myisam_recover          = BACKUP
key_buffer_size     = 128M
#open-files-limit   = 2000
table_open_cache    = 400
myisam_sort_buffer_size = 512M
concurrent_insert   = 2
read_buffer_size    = 2M
read_rnd_buffer_size    = 1M
#
# * Query Cache Configuration
#
# Cache only tiny result sets, so we can fit more in the query cache.
query_cache_limit       = 128K
query_cache_size        = 64M
# for more write intensive setups, set to DEMAND or OFF
#query_cache_type       = DEMAND
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# we do want to know about network errors and such
log_warnings        = 2
#
# Enable the slow query log to see queries with especially long duration
#slow_query_log[={0|1}]
slow_query_log_file = /var/log/mysql/mariadb-slow.log
long_query_time = 10
#log_slow_rate_limit    = 1000
log_slow_verbosity  = query_plan

#log-queries-not-using-indexes
#log_slow_admin_statements
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#report_host        = master1
#auto_increment_increment = 2
#auto_increment_offset  = 1
log_bin         = /var/log/mysql/mariadb-bin
log_bin_index       = /var/log/mysql/mariadb-bin.index
# not fab for performance, but safer
#sync_binlog        = 1
expire_logs_days    = 10
max_binlog_size         = 100M
# slaves
#relay_log      = /var/log/mysql/relay-bin
#relay_log_index    = /var/log/mysql/relay-bin.index
#relay_log_info_file    = /var/log/mysql/relay-bin.info
#log_slave_updates
#read_only
#
# If applications support it, this stricter sql_mode prevents some
# mistakes like inserting invalid dates etc.
#sql_mode       = NO_ENGINE_SUBSTITUTION,TRADITIONAL
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
default_storage_engine  = InnoDB
# you can't just change log file size, requires special procedure
#innodb_log_file_size   = 50M
innodb_buffer_pool_size = 20G
innodb_log_buffer_size  = 8M
innodb_file_per_table   = 1
innodb_open_files   = 400
innodb_io_capacity  = 400
innodb_flush_method = O_DIRECT
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

[mysqldump]
quick
quote-names
max_allowed_packet  = 16M

[mysql]
#no-auto-rehash # faster start of mysql but no tab completition

[isamchk]
key_buffer      = 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/

And the contents of the inno variables:

MariaDB [(none)]> SHOW VARIABLES LIKE 'inno%';
+-------------------------------------------+------------------------+
| Variable_name                             | Value                  |
+-------------------------------------------+------------------------+
| innodb_adaptive_flushing                  | ON                     |
| innodb_adaptive_flushing_lwm              | 10                     |
| innodb_adaptive_hash_index                | ON                     |
| innodb_adaptive_hash_index_partitions     | 1                      |
| innodb_adaptive_max_sleep_delay           | 150000                 |
| innodb_additional_mem_pool_size           | 8388608                |
| innodb_api_bk_commit_interval             | 5                      |
| innodb_api_disable_rowlock                | OFF                    |
| innodb_api_enable_binlog                  | OFF                    |
| innodb_api_enable_mdl                     | OFF                    |
| innodb_api_trx_level                      | 0                      |
| innodb_autoextend_increment               | 64                     |
| innodb_autoinc_lock_mode                  | 1                      |
| innodb_buffer_pool_dump_at_shutdown       | OFF                    |
| innodb_buffer_pool_dump_now               | OFF                    |
| innodb_buffer_pool_filename               | ib_buffer_pool         |
| innodb_buffer_pool_instances              | 8                      |
| innodb_buffer_pool_load_abort             | OFF                    |
| innodb_buffer_pool_load_at_startup        | OFF                    |
| innodb_buffer_pool_load_now               | OFF                    |
| innodb_buffer_pool_populate               | OFF                    |
| innodb_buffer_pool_size                   | 21474836480            |
| innodb_change_buffer_max_size             | 25                     |
| innodb_change_buffering                   | all                    |
| innodb_checksum_algorithm                 | innodb                 |
| innodb_checksums                          | ON                     |
| innodb_cleaner_lsn_age_factor             | high_checkpoint        |
| innodb_cmp_per_index_enabled              | OFF                    |
| innodb_commit_concurrency                 | 0                      |
| innodb_compression_failure_threshold_pct  | 5                      |
| innodb_compression_level                  | 6                      |
| innodb_compression_pad_pct_max            | 50                     |
| innodb_concurrency_tickets                | 5000                   |
| innodb_corrupt_table_action               | assert                 |
| innodb_data_file_path                     | ibdata1:12M:autoextend |
| innodb_data_home_dir                      |                        |
| innodb_disable_sort_file_cache            | OFF                    |
| innodb_doublewrite                        | ON                     |
| innodb_empty_free_list_algorithm          | backoff                |
| innodb_fake_changes                       | OFF                    |
| innodb_fast_shutdown                      | 1                      |
| innodb_file_format                        | Antelope               |
| innodb_file_format_check                  | ON                     |
| innodb_file_format_max                    | Antelope               |
| innodb_file_per_table                     | ON                     |
| innodb_flush_log_at_timeout               | 1                      |
| innodb_flush_log_at_trx_commit            | 1                      |
| innodb_flush_method                       | O_DIRECT               |
| innodb_flush_neighbors                    | 1                      |
| innodb_flushing_avg_loops                 | 30                     |
| innodb_force_load_corrupted               | OFF                    |
| innodb_force_recovery                     | 0                      |
| innodb_foreground_preflush                | exponential_backoff    |
| innodb_ft_aux_table                       |                        |
| innodb_ft_cache_size                      | 8000000                |
| innodb_ft_enable_diag_print               | OFF                    |
| innodb_ft_enable_stopword                 | ON                     |
| innodb_ft_max_token_size                  | 84                     |
| innodb_ft_min_token_size                  | 3                      |
| innodb_ft_num_word_optimize               | 2000                   |
| innodb_ft_result_cache_limit              | 2000000000             |
| innodb_ft_server_stopword_table           |                        |
| innodb_ft_sort_pll_degree                 | 2                      |
| innodb_ft_total_cache_size                | 640000000              |
| innodb_ft_user_stopword_table             |                        |
| innodb_io_capacity                        | 400                    |
| innodb_io_capacity_max                    | 2000                   |
| innodb_kill_idle_transaction              | 0                      |
| innodb_large_prefix                       | OFF                    |
| innodb_lock_wait_timeout                  | 50                     |
| innodb_locking_fake_changes               | ON                     |
| innodb_locks_unsafe_for_binlog            | OFF                    |
| innodb_log_arch_dir                       | ./                     |
| innodb_log_arch_expire_sec                | 0                      |
| innodb_log_archive                        | OFF                    |
| innodb_log_block_size                     | 512                    |
| innodb_log_buffer_size                    | 8388608                |
| innodb_log_checksum_algorithm             | innodb                 |
| innodb_log_compressed_pages               | ON                     |
| innodb_log_file_size                      | 50331648               |
| innodb_log_files_in_group                 | 2                      |
| innodb_log_group_home_dir                 | ./                     |
| innodb_lru_scan_depth                     | 1024                   |
| innodb_max_bitmap_file_size               | 104857600              |
| innodb_max_changed_pages                  | 1000000                |
| innodb_max_dirty_pages_pct                | 75                     |
| innodb_max_dirty_pages_pct_lwm            | 0                      |
| innodb_max_purge_lag                      | 0                      |
| innodb_max_purge_lag_delay                | 0                      |
| innodb_mirrored_log_groups                | 1                      |
| innodb_monitor_disable                    |                        |
| innodb_monitor_enable                     |                        |
| innodb_monitor_reset                      |                        |
| innodb_monitor_reset_all                  |                        |
| innodb_old_blocks_pct                     | 37                     |
| innodb_old_blocks_time                    | 1000                   |
| innodb_online_alter_log_max_size          | 134217728              |
| innodb_open_files                         | 400                    |
| innodb_optimize_fulltext_only             | OFF                    |
| innodb_page_size                          | 16384                  |
| innodb_print_all_deadlocks                | OFF                    |
| innodb_purge_batch_size                   | 300                    |
| innodb_purge_threads                      | 1                      |
| innodb_random_read_ahead                  | OFF                    |
| innodb_read_ahead_threshold               | 56                     |
| innodb_read_io_threads                    | 4                      |
| innodb_read_only                          | OFF                    |
| innodb_replication_delay                  | 0                      |
| innodb_rollback_on_timeout                | OFF                    |
| innodb_rollback_segments                  | 128                    |
| innodb_sched_priority_cleaner             | 19                     |
| innodb_show_locks_held                    | 10                     |
| innodb_show_verbose_locks                 | 0                      |
| innodb_sort_buffer_size                   | 1048576                |
| innodb_spin_wait_delay                    | 6                      |
| innodb_stats_auto_recalc                  | ON                     |
| innodb_stats_method                       | nulls_equal            |
| innodb_stats_on_metadata                  | OFF                    |
| innodb_stats_persistent                   | ON                     |
| innodb_stats_persistent_sample_pages      | 20                     |
| innodb_stats_sample_pages                 | 8                      |
| innodb_stats_transient_sample_pages       | 8                      |
| innodb_status_output                      | OFF                    |
| innodb_status_output_locks                | OFF                    |
| innodb_strict_mode                        | OFF                    |
| innodb_support_xa                         | ON                     |
| innodb_sync_array_size                    | 1                      |
| innodb_sync_spin_loops                    | 30                     |
| innodb_table_locks                        | ON                     |
| innodb_thread_concurrency                 | 0                      |
| innodb_thread_sleep_delay                 | 10000                  |
| innodb_track_changed_pages                | OFF                    |
| innodb_undo_directory                     | .                      |
| innodb_undo_logs                          | 128                    |
| innodb_undo_tablespaces                   | 0                      |
| innodb_use_atomic_writes                  | OFF                    |
| innodb_use_fallocate                      | OFF                    |
| innodb_use_global_flush_log_at_trx_commit | ON                     |
| innodb_use_native_aio                     | ON                     |
| innodb_use_stacktrace                     | OFF                    |
| innodb_use_sys_malloc                     | ON                     |
| innodb_version                            | 5.6.17-65.0            |
| innodb_write_io_threads                   | 4                      |
+-------------------------------------------+------------------------+
143 rows in set (0.02 sec)

The number of cores of the machine is 8, it's a
Intel(R) Xeon(R) CPU E3-1246 v3 @ 3.50GHz as of /proc/cpuinfo
One last note: Ran the queries with the indexes suggested by RolandoMYSQLDBA, and the queries took about 11-20s each.
I do want to point out that it is crucial for me (this is the main table of a bulletin board) that the first query about a threadid returns in less than a second, as there are more than 60.000 threads and google-bots constantly crawl these threads.

A: @RolandMySQLDBA has given the right hint to answer the question. The problem seems to lie in the query and that for the results to be given back, each of those fields has to be read (somehow from the database).
I dropped all indexes but the PRIMARY KEY, and inserted this new index:
ALTER TABLE newbb_innopost ADD INDEX threadid_visible_dateline_index (threadid,visible,dateline,userid,attach,ipaddress);
This link explains what happens here (covering index): The queried fields of the query which are postid,attach can now be extracted from the key itself. That saves checking the real data and using I/O to the hard disk.
All the queries now run with 0.00 seconds.. :)
Thanks a lot all for your help.
Edit: The actual underlying problem is not solved, I just circumvented it with this technique. InnoDB needs some serious fixing in this area.

A: YOUR QUERY
SELECT post.postid, post.attach FROM newbb_innopost AS post WHERE post.threadid = 51506;

At first glance, that query should only touches 1.1597% (62510 out of 5390146) of the table. It should be fast given the key distribution of threadid 51506.
REALITY CHECK
No matter which version of MySQL (Oracle, Percona, MariaDB) you use, none of them can fight to one enemy they all have in common : The InnoDB Architecture.

CLUSTERED INDEX
Please keep in mind that the each threadid entry has a primary key attached. This means that when you read from the index, it must do a primary key lookup within the ClusteredIndex (internally named gen_clust_index). In the ClusteredIndex, each InnoDB page contains both data and PRIMARY KEY index info. See my post Best of MyISAM and InnoDB for more info.
REDUNDANT INDEXES
You have a lot of clutter in the table because some indexes have the same leading columns. MySQL and InnoDB has to navigate through the index clutter  to get to needed BTREE nodes. You should reduced that clutter by running the following:
ALTER TABLE newbb_innopost
    DROP INDEX threadid,
    DROP INDEX threadid_2,
    DROP INDEX threadid_visible_dateline,
    ADD INDEX threadid_visible_dateline_index (`threadid`,`visible`,`dateline`,`userid`)
;

Why strip down these indexes ?

*

*The first three indexes start with threadid

*threadid_2 and threadid_visible_dateline start with the same three columns

*threadid_visible_dateline does not need postid since it's the PRIMARY KEY and it's embedded

BUFFER CACHING
The InnoDB Buffer Pool caches data and index pages. MyISAM only caches index pages.
Just in this area alone, MyISAM does not waste time caching data. That's because it's not designed to cache data. InnoDB caches every data page and index page (and its grandmother) it touches. If your InnoDB Buffer Pool is too small, you could be caching pages, invalidating pages, and removing pages  all in one query.
TABLE LAYOUT
You could shave of some space from the row by considering importthreadid and importpostid. You have them as BIGINTs. They take up 16 bytes in the ClusteredIndex per row.
You should run this
SELECT importthreadid,importpostid FROM newbb_innopost PROCEDURE ANALYSE();

This will recommend what data types these columns should be for the given dataset.
CONCLUSION
MyISAM has a lot less to contend with than InnoDB, especially in the area of caching.
While you revealed the amount of RAM (32GB) and the version of MySQL (Server version: 10.0.12-MariaDB-1~trusty-wsrep-log mariadb.org binary distribution, wsrep_25.10.r4002), there are still other pieces to this puzzle you have not revealed

*

*The InnoDB settings

*The Number of Cores

*Other settings from my.cnf
If you can add these things to the question, I can further elaborate.
UPDATE 2014-08-28 11:27 EDT
You should increase threading
innodb_read_io_threads = 64
innodb_write_io_threads = 16
innodb_log_buffer_size = 256M

I would consider disabling the query cache (See my recent post Why query_cache_type is disabled by default start from MySQL 5.6?)
query_cache_size = 0

I would preserve the Buffer Pool
innodb_buffer_pool_dump_at_shutdown=1
innodb_buffer_pool_load_at_startup=1

Increase purge threads (if you do DML on multiple tables)
innodb_purge_threads = 4

GIVE IT A TRY !!!

A: Although not directly applicable to @jollyroger because he already has the correct setting, but I got a major improvement changing the innodb_buffer_pool_size to 70% of my RAM as explained in Why is myisam slower than Innodb
First MyISAM was slow, but oke. Then InnoDB made things bad, similar to the 100x slower in this question and after changing the setting InnoDB got 10x faster then MyISAM.
My default setting was on 8MB which is far to little.

A: Based on your both the query and table it seems like you are selectikg data from a time-series table. As such, it may be that the query time is slow because you are inserting simultaneously?
If those two things are true, than may I suggest looking into ScaleDB as an alternative? You will still be on MariaDB, just (maybe) a more appropriate engine.
http://www.scaledb.com - Homepage
http://www.scaledb.com/download-form.php - our product

A: Both engines will run the query much faster with
INDEX(threadid, attach, postid)

This is because it will be a "covering" index, and will operate virtually the same way (using the index BTree).
Also, I will say that this is not possible for either engine on a "cold" server:
62510 rows in set (0.13 sec)

Please use SQL_NO_CACHE whenever running timings -- we don't want the Query cache to pollute the conclusions.
Another fast approach (regarless of I/O caching):
Use InnoDB, and change from PRIMARY KEY (postid) to
PRIMARY KEY(threadid, postid),
INDEX(postid)

The reason is that this will cause all the relevant rows to be adjacent, thereby requiring less I/O, etc.  The INDEX(postid) is to keep AUTO_INCREMENT happy.  Caveat:  This messes with all the secondary keys -- some will be faster, some will be slower.


text:
Q: javassist:javassist vs org.javassist:javassist What is the difference between the Maven artifacts
javassist:javassist and org.javassist:javassist
In my project I've the first dependency with version 3.8 where as the second one I've introduced to resolve (StackMap verify)issues with powermock, as part of java 7 migration from 6 . The second dependency has latest of 3.18 version only. I still can't resolve my issues, but want to know the real difference between these two.
I've googled it but couldn't find any explanation. I hope it's not a duplicate question.
Thanks.

A: According maven group id naming convention group names should starts from domain name, so guys who develop javaassist changed group name in 3.13.0 release.
Versioning was naturaly continued after 3.12.1 release from 3.13.0.
Changes was done in r562 by adinn with comment:

r562 | adinn | 2010-07-22 12:32:26 +0300 (Thu, 22 Jul 2010) | 1 line
modified group id to org.javassist to keep the Sonatype repo people
  happy -- fixes for JASSIST-96

Link to JASSIST JIRA.


text:
Q: flattening json with mulitple nested lists I have a json with nested lists @ "ManyActionDateTimes" and @ "Comments" like this:
jframe = [{"LoadRef": 0,
            "BookedDate": "2021-10-13T01:15:54.287Z",
            "EndDateTime": "2021-10-13T01:15:54.287Z",
            "Duration": "string",
            "Mp": true,
            "ManyActionDateTimes": [
            {
            "EventTime": "2021-10-13T01:15:54.287Z",
            "Type": "string",
            "Vehicle": "string"
            }
            ],
            "Finished": true,
            "Comments": [
            {
            "Comment": "string",
            "DateInserted": "2021-10-13T01:15:54.287Z"
            }
            ],
            "Company": "string",
            "SiteCode": 0,
            "Source": "string"
            }]

i'm trying to flatten this into a dataframe, i know for one nested list i can use the 'record_path' argument but it doesnt work for multiples as when i use the code:
cols = []
[d] = jframe
drop = ['Comments','ManyActionDateTimes']
for k, v in d.items():
    if k in drop:
        pass
    else:
        cols.append(k)

jdf = pd.json_normalize(jframe,
record_path=['Comments','ManyActionDateTimes'],meta=cols, errors='ignore')

i get the error 'KeyError: 'ManyActionDateTimes':
KeyError: 'ManyActionDateTimes'
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-33-55851049e36a> in <module>
      4     cols.append(k)
      5
----> 6 jdf = pd.json_normalize(jframe,
      7 record_path=['Comments','ManyActionDateTimes'],meta=cols, errors='ignore')
      8 #meta=[:], errors='ignore')

C:\ProgramData\Miniconda3\lib\site-packages\pandas\io\json\_normalize.py in _json_normalize(data, record_path, meta, meta_prefix, record_prefix, errors, sep, max_level)
    502                 records.extend(recs)
    503
--> 504     _recursive_extract(data, record_path, {}, level=0)
    505
    506     result = DataFrame(records)

C:\ProgramData\Miniconda3\lib\site-packages\pandas\io\json\_normalize.py in _recursive_extract(data, path, seen_meta, level)
    472                         seen_meta[key] = _pull_field(obj, val[-1])
    473
--> 474                 _recursive_extract(obj[path[0]], path[1:], seen_meta, level=level + 1)
    475         else:
    476             for obj in data:

C:\ProgramData\Miniconda3\lib\site-packages\pandas\io\json\_normalize.py in _recursive_extract(data, path, seen_meta, level)
    475         else:
    476             for obj in data:
--> 477                 recs = _pull_records(obj, path[0])
    478                 recs = [
    479                     nested_to_record(r, sep=sep, max_level=max_level)

C:\ProgramData\Miniconda3\lib\site-packages\pandas\io\json\_normalize.py in _pull_records(js, spec)
    397         if has non iterable value.
    398         """
--> 399         result = _pull_field(js, spec)
    400
    401         # GH 31507 GH 30145, GH 26284 if result is not list, raise TypeError if not

C:\ProgramData\Miniconda3\lib\site-packages\pandas\io\json\_normalize.py in _pull_field(js, spec)
    388                 result = result[field]
    389         else:
--> 390             result = result[spec]
    391         return result
    392

KeyError: 'ManyActionDateTimes'

and none of my other solution attempts have worked either and im out of ideas,
many thanks

A: You can use this instead:
df = pd.json_normalize(jframe)
df = df.join(df['ManyActionDateTimes'].explode().apply(pd.Series)).join(df['Comments'].explode().apply(pd.Series))
df.drop(columns=['ManyActionDateTimes', 'Comments'], inplace=True)

Output:
LoadRef                BookedDate               EndDateTime Duration    Mp  Finished Company  SiteCode  Source                 EventTime      Type  Vehicle Comment              DateInserted
0        0  2021-10-13T01:15:54.287Z  2021-10-13T01:15:54.287Z   string  True      True  string         0  string  2021-10-13T01:15:54.287Z  string  string  string  2021-10-13T01:15:54.287Z

A: flatten_json works well with nested json structures
from flatten_json import flatten
dic_flattened = (flatten(d, '.') for d in jframe)
df = pd.DataFrame(dic_flattened)

Output
   LoadRef                BookedDate               EndDateTime Duration    Mp ManyActionDateTimes.0.EventTime  ... Finished Comments.0.Comment   Comments.0.DateInserted Company SiteCode  Source
0        0  2021-10-13T01:15:54.287Z  2021-10-13T01:15:54.287Z   string  True        2021-10-13T01:15:54.287Z  ...     True             string  2021-10-13T01:15:54.287Z  string        0  string

[1 rows x 14 columns]


text:
Q: Ajax SOAP Cross Domain 'POST' bad request 400 I was stuck on below the 'soapRequest', I try to test my netbeans connect cross domain access but keep on failing, anyone can help me point out my mistake?
Add on, I installed 'Allow-Control-Allow-Origin' on my google chrome browser and also tried to browser poster plugin to test the 'get' and 'post' are work.
function submitLogIn(username, passw) {
    var userId = document.getElementById(username).value;
    var userPass = document.getElementById(passw).value;

    var soap1 = '<soap:Envelope ';
    var soap2 = 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ';
    var soap3 = 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ';
    var soap4 = 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> ';
    var soap5 = '<soap:Body> ';
    var soap6 = '<Login xmlns="S2Ed"> ';
    var soap7 = '<userid>' + userId + '</userid> ';
    var soap8 = '<password>' + userPass + '</password> ';
    var soap9 = '</Login>';
    var soap10 = '</soap:Body>';
    var soap11 = '</soap:Envelope>';
    var soapMessage = soap1 + soap2 + soap3 + soap4 + soap5 + soap6 + soap7 + soap8 + soap9 + soap10 + soap11;

    // Call + ing......
    CallAjax(soapMessage);
}

function CallAjax(soapMessage) {
    console.log(soapMessage.toString());

    $.support.cors = true;
    $.ajax({
        type: 'POST',
        url: http://localhost:5566/Test.svc,
        // contentType: 'application/soap+xml',
        // content-Type: 'text/plain',
        contentType: 'text/xml; charset=utf-8',
        async: true,
        dataType: 'xml',
        crossDomain: true,
        // processData: false,
        headers: {
            SOAPAction: 'S2Ed/App/Login'
        },
        data: soapMessage,
        success: function (soapResponse) {
            console.log(soapResponse);
            console.log(soapResponse.toString());
            console.log(soapResponse.toJSON());
            console.log(soapResponse.toXML());
        },
        error: function (soapResponse) {
            alert("Failed SOAP ");
        }
    });
}

Below is the error message
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/. (15:39:52:688 | warning, deprecation)
  at public_html/js/jquery-1.11.3.min.js:5
Failed to load resource: the server responded with a status of 400 (Bad Request) (15:39:58:281 | error, network)
  at http://localhost:5566/Test.svc
XMLHttpRequest cannot load http://localhost:5566/Test.svc. Invalid HTTP status code 400 (15:39:58:282 | error, javascript)
  at public_html/index.html

A: Error 400 usually means you submitted something to the server which the server does not like. I.e submitting the name in the age field, etc
To add on, it might be possible that your request xml is wrong. Can you print it in console and see if it's a valid xml?


text:
Q: GNU Make | How to create dependency between source code hierarchy and compiler output h-hy? Some code from Makefile:
tempDir := ...
javaSources := $(wildcard src/java/**/%.java)
javaClasses := $(subst src/java, $(tempDir)/java/classes, $(subst .java,.class, $(javaSources)))

$(javaClasses): $(javaSources)
  mkdir -p $(tempDir)/java/classes || true
  javac \
    -d  $(tempDir)/java/classes \
    -cp $(tempDir)/java/classes \
  $?

How to create a pattern rule (like here) to preserve in / out order?
@MadScientist

A: First, your wildcard won't work.  GNU make uses only basic shell globbing, which means it can't understand advanced globbing like ** meaning "search all subdirectories".  Second, % is not a shell globbing character at all so you're just looking for files that are literally named %.java.
Instead you probably want something like this:
javaSources := $(shell find src/java -name '*.java')

Next, to create the javaClasses content you really don't want to use subst because it substitutes everywhere which can give false matches (e.g., $(subst .x,.y,foo.xbar) will yield foo.ybar which is probably not what you want).
Something like this is simpler to understand:
javaClasses := $(patsubst src/java/%.java,$(tempdir)/java/classes/%.class,$(javaSources))

Finally, you are repeating exactly the same error you made in the previous question, where you tried to list all the targets and all the prerequisites in the same rule.  Just as I said for that question, that is not right.
The answer is exactly the same as in the previous question: you should write a pattern rule that describes how to build one single target from one single source file.
And again you need an all target or similar which depends on all the outputs.

A: In complement to MadScientist answer, you should probably use a pattern rule like:
$(tempDir)/java/classes/%.class: src/java/%.java
    mkdir -p $(dir $@)
    javac -d $(dir $@) -cp $(dir $@) $<

(not sure what -cp should be in this case, it depends on your specific project). And as MadScientist also suggested, you will need:
.PHONY: all
all: $(javaClasses)

such that you can call make all to compile all the source files that need to be. Put it before any other explicit target if you want all to be the default goal (the goal make selects if you just call make), or use the .DEFAULT_GOAL special variable:
.DEFAULT_GOAL := all


text:
Q: Android background bitmap crop I have a background png in my Android application. I would like to support lots of displays, but I have this one obstacle - many displays have many resolutions and many ratios. I would like to make sure my background is displayed properly and make it more ellegant, than just creating 10+ cropped png files in Photoshop.
My idea would be - a fairly large picture imported in the project. The app would find out screen dimensions and simply say starting points(x,y) and ending points, that would "crop" the picture and display it without any deformations.
Is there a way of doing it?

A: I think bitmap.createBitmap() is the method your looking after. The method simply lets you cut out a defined portion of the bitmap.


text:
Q: JavaCV capture a frame using FFmpeg I create a class that capture frame from a video. When it capture a frame, it's saved as a picture. When the video is .avi, application works ok. When format is .avi.
public static void main(String[] args) {

     FFmpegFrameGrabber grabber = new FFmpegFrameGrabber("C:/Users/Ioanna/Desktop/video1.avi");

     try {
         IplImage img;

         //Start grabber to capture video
         grabber.start();

         //grab video frame to IplImage
         img = grabber.grab();

         if (img != null) {
             //save video frame as a picture
             cvSaveImage("capture.jpg", img);
         }

     }catch (Exception e) {
     }
}

The error is
Exception in thread "main" java.lang.ExceptionInInitializerError
    at com.googlecode.javacv.FFmpegFrameGrabber.<init>(FFmpegFrameGrabber.java:106)
    at Video.main(Video.java:75)
Caused by: java.lang.IllegalStateException: Can't overwrite cause with java.lang.UnsatisfiedLinkError: no avcodec in java.library.path
    at java.lang.Throwable.initCause(Throwable.java:457)
    at com.googlecode.javacpp.Loader.load(Loader.java:581)
    at com.googlecode.javacpp.Loader.load(Loader.java:532)
    at com.googlecode.javacv.cpp.avcodec.<clinit>(avcodec.java:39)
    ... 2 more
Caused by: java.lang.UnsatisfiedLinkError: no jniavcodec in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1837)

Do anyone know what is the problem?
Thanks in advance

A: After searching the web for quite some time, I came to the following solution:
Step 1: Download the .zip file "javacv-0.6-cppjars.zip" from
https://code.google.com/p/javacv/downloads/list and unzip it.
Step 2: Add "ffmpeg-20130915-git-7ac6c63-windows-x86_64.jar" file to your Java project!


text:
Q: Spring support for Maven2 WebApps I can create a minimal web application by using the maven-archetype-webapp .
Now I want to make my webapp Spring-Web-MVC powered.
Can I directly modify my POM, and how?
What's the best practices for the folder structure, and so on?
Can you show me a spring web mvc archetype, or a hello world example?

A: Maven Overlays document describes in great detail how web application should be structured using Maven. Here you'll find my simple Spring MVC showcase (REST-oriented).
Of course you are allowed to modify pom.xml (if the file is so complicated that users are afraid to modify it, then there must be something wrong with Maven...)
The only Spring-specific convention is to place general applicationContext.xml file under /WEB-INF - but this can be easily overridden.

A: The STS (Spring Source Tool Suite) ships with the Spring Template Project, this project wizard will create a simple Spring MVC webapp + maven support.
Hope this helps
You can refer the step-by-step instructions, under the below link.
http://webapptutorials.wordpress.com/category/spring-mvc/

A: You may also want to look using appfuse to bootstrap your spring-mvc application.


text:
Q: Undefinex Index id PHP mySQL phpMyAdmin Hello I am currently having an issue with my website, I have a basic list of Todo's that are accessed from phpMyAdmin database and I keep getting errors like this.. I cannot find a solution since I don't know what variable should be there
Notice: Undefined index: ID in C:\Users\User1\Downloads\COMP1006-W2017-MidTerm\COMP1006-W2017-MidTerm\index.php on line 59
Notice: Undefined index: todolistID in C:\Users\User1\Downloads\COMP1006-W2017-MidTerm\COMP1006-W2017-MidTerm\book_details.php on line 8
I have included a link to my github so you can see the files as they are. Any help is greatly appreciated (Don't worry about it being called Midterm, I simply am using a file I got working with another database and I am trying to replicated the results
https://github.com/AlexandreMelano/COMP1006-MidTerm-200249154
<?php
include_once('database.php'); // include the database connection file

/*//////////////////////*/
/* YOUR CODE GOES HERE */
/*/////////////////////*///
$todolistID = $_GET["todolistID"]; // assigns the gameID from the URL
echo $todolistID;
if($todolistID == 0) {
    $todolist = null;
    $isAddition = 1;
} else {
    $isAddition = 0;
    $query = "SELECT * FROM todolists WHERE Id = :todolist_id "; // SQL statement
    $statement = $db->prepare($query); // encapsulate the sql statement
    $statement->bindValue(':todolist_id', $todolistID);
    $statement->execute(); // run on the db server
    $book = $statement->fetch(); // returns only one record
    $statement->closeCursor(); // close the connection
}
?>

next page

<?php
include_once('database.php');

$query = "SELECT * FROM todolists"; // SQL statement
$statement = $db->prepare($query); // encapsulate the sql statement
$statement->execute(); // run on the db server
$todolists = $statement->fetchAll(); // returns an array
$statement->closeCursor(); // close the connection
?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Book List</title>

    <link rel="stylesheet" href="./Scripts/lib/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="./Scripts/lib/bootstrap/dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="./Scripts/lib/font-awesome/css/font-awesome.css">
    <link rel="stylesheet" href="./Content/app.css">

Books List

                 Add New Book

                    ID
                    Todo
                    Notes

                    <?php foreach($todolists as $todolist) : ?>

                            <?php echo $todolist['Id'] ?>
                            <?php echo $todolist['TODO'] ?>
                            <?php echo $todolist['Notes'] ?>

                            <a class="btn btn-primary" href="book_details.php?todolistID=<?php echo $todolist['Id'] ?>"> Edit

                            <a class="btn btn-danger" href="book_delete.php?todolistID=<?php echo $todolist['Id'] ?>"> Delete

                    <?php endforeach; ?>


text:
Q: How to demonstrate invalid PID assumptions? It seems many programmers are happy with saving a PID to a file, and then later read and use the PID as if it was guaranteed to be the same process. It seems the general idea is that the odds are good enough to ignore. How can I simply demonstrate this problem? Ideally in such a way that existing shell scripts can be adapted to demonstrate this with the minimum of trial and error.
Dummy example:
foo &
pid=$!
echo $pid > pidfile
do
    kill $!
    sleep 1 &
until [ $pid -eq $! ]
kill "$(cat pidfile)" # Kills `sleep`, not `foo`!

A: Using exec is a pretty good demonstration of PID reuse:
#!/bin/bash

cat > foo << 'EOF'
echo "Inside foo."
sleep 5
exec ./bar
EOF

cat > bar << 'EOF'
#!/bin/bash

echo "Inside bar."
sleep 5
EOF

chmod a+x foo bar

./foo &

while sleep 3; do
    [[ -f "/proc/$!/cmdline" ]] || break
    printf 'pid %d == %s\n' "$!" "$(tr '\0' ' ' < "/proc/$!/cmdline")"
done

rm foo bar

Running this script yields something like the following:
$ ./script
Inside foo.
pid 4953 == /bin/bash ./script
Inside bar.
pid 4953 == /bin/bash /tmp/tmp.AvDLtMWYPy/bar
pid 4953 == /bin/bash /tmp/tmp.AvDLtMWYPy/bar

You can exec arbitrary programs, so there is no guarantee (at all) that the process at that PID is the same, or even similar.


text:
Q: Question about r(t), movement along line So I'm studying for an exam in calculus when i came across the concept of objects moving along a curve. I have a general idea of how to calculate speed, velocity and such when r(t)(position vector I think it is called) is given, but I can not quite understand how to determine r(t) myself.
As an example:

$r = r(t) = x(t)i+y(t)j+z(t)k$

Then if I have $y=x^2$ should not $r=x^2i - yj$? The book says $r=xi+x^2j$

A: You need to parametrize the curve, i.e., insert another variable lets call it $t$ to describe the x-axis and y-axis in terms of $t$. In our case we can let $x(t) = t$. Thus $y(t) = t^2$. So our curve is $r(t) = t i + t^2 j$.
Different curves needs different parametrizes.


text:
Q: Example of horizontal grid scrolling in material ui v5 In the previous version of material-ui v4.11.1 they had a Grid List component that in the current version was replaced by Image list. But in Gid List there was an example for Single line Grid list.
https://material-ui.com/components/grid-list/#single-line-grid-list

But in current version material ui v5.0.0-alpha.37
https://next.material-ui.com/components/image-list/
The example for horizontal scrolling is not provided for the Grid or Image List component.
And tried adding the modifications from the previous version.
flexWrap: "nowrap",
overflowX: "scroll",

but it doesn't work, I would appreciate if someone could share a simple example.

A: So i ran into a similar issue and was able to solve this for version 5 of material UI. In your ImageList component, you want to define, within sx, an overflow of auto. Furthermore, the height at which you want your images to appear as on screen you will define with rowHeight, so I placed rowHeight at 200 for myself. Finally, within your ImageListItem, you want to set it, within sx, with a display of flex and a flexDirection of row, doing so allows each item to be placed horizontally. To add spacing in between each image, within the img tag define a marginRight of 1em or whichever number you choose for your liking - remember this goes within your style attribute.
Here is my code example of creating a horizontal scroll of ImageList:
<ImageList sx={{ overflowX: 'auto' }} rowHeight={200}>
          <ImageListItem sx={{display: 'flex', flexDirection: 'row'}}>
            {state.posts[i].images.map(image => {
              return (
              <img
              src={image}
              srcSet={image}
              alt='title'
              loading='lazy'
              style={{paddingRight: '1em'}}
              />
              )
            })}
          </ImageListItem>
        </ImageList>

Here are two images of what it looks like:


text:
Q: Best way to bind directive form fields to root scope variables I created a directive to handle form input groups. Each input needs to be bound to a root scope variable.  I set up a factory to store the variables so that I can use them in the main controller and directive.
So far, I've gotten as far as to have the data populate the form fields (all of the same data in every field).  But I'm doing that by specifying the field name. In order to have each instance of the directive show different data, I can send the name of the field to which it should bind, but it throws an error if I use it in ng-model.
Also, even when I hard-code the field in, it's only a one-way binding.
    var app = angular.module('myApp', []);
    app.controller('mainCtl', function($scope, sharedData){
        $scope.otherdata = "main scope";$scope.test = sharedData.data1;
    }).service('sharedData', function(){
        this.data1 = 600;
      this.data2 = 700;
    }).directive('myDir', function(sharedData){
        return {
      restrict: 'E',
        replace: 'true',
        templateUrl: 'my-dir',
        scope: {
        bindTo: '=',
            showMe: '='
        },
        link: function(scope, element, attrs){
            scope.data1 = sharedData.data1;
          scope.data2 = sharedData.data2;
        }
      };

Shortened sample here: https://jsfiddle.net/wkaskie/najnkga4/12/  In the fiddle, I have it to where there is a one-way binding to data1.  I need to pass in a variable to indicate to which field each input should be bound.

A: UPDATE Good news, after 12 hours of researching and testing, I came up with a solution.

*

*Consider the controllers more. I created a new controller to handle the subset of data and attached it to the directive.
app.controller('subCtl', function($scope, sharedData){
this.sData = sharedData;
}).directive('myDir', function(sharedData){
return {
restrict: 'E',
replace: 'true',
templateUrl: 'my-dir',
bindToController: true,
controller:'subCtl',
controllerAs: 'sub',
//...

*Right on the dot. Much advise I've found was to use dot notation, so I did and that fixed most of the binding issues. In other words, instead of binding the specific data variables I bound the whole daggone object, which included the data points.
from: scope.data1 = sharedData.data1;
to: scope.allData = sharedData; (which includes sharedData.data1, sharedData.data2)

*Remember the brackets. Also, my big wish was to be able to tell each instance of my directive to model the input field off of a different data field. Using bracket notation helped to clear this up. The concept was a simple as passing a basic JavaScript expression to ng-model.

I've updated the fiddle to demo the changes.


text:
Q: WCF - reading an xml file in a service using XElement.Load i have a simple xml file in a wcf service that i am trying to load using Xelement.Load("sample.xml") which is not reading the file. What's the right way of doing this?
The service is supposed to return an xml to an asp.net application.
TIA

A: I got it to work by providing the ABSOLUTE path as the parameter to the XElement.Load() method, RELATIVE path would be better though.

A: You should try something like this then.
var appPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
 bodyFile = Path.Combine(appPath, @"<File Name Path");
This will work relative to your application's physical path.


text:
Q: How to center an image inside an anchor tag? You can check the outcome here in this link. At the bottom of the page, on the extreme right, there is a circle with an image of a tshirt. The image is not vertically centered properly.
The css of the anchor tag is this:-
.dfa {
    padding: 5px 5px;
    font-size: 30px;
    width: 44px;
    text-align: center;
    text-decoration: none;
    margin: 5px 2px;
    border-radius: 50%;
    //line-height: 10px;
}

.dfa-tshirt {
    background: #2c4762;
    color: white;
}

The HTML is this:-

How can I center it? For the time being, I am using inline css for the img, which I will later remove to css file.

A: I would recommend to just keep it simple, let flex handle it for you. All your margins and padding will exacerbate things when your image changes sizes or other common situations

.dfa-tshirt {
    background: #2c4762;
}

a {
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius:50%;
  width: 44px; height: 44px;
}
a img {
  width: 35px; height: 35px;
}

EDIT: Non-flex solution --
I can't really plan for every scenario you may have, but to answer your question and support most browsers, I would also recommend just moving the actual styling to the image only:

a img {
  width: 30px; height: 30px;
  padding: 5px;
  border-radius: 50%;
  background: #2c4762;
}

A: Use this:
img { vertical-align: middle; }

.dfa {
    padding: 5px 5px;
    font-size: 30px;
    width: 44px;
    text-align: center;
    text-decoration: none;
    margin: 5px 2px;
    border-radius: 50%;
    line-height: 10px;
}

.dfa-tshirt {
    background: #2c4762;
    color: white;
}

img {
    vertical-align: middle;
    width:35px;
    height:35px;
}

A: The images parent needs to be displayed inline-block
.dfa {
    padding: 5px 5px;
    font-size: 30px;
    width: 44px;
    text-align: center;
    text-decoration: none;
    margin: 5px 2px;
    border-radius: 50%;
    display: inline-block;
}

The inline style should just be

A: I have just checked you site url, you can add two lines for the class as bellow.

display: table;
      float: right;

  .dfa {
        padding: 5px 5px;
        font-size: 30px;
        width: 44px;
        text-align: center;
        text-decoration: none;
        margin: 5px 2px;
        border-radius: 50%;
        display: table;
        float: right;
   }

Img tag