text:
Q: Can I make an identity field span multiple tables in SQL Server? Can I have an "identity" (unique, non-repeating) column span multiple tables?
For example, let's say I have two tables:  Books and Authors.
Authors
  AuthorID
  AuthorName
Books
  BookID
  BookTitle

The BookID column and the AuthorID column are identity columns.
I want the identity part to span both columns.
So, if there is an AuthorID with a value of 123, then there cannot be a BookID with a value of 123.  And vice versa.
I hope that makes sense.
Is this possible?
Thanks.
Why do I want to do this?  I am writing an APS.NET MVC app.  I am creating a comment section.  Authors can have comments.  Books can have comments.  I want to be able to pass an entity ID (a book ID or an author ID) to an action and have the action pull up all the corresponding comments.  The action won't care if it's a book or an author or whatever.  Sound reasonable?

A: Even if you could put the identity sequence across multiple tables, your comment table is not going to be able to reference both columns in a single foreign key.
The best way to do this, in terms of relational database design theory, would be to create two comment tables. But obviously, you want to avoid that, probably for code-reuse reasons.
The most straightforward pragmatic approach would be to put two foreign key columns on the comment table, and just make one null and the other not null for each comment.
Another approach, which might be the best compromise, is this. You refer in your question to an "entity ID". So make an Entity table! Then the authors and books and comments can all refer to that table.
Edited to add:
Philip Kelley, Ray, and (I think) Artic have all suggested modifying the comment table by adding an entity_id, which can refer to either the book_id or the author_id, and a flag of some sort (char(1), tinyint, and boolean, respectively) that indicates which of these is being referred to.
This is not a good solution for many reasons, both pragmatic (including data integrity, reporting, efficiency) and theoretical.
The first and most obvious problem is the data integrity problem. A relational database system should always be responsible for maintaining the integrity of its own data, and there are natural and preferred ways that the DB is designed to do this. One of the most important of these mechanisms is the foreign key system. If the comment.entity_id column is to reference both book.book_id and author.author_id, then a foreign key cannot be created for this column.
Sure, you could put a check in your DML (insert, update, delete) stored procedures to verify the references, but that would quickly turn into a big mess, as all DML operations on all three tables would be involved.
And that leads us to the efficiency problem. Whenever a query is run against the comment table, it will require joins to either the author or book table or both. The query plan generation system will not have foreign keys available to optimize with, so its performance could very well be degraded.
Then there are problems with this scheme in reporting. Any report generating system is going to have trouble with this sort of system. Sure this won't be a problem for expert programmers, but any user ad-hoc reports are going to have to mock up the logic behind when the event_id means this or that, and it could be a pretty bad deal. Maybe you won't ever use report generating tools on this database. But then again, nobody knows where a database is going to be ultimately used. Why not work with the system to allow for anything?
And that leads us to the theoretical problems.
In relational database theory, each row (a.k.a. "tuple") in each table ("relation variable") represents a proposition about the real world. Designing a table is to decide the form of that proposition. Let's look at a few examples of how this might work.
comment (comment_id int, comment_type char(1), entity_id int,
         user_id int, comment_text nvarchar(max), comment_date datetime)
/* comment_id identifies a comment (comment_text) that a user (user_id)
   has made about a book (entity_id if comment_type = 'B') or author
   (entity_id if comment_type = 'A') at a particular date and
   time (comment_date).*/

Here it is clear that the column (or "attribute") called entity_id is doing double-duty. It doesn't really represent anything, except with reference to another column. This is workable, but unsatisfactory.
comment (comment_id int, book_id int, author_id int, user_id int,
         comment_text nvarchar(max), comment_date datetime)
/* comment_id identifies a comment (comment_text) that a user (user_id)
   has made about a book (book_id if not null) or author (author_id if
   not null) at a particular date and time (comment_date). */

This buys us the foreign keys that are the biggest omission from the first version. But this still isn't terribly satisfactory, unless a single comment can refer to both a book and an author (which might be reasonable). Nullable columns are a warning sign that something is wrong with the design, and that may be the case here as well. A check constraint may be necessary to avoid a comment that refers to nothing at all, or to both a book and an author if that is not to be allowed.
From a theoretical perspective (and thus, my perspective :)) there is a clear best option:
book_comment (book_comment_id int, book_id int, user_id int,
              comment_text nvarchar(max), comment_date datetime)
/* book_comment_id identifies a comment (comment_text) that a
   user (user_id) has made about a book (book_id) at a particular
   date and time (comment_date). */

author_comment (author_comment_id int, author_id int, user_id int,
                comment_text nvarchar(max), comment_date datetime)
/* author_comment_id identifies a comment (comment_text) that a
   user (user_id) has made about an author (author_id) at a particular
   date and time (comment_date). */

This last option would provide the best efficiency, data integrity, and ease of reporting. And the only expense would be that the DML stored procedures would need to put the comments into the right tables, which is not a big deal, since they had to know what the comments were referring to anyway.
If your plan was to retrive all comments for a book or author at once, then you can easily create a view on top of these tables that reproduces the other designs, if that's what you want to do.
create view comments as
select
    book_comment_id as comment_id,
    book_id as entity_id,
    comment_text,
    'B' as comment_type
from book_comment
union
select
    author_comment_id as comment_id,
    author_id as entity_id,
    comment_text,
     'A' as comment_type
from author_comment

A: Actually, Joe Celko suggests on this blog to use a custom sequence in your database, and then, for any primary key of your desired tables, specify their default values to get the next number from your custom sequence.
Here is a code sample from his blog:
CREATE SEQUENCE Service_Ticket_Seq
 AS INTEGER
 START WITH 1
 INCREMENT BY 1
 MINVALUE 1
 MAXVALUE 100
 CYCLE;

CREATE TABLE Meats
(ticket_seq INTEGER DEFAULT NEXT VALUE FOR Service_Ticket_Seq
       PRIMARY KEY,
 meat_type VARCHAR(15) NOT NULL);

CREATE TABLE Fish
(ticket_seq INTEGER DEFAULT NEXT VALUE FOR Service_Ticket_Seq
       PRIMARY KEY,
 fish_type VARCHAR(15) NOT NULL);

INSERT INTO Meats (meat_type) VALUES ('pig');
INSERT INTO Fish (fish_type) VALUES ('squid');

select * from Meats

select * from Fish

This being said, an identity field spanning multiple tables is possible in MS SQL.

A: The short answer is: No, you can't do that (at least in MS SQL Server through 2008).
You could make a new table, "CommentableEntity", plug your identity column in there, then define foreign keys in Authors and Books to reference it as a parent table, and then do one of a number of tricks to ensure that a given ID value is not assigned to both tables... but this is a poor idea, because the data model you built would imply that Authors and Books are related kinds of data, and they really aren't.
You could have a separate table, Comments, have the identity column in there, and park a CommentId column in both Authors and Books. However, that would limit each book and author to only one comment.
Me, I'd probably add a column like "CommentorType" to the Comments table and a put a flag in there indicating source of comment ("A" for author, "B" for book). Build a primary key on "CommentorId + CommentorType", and it should work well enough -- and it'd be trivial to add further types of commentors as the system expands.

A: As a suggestion - try to use table like ComentId, EntityId, isBook, Comment for comments. isBook is boolean type and not much place to get. Your concept is not good from relational point of view.

A: SQL server does not support this. You could roll your own with an id table, but that would be more work than it is worth.
I suggest your comment table look like this:
comment_id int identity
comment_type tinyint
entity_id int

comment_type specifies if the comment belongs to a book, an author, or something else you add in the future. entity_id is the id of the book, author, whatever. In this scheme, it doesn't matter if book or author ids overlap.
Or, if you can switch to oracle, use a sequence :)


text:
Q: Calculations of linear discriminant function for classification Referring to the below diagram from Chris Bishop (with my markings/write-ups in yellow color), I tried to find the distance (marked as $r$) of a point $\mathbf{x}$ from decision surface (the red line).
When I consider the point $\mathbf{x}$ from $O$ as origin instead of the origin of $x_1$ and $x_2$, I could derive (see after the diagram) what is written in the book. My concern is that if this change of origin is correct? From the blue coloring of $\mathbf{x}$, it seems the vector is supposed to be considered from the origin of the $x_1$ and $x_2$. If so, then how do we arrive at the same derivation for the distance $r$?

My derivation:
$$
\mathbf{x} = \mathbf{x_\perp} + r \frac{\mathbf{w}}{||\mathbf{w}||}$$
Given Linear discriminant function $ y(\mathbf{x})=\mathbf{w}^T\mathbf{x} + w_0
$, and since $\mathbf{x_\perp}$ is on the decision-boundary $y(\mathbf{x})=0$ (the red line), we have
$$ y(\mathbf{x_\perp})=0 = y(\mathbf{x} - r \frac{\mathbf{w}}{||\mathbf{w}||}) = \mathbf{w}^T(\mathbf{x} - r \frac{\mathbf{w}}{||\mathbf{w}||}) + w_0
$$
Solving for $r$, $$
r=\frac{\mathbf{w}^T\mathbf{x} + w_0}{||\mathbf{w}||} = \frac{y(\mathbf{x})}{||\mathbf{w}||}
 $$

A: Someone just pointed me out that we don't need to shift the origin as I suspected.
The equation:
$$
\mathbf{x} = \mathbf{x_\perp} + r \frac{\mathbf{w}}{||\mathbf{w}||}$$
is still valid considering the $\mathbf{x}$ (blue-line) in original coordinate along with $\mathbf{x_\perp}$ as the vector shown in fuchsia-line (see below).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tribonacci generating matrix I know that $T(0) = 0$ and $T(1) = T(2) = 1$. For $n \ge 3$,
$$T(n)=T(n-1)+T(n-2)+T(n-3)$$
Now I find that
$$\begin{bmatrix}T(n+1)\\T(n)\\T(n-1)\end{bmatrix} = \begin{bmatrix}1&1&1\\1&0&0\\0&1&0\end{bmatrix}\cdot\begin{bmatrix}T(n)\\T(n-1)\\T(n-2)\end{bmatrix} = \cdots=\begin{bmatrix}1&1&1\\1&0&0\\0&1&0\end{bmatrix}^n\cdot\begin{bmatrix}1\\1\\0\end{bmatrix}$$
How do I find now that
$$\begin{bmatrix}1&1&1\\1&0&0\\0&1&0\end{bmatrix}^n = \begin{bmatrix}
T(n+1)&T(n)+T(n-1)&T(n)\\T(n)&T(n-1) + T(n-2)&T(n-1)\\T(n-1)&T(n-2)+T(n-3)&T(n-2)\end{bmatrix}$$
Do I need to guess? Or there is a way to do it?

A: One option is surely to get your transfermatrix, say $\mathbb M$, (that one with zeros and ones) as solution of one step of iteration.
So for instance $[T_0, T_1, T_2] \cdot \mathbb M = [T_1,T_2,T_3]  \Rightarrow \text{ find } \mathbb M$ . Now this simple ansatz does not yet help, because we cannot apply matrix-inversion on the one-row vector on the lhs.
But instead to have only a one-row vector on the lhs, we can construct square matrices $\mathbb T_0$,$\mathbb T_1$  to attempt $ \mathbb T_0 \cdot \mathbb M = \mathbb T_1  \Rightarrow \mathbb M = \mathbb T_0^{-1} \cdot \mathbb T_1$ :
$$ \begin{array}{ccc}
   &  & \mathbb M  \\
   & * & ========\\
 \left[\begin{array}{}  T_0&T_1&T_2 \\T_1&T_2&T_3 \\T_2&T_3&T_4 \end{array}\right]
   & = &
\left[\begin{array}{}  T_1&T_2&T_3 \\T_2&T_3&T_4 \\T_3&T_4&T_5 \end{array}\right] \\
\end{array}
$$
Then $ \mathbb T_0 \cdot \mathbb M^n = \mathbb T_n$ by construction.

Note: It would have been better to use small letters for scalar values and capital letters for the matrices, but well: I just used the "mathbb"-attribute for distinction


text:
Q: Load BLOB to Gallery android I would like to read a Blob of my MySQL database
This "Array" BLOB would be placed in a "Gallery".
Code to read BLOB from the database:
while (rs.next()) {
            String id = rs.getString("id");
            String description = rs.getString("description");
            Blob image = (Blob) rs.getBlob("img");

            Material m = new Material(id, description,image);
            listaMaterial.add(m);
}

Como eu faço para colocar várias BLOB em uma Gallery, qual transformação devo fazer?

A: To store images in base64 format -
To Encode :
Bitmap clickedPhoto;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
clickedPhoto.compress(Bitmap.CompressFormat.JPEG, 100, baos);
String strData = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);

You can store this strData as a varchar/text in your database
To Decode:
byte[] arrPhoto = Base64.decode(strData, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(arrPhoto, 0, arrPhoto.length);

Get strData by using getString() from your ResultSet and then decode it to a Bitmap to use in your application.
Let me know if this works for you.


text:
Q: Select function name based on template parameter Is there a way to automatically select between multiple non-template functions based on a template parameter?
Example:
class Aggregate
{
public:
     std::string asString();
     uint32_t asInt();
private:
     // some conglomerate data
};

template <typename T>
T get(Aggregate& aggregate)
{
     // possible map between types and functions?
     return bind(aggregate, typeConvert[T])(); ??
     // or
     return aggregate.APPROPRIATE_TYPE_CONVERSION();
}

The solution would be nice to throw a compiler error if there is no good conversion available, i.e.
get<double>(aggregate); // compile error

I do not want to use template specialization, i.e
template<>
int get(Aggregate& aggregate)
{
    return aggregate.asInt();
}

because it leads to code duplication when your get() function has more then one line of code

A: The pedestrian way is to define each possible option separately:
template <typename T> T get(Aggregate &);    // leave undefined

template <> uint32_t get(Aggregate & a) { return a.asInt(); }

// ...

Absent any more systematic structure that encodes which function serves which conversion, I think this is the best you can do. It may be worth redefining Aggregate, though, to be more introspectible.

A: You may do something like (require C++11) : (https://ideone.com/UXrQFm)
template <typename T, typename... Ts> struct get_index;

template <typename T, typename... Ts>
struct get_index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename Tail, typename... Ts>
struct get_index<T, Tail, Ts...> :
    std::integral_constant<std::size_t, 1 + get_index<T, Ts...>::value> {};

template <typename T, typename Tuple> struct get_index_in_tuple;

template <typename T, typename ... Ts>
struct get_index_in_tuple<T, std::tuple<Ts...>> : get_index<T, Ts...> {};

class Aggregate
{
public:
     std::string asString();
     uint32_t asInt();
private:
     // some conglomerate data
};

template <typename T>
T get(Aggregate& aggregate)
{
    using types = std::tuple<uint32_t, std::string>;
    auto funcs = std::make_tuple(&Aggregate::asInt, &Aggregate::asString);

    return (aggregate.* (std::get<get_index_in_tuple<T, types>::value>(funcs)))();
}


text:
Q: After name server change, DNS queries on and off I migrated the domain www.pantego.com to a different name server. We were using the Enom registrar and their default name servers, but I migrated them to AWS Route 53. I know all records were copied over, but the domain seems to go up and down at random. Sometimes the website works, and sometimes it doesn't. This corresponds to when nslookup works and doesn't work. The previous TTL was two days and it has not been that long yet, however, why does DNS go up and down for my site? Other users report this too. Any help is appreciated.
Edit:
Dig always works - nslookup (and therefore ping and http requests) don't always work. I did notice that pinging ns1.pantego.com and ns2.pantego.com return the old IPs, but nothing should be using those addresses anyways? Both the old name server and the new name server have the same settings. I will remove the old one when the TTL expires.

A: It could be a temporary problem, that will be solved when old records expire.
According to Global DNS Propagation Check, all servers return the same IP:
https://www.whatsmydns.net/#A/www.pantego.com
Try using "nslookup www.pantego.com" (Windows) or "host www.pantego.com" (Unix) on problematic computers to see which IP they get from DNS.
Do not forget to completely remove the domain from previous DNS servers.


text:
Q: Split 200MB textfile with delimiter-line in PHP I need to split a big text-file (200MB) into multiple smaller files. The split should be based on a defined text-line.
Big file
This is a title
Lorem Ipsum
New Chapter
This is a title
Lorem Ipsum

So the line This is a title should mark where to split the file and it also should be the first line of the new file. So the result would be:
First file
This is a title
Lorem Ipsum
New Chapter

Second file
This is a title
Lorem Ipsum

I can split the textfile into defined byte-sizes, but this is not, what I need:
$i = 1;
$fp = fopen("big_file.txt",'r');
while(! feof($fp)) {
    $contents = fread($fp,1000);
    file_put_contents($i.'.txt',$contents);
    $i++;
}

I need to split for a defined line.

A: Just go line by line and search for the delimiter:
$i = 1;
$file = fopen("big_file.txt", "r");
while(!feof($file)){
    $line = fgets($file);
    if ($line == "delimiter") {
        if ($contents) file_put_contents($i.'.txt',$contents);
        $contents = '';
        $i++;
    }
    else $contents .= $contents;
}
fclose($file);


text:
Q: Https returns 404 with DefaultHttpClient on Android? I have an http request that worked as http://blah.com and now I have been asked to use https://blah.com
The former works and the later fails with a Network I/O error.  Are there any missing parameter settings that I need for the client?
The URL request:
D/MyAppWebservice(23142): http-transform :) [https://cdp.mobibob.com:8151/DoTransaction]

Following is the log:
E/MyAppContentProvider(23142): com.mobibob.myapp.MyAppExceptions$ParseException: Network or I/O error calling web service.
W/System.err(23142): com.mobibob.myapp.MyAppExceptions$ParseException: Network or I/O error calling web service.
W/System.err(23142):    at com.mobibob.myapp.MyAppWebservice.queryApi(MyAppWebservice.java:558)
W/System.err(23142):    at com.mobibob.myapp.MyAppContentProvider.queryWebservice(MyAppContentProvider.java:751)
W/System.err(23142):    at com.mobibob.myapp.MyAppContentProvider.query(MyAppContentProvider.java:440)
W/System.err(23142):    at android.content.ContentProvider$Transport.query(ContentProvider.java:130)
W/System.err(23142):    at android.content.ContentResolver.query(ContentResolver.java:202)
W/System.err(23142):    at com.mobibob.myapp.ui.DownloadActivity.goGenDownloadTransaction(DownloadActivity.java:168)
W/System.err(23142):    at com.mobibob.myapp.ui.DownloadActivity$DownloadTransaction.doInBackground(DownloadActivity.java:90)
W/System.err(23142):    at com.mobibob.myapp.ui.DownloadActivity$DownloadTransaction.doInBackground(DownloadActivity.java:1)
W/System.err(23142):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
W/System.err(23142):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
W/System.err(23142):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
W/System.err(23142):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
W/System.err(23142):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
W/System.err(23142):    at java.lang.Thread.run(Thread.java:1096)
W/System.err(23142): Caused by: java.io.IOException: SSL handshake failure: I/O error during system call, Unknown error: 0
W/System.err(23142):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.nativeconnect(Native Method)
W/System.err(23142):    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:305)
W/System.err(23142):    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:92)
W/System.err(23142):    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:321)
W/System.err(23142):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:129)
W/System.err(23142):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(23142):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(23142):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
W/System.err(23142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(23142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(23142):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(23142):    at com.mobibob.myapp.MyAppWebservice.queryApi(MyAppWebservice.java:510)
W/System.err(23142):    ... 13 more

A: Https almost always implies a different port being used (standard http=>80; standard https=>443). You have a hardcoded port (8151). I'm guessing the https servlet is listening on a different port.
Or you're trying to connect to a server that doesn't support https.


text:
Q: Knowing $a|bx$ can we conclude that $\frac{a}{gcd(a,b)}|\frac{bx}{gcd(a,b)}$ Knowing $a|b$ can we conclude that $\frac{a}{gcd(a,b)}|\frac{b}{gcd(a,b)}$?

My apologies the thing I was actually looking for was actually if we have $a|bx$ can we conclude that $\frac{a}{gcd(a,b)}|\frac{bx}{gcd(a,b)}$ I thought for a moment $x$ didn't matter

A: Yes.  $a|b$ means that gcd$(a,b)=a$ and $\frac a{\text{gcd}(a,b)}=1$ and $1|k$ for all nonzero $k$.
Based on the edit, we have $a=u\cdot \text{gcd}(a,b),\ b=v\cdot \text{gcd}(a,b)$, so given $a\mid bx$ we get
$$u\cdot \text{gcd}(a,b)\mid v\cdot \text{gcd}(a,b)\cdot x$$
so there exists $m$ such that
$$u\cdot \text{gcd}(a,b)\cdot m= v\cdot \text{gcd}(a,b)\cdot x$$
and dividing by $\text{gcd}(a,b)$ yields $u\cdot m=v\cdot x$ and so $u\mid v\cdot x$ and thus
$$\frac a{\text{gcd}(a,b)}\left.\right| \frac b{\text{gcd}(a,b)}\cdot x$$


text:
Q: Reading iostat utilization with ZFS zvols First off, I asked this question 5 days ago over on Serverfault. I hope I'm not doing a bad by bringing it over here to the Unix&Linux Stack. I have also asked this question on 3 other sites not related to Stack, with no answers. I plan on updating each site with an answer, if I can just get it answered. Here we go.
I am having a hard time understanding the output of iostat -x with specific regards to ZFS zvols. I'm running Proxmox 4.4, fully updated and encountering some generally poor IO performance.
While troubleshooting the sluggish performance, I was looking at iostat -x 1 and saw this sort of utilization reading near constantly.
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
sda               0.00     0.00   77.00  115.00   308.00   640.00     9.88     2.02   10.33    9.92   10.61   3.58  68.80
sdb               0.00     0.00   81.00  116.00   324.00   644.00     9.83     1.32    6.72    6.42    6.93   2.50  49.20
...
sde               0.00     0.00   77.00  117.00   308.00   640.00     9.77     1.16    6.25    5.25    6.91   2.35  45.60
sdf               0.00     0.00   78.00  116.00   312.00   640.00     9.81     1.25    6.45    5.64    7.00   2.47  48.00
...
zd32              0.00     0.00    0.00  197.00     0.00   788.00     8.00     1.09    5.54    0.00    5.54   5.06  99.60

Where I am confused is that the utilization percent for zd32, the zvol of my VM, is at 100%, where the underlying storage is at roughly 50% utilization.
My question is: Shouldn't the zvol utilization reflect the utilization of the underlying storage devices?
For reference, there are other VMs on this system, but this troubleshooting was done after hours, so they were idle. This one VM was the only busy VM, running Windows updates. The zpool is a RAID-Z2 of 7200RPM SATA disks, so not exactly built for incredible speed. I'm just wondering about the utilization right now.

A: Here are some hints. Yes, it should, because zfs volume is created on zpool which is located on a storage device. If that storage is shared between other resources, they can affect zfs pools and volumes.
Unfortunately, I do not know what Proxmox is, but %util usually shows the time the device has a positive queue of transactions. A number of transactions in the queue is avgqu-sz. Both of these values are also depend on the storage system type and model which can support quite a large queue. So, it may be a bad symptom or not. Therefore first of all it's better to look at: await, r/s, w/s, rkB/s, wkB/s to see if the volume has a real workload and performance issues or not.
There is a special command: zpool iostat to monitor zpool statistic.


text:
Q: Customize Password Validation Error message Of Password Rule Class of Laravel Fortify What is the efficient way to customize validation message defined in Password Rule class of Laravel Fortify ?

A: For now, I am customizing messages by defining the translation as:
{
    "The :attribute must be at least :length characters.": ":attribute を少なくとも :length 文字の英数字に設定してください\n文字。"
}

Which seems to work fine, but is there any other better way to do so ?


text:
Q: Get a point on a line segment parallel to another line segment having common intersection line
In the image above, coordinates of points $A,\, B,\, C,\, D$ and $E$, are known. Also line $AB$ is parallel to $EX_1$ and so are lines $AC$ and $EX_2$. How can I find coordinates of points $X_1$ and $X_2$.

A: Let $r  = \frac {DE}{DA}= \frac {DX_2}{DC}= \frac {DX_1}{DB}$.
Then $X_1$ and $X_2$ are $r$ of the distance between $D$ and $B$ and between $D$ and $C$.
So $X_1= (D_x + r(B_x - D_x), D_y + r(B_y- D_y))$ and $X_2 =(D_x + r(C_x - D_x), D_y + r(C_y- D_y))$.

A: Hint: You can find equations of the lines $AB$ and $BD$. Then you find the line parallel to $AB$ and passes through $E$. Finally, you find intersection of the lines $BD$ and $EX_1$.

A: Working in homogeneous coordinates, $$X_1\sim (B\times D)\times((A-B)\times E) \\ X_2\sim (C\times D)\times((A-C)\times E).$$ This is basically Farrukh Ataev's answer computed directly.


text:
Q: ClickOnce application I have prepared a ClickOnce application. All my files and a folder in the same location includes application files (folder), connexionDeployment_V2.application, connexionsetup.msi (my setup to call in default.htm), default.htm (to setup the application), setup.exe (redundant).
Default.htm includes a command line that is
<a href="./connexionsetup.msi"> run application </a>

After finishing project, my ClickOnce project does not behave like a ClickOnce project. That is, it is not doing the setup process by itself; it is doing the setup process normal setup application by waiting for my click "next-next-next", but a ClickOnce application, as you know, begins the setup process by itself and it does not look like a normal download project and it does not tell me to click next click next to continue because it does all steps by itself.
How can I fix this problem? How can my application behave like an original ClickOnce application?
Pictures of my steps
My command line:

After clicking run application:

A: Your link is trying to install using an msi which is not the ClickOnce application you are looking for. ClickOnce.
connexionDeployment_V2.application is used to run the application if all prerequisites are installed.
setup.exe is use to install the application if you do not have prerequisites installed.
msi is usually a standalone installer like you are seeing.
Why not use the default generated page for ClickOnce publishing? How are you creating the ClickOnce deployment?


text:
Q: pygame and python not working for me I'm just starting out with pygame and I'm have a bit of an issue, here is my code...
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

and here is the error i keep getting...
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1521, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Jason\Documents\Python\pygame.… line 1, in <module>
import pygame, sys
File "C:\Users\Jason\Documents\Python\pygame.… line 2, in <module>
from pygame.locals import *
ImportError: No module named 'pygame.locals'; pygame is not a package

So my question is how do i get pygame to work with python?
python version 3.3.2
pygame version: Python 3.3 pygame-1.9.2pre(64-bit)

A: Your pygame install was no successful what you need to do is install python 2.7 from here
then you need to reinstall your pygame. If you are using python 3.3 you will want to make a new install with the older version it will not delete your newer one. Make sure that it says the install is sucsessful. If that doesn't work try rebooting and/or reinstalling. GOOD LUCK!!


text:
Q: user account "effective permissions" with powershell I need to compare AD users permissions (one user can "unset" an attribute and another cannot, both can change it).
How can I dump/compare user account "effective permissions" which I find when I go to user account > Security > Advanced > Effective Permissions (and select an user account) with powershell?

A: Using Quest Free PowerShell Commands for Active Directory is simple:
Get-QadPermission useraccountname -Inherited

or better way:
Get-QADUser -Name useraccountname -SecurityMask DACL | Get-QADPermission -Inherited -SchemaDefault

This return all effective permission Inherited or Explicit assigned for the user 'useraccountname'
The comparison can be made with compare-object.
A very simple example:
compare-object (Get-QADPermission userA -Inherited | select Rights) (Get-QADPermission userB -Inherited | select rights)

A: We were in a similar situation once and needed to know who all could delete one of our main OUs, so we figured that maybe we should dump the ACL on the OU and look for everyone who had delete permissions on the object. Of course dsacls was very helpful in this regard and we could dump the ACL on it easily.
But then, as we started looking at the ACL, we found that it had almost 60 permission entries, including about half a dozen deny entries, some of which were direct and others inherited. We initially didn't consider the denies and came up with a list of about 200 users who could delete the OU, but that did not seem right (; it seemed too high.) Then, we realized that we had to intersect the denies with the allows!
So we flattened all deny permissions, and all allow permissions, but then we had to figure out which of these denies would apply, since some of them were inherited, and I believe the inherited ones don't negate any direct allows, so that took some more pain-staking work, and while doing it we realized that some of those inherited permissions did not apply to the object, so we had to start from scratch!
Finally, we almost gave up, and when I asked one of our Enterprise Admins, he said what we needed to do was determine Effective Permissions on our OU, and he pointed us to the Effective Permissions Tab in the Active Directory Users and Computers snap-in.
So we launched ADUC and navigated to the Effective Permissions Tab, and figured it would be a matter of clicking OK somewhere. However, we soon realized that it needed us to enter each person's name individually. Now, we have almost 2000 people in our environment, so there was no way we could put in 2000 people's names one by one. The other thing was that even for a single person, it  would show us all the effective permissions for that person, and in technical terms, which we would have to further refine.
We then figured we'd give Powershell a shot, and looked at many options to do this using Powerhsell, but there was no easy to determine effective permissions in AD using Powershell, which was disappointing. In particular, we tried Quest's free PowerShell commands Get-QadPermission useraccountname and Get-QADUser -Name useraccountname, but we were disappointed to see that this only retrieved the list of all permissions specified for a given user. It did not reveal the Effective Permissions granted to a user. We found ourselves having to start with the results it brought back to then manually try and determine effective permissions, which was not worth our time.
So, we had almost given up hope, but before quitting we thought we would just Google "Active Directory Effective Permissions Tool" with the hope that there must be something out there that could do this for us. I am glad we did because we found a tool that could do exactly what we needed: figure out effective permissions on our OU and give us the ability to export these effective permissions -
http://www.paramountdefenses.com/goldfinger_capabilities_true_effective_permissions_for_active_directory.html
We found that this tool (called Gold Finger for AD) has the ability to determine Effective Permissions on Active Directory objects, and provide the output such that we could easily see the list of all users who had "effective permissions" for a specific right on an object. For instance, we were able to use it to determine and enumerate the list of all admins who had "effective delete access" rights on the OU we were interested in.
It has turned out to be quite helpful for us, and maybe it could be of help to you too. I just thought I would share this because I've been the dsacls route and I wouldn't want you to go through the same pain we did in trying to manually do this. Its just too painful to do do manually.


text:
Q: Looping to get result in VBA
Code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim lastRow As Long
Application.ScreenUpdating = False

Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

    .Range("P2").Formula = "=IF(MOD(SUMPRODUCT(($B$2:$B2=B2)*($K$2:$K2=K2)),3)=1,1,0)"
    .Range("P2").AutoFill Destination:=.Range("P2:P" & lastRow)
    .Range("P2:P" & lastRow).Value = .Range("P2:P" & lastRow).Value
    .Range("F2").Formula = "=IF"
End With
Application.ScreenUpdating = True
End Sub

What I want to achieve is to use the existing code to continue to add on to get the value in Column F to get the quantity.
If the quantity is < 36, then 1 point in "point" column;

if the quantity is 36 - 45, then 2 points in "point" column;

if the quantity is more then 46, then 3 points in the "point" column.

A: Try this formula

Option Explicit

Private Sub CommandButton1_Click()
    Dim ws As Worksheet, lr As Long

    Application.ScreenUpdating = False

    Set ws = ThisWorkbook.Sheets("Sheet1")
    lr = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row

    With ws.Range("P2:P" & lr)
        .Formula = "=IF(COUNTIF(B$2:B2,B2)>1, 0, IF(F2<36, 1, IF(F2<46, 2, 3)))"
        .Value = .Value
    End With

    Application.ScreenUpdating = True
End Sub

A: just add the below lines before End with in your code
.Range("Q2").Formula = "=IF(AND(F2<36,F2>0),1,IF(AND(F2>=36,F2<=45),2,IF(F2>46,3,""Zero or Beyong 46"")))"
.Range("Q2").AutoFill Destination:=.Range("Q2:Q" & lastRow)
.Range("Q2:Q" & lastRow).Value = .Range("Q2:Q" & lastRow).Value


text:
Q: handling large amounts of data to include in an oracle select statement Recent bug report states that a method being called is crashing the service causing it to restart.  After troubleshooting, the cause was found to be an obnoxious Oracle SQL call with thousands of strings passed.  There is a collection of strings being passed to a method from an external service which often is more than 10,000 records.  The original code used a where clause on the passed collection using the LIKE keyword, which I think is really, really bad.
public IList<ContainerState> GetContainerStates(IList<string> containerNumbers)
{
    string sql =
    String.Format(@"Select CTNR_NO, CNTR_STATE FROM CONTAINERS WHERE CTRN_SEQ = 0 AND ({0})",
        string.Join("OR", containerNumbers
                .Select(item => string.Concat(" cntr_no LIKE '", item.SliceLeft(10), "%' ")))
    );
    return DataBase.SelectQuery(sql, MapRecordToContainerState, new { }).ToList();
}

Clarification of in house methods used which may be confusing:
DataBase.SelectQuery is an internal library method using generics which gets passed the sql string, a function to map the records to .NET objects, and the parameters being passed and returns an IEnumerable of Objects of type retuned by the Mapping function.
SliceLeft is an extension method from another internal helper library that just returns the first part of a string up to the number of characters specified by the parameter.

The reason that the LIKE statement was apparently used, is that the strings being passed and the strings in the database only are guaranteed to match the first 10 characters.  Example ("XXXX000000-1" in the strings being passed should match a database record like "XXXX000000-8").
I believed that the IN clause using the SUBSTR would be more efficent than using multiple LIKE clauses and replaced the code with:
public IList<ContainerRecord> GetContainerStates(IList<string> containerNumbers)
{
    string sql =
String.Format(@"Select CTNR_NO, CNTR_STATE FROM CONTAINERS WHERE CTRN_SEQ = 0 AND ({0})",
              string.Format("SUBSTR(CNTR_NO, 1, 10) IN ({0}) ",
                            string.Join(",", containerNumbers.Select(item => string.Format("\'{0}\'",  item.SliceLeft(10) ) ) )
                            )
              );
    return DataBase.SelectQuery(sql, MapRecordToContainerState, new { }).ToList();
}

This helped slightly, and there were fewer issues in my tests, but when there are huge amounts of records passed, there is still an exception thrown and core dumps occur, as the SQL is longer than the server can parse during these times.  The DBA suggests saving all the strings being passed to a temporary table, and then joining against that temp table.
Given that advice, I changed the function to:
public IList<ContainerRecord> GetContainerStates(IList<string> containerNumbers)
{
    string sql =

@"
        CREATE TABLE T1(cntr_num VARCHAR2(10));
        DECLARE GLOBAL TEMPORARY TABLE SESSION.T1 NOT LOGGED;
        INSERT INTO SESSION.T1 VALUES (:containerNumbers);

        SELECT
                DISTINCT    cntr_no,
                            '_IT' cntr_state
        FROM
                tb_master
        WHERE
                cntr_seq = 0
            AND cntr_state IN ({0})
            AND adjustment <> :adjustment
            AND SUBSTR(CTNR_NO, 1, 10) IN (SELECT CNTR_NUM FROM SESSION.T1);
";

        var parameters = new
        {
            @containerNumbers = containerNumbers.Select( item => item.SliceLeft(10)).ToList()
        };
    return DataBase.SelectQuery(sql, MapRecordToContainerState, parameters).ToList();
}

Now I'm getting a "ORA-00900: invalid SQL statement".  This is really frustrating, how can I properly write a SQL Statement that will put this list of strings into a temporary table and then use it in a SELECT Statement to return the list I need?

A: There are couple possible places could cause this error, it seams that the "DECLARE GLOBAL TEMPORARY" is a JAVA API, I don't think .net has this function. Please try "Create global temporary table" instead. And, I don't know whether your internal API could handle multiple SQLs in one select sql. As far as I know, ODP.net Command class can only execute one sql per call. Moreover, "create table" is a DDL, it therefore has its own transaction. I can't see any reason we should put them in the same sql to execute. Following is a sample code for ODP.net,
using (OracleConnection conn = new OracleConnection(BD_CONN_STRING))
        {
            conn.Open();
            using (OracleCommand cmd = new OracleCommand("create global temporary table t1(id number(9))", conn))
            {
                // actually this should execute once only
                cmd.ExecuteNonQuery();
            }

            using (OracleCommand cmd = new OracleCommand("insert into t1 values (1)", conn)) {
                cmd.ExecuteNonQuery();
            }

            // customer table is a permenant table
            using (OracleCommand cmd = new OracleCommand("select c.id from customer c, t1 tmp1 where c.id=tmp1.id", conn)) {
                cmd.ExecuteNonQuery();
            }
        }


text:
Q: Microsoft Graph - Deleted Events from deleted Items folder I'm looking to return all calendar events that are in the Deleted Items folder.
Currently I am using the call:
https://graph.microsoft.com/beta/me/mailFolders/{deletedItems-id}/messages
But this only returns the deleted messages. Is there any call available that will allow me to retrieve the deleted events? Thanks in advance.

A: One idea is to query all events and filter on the isCancelled property and optionally add startDateTime and enddatetime to limit the search.
GET https://graph.microsoft.com/v1.0/me/events?$filter=isCancelled eq true
Also, I also tested querying the deleted messages folder and I am seeing items in there that look like the following (note the type and meetingMessageType properties). Are you seeing something similar in your queries?
{
    "@odata.type": "#microsoft.graph.eventMessage",
    "@odata.etag": "W/\"DQAAABYAAACuuXbTGFIVS6y5orm951W8AAAUik5T\"",
    "id": "AAMkA...=",
    "createdDateTime": "2017-07-10T20:13:57Z",
    "lastModifiedDateTime": "2017-07-10T20:13:59Z",
    "changeKey": "DQAA...",
    "categories": [],
    "receivedDateTime": "2017-07-10T20:13:57Z",
    "sentDateTime": "2017-07-10T20:13:56Z",
    "hasAttachments": false,
    "internetMessageId": "<SN2PR00MB012...>",
    "subject": "Canceled: test cancelled event",
    "bodyPreview": "",
    "importance": "high",
    "parentFolderId": "AAMkADYwODg0MWJiLTQ...=",
    "conversationId": "AAQkADYwODg0MWJiLTQ...=",
    "isDeliveryReceiptRequested": false,
    "isReadReceiptRequested": false,
    "isRead": false,
    "isDraft": false,
    "webLink": "https://outlook.office365.com/...",
    "inferenceClassification": "focused",
    "meetingMessageType": "meetingCancelled",
}

A: Found a similar question : 'Microsoft Graph APi not returning "Cancelled" Events'
With the response of :

By design, when an event is canceled, it is deleted from the calendar. So, there isn't a way today to query list of events that are deleted. We have an item in our backlog for supporting deleted events, but no timeline.


text:
Q: How to set boundaries for a draggable object? I want the black button not to move out of the triangle, (see Flickr link)
and if it goes over the edge of the triangle, that the button is returned back into the triangle.
How do I do that?
http://www.flickr.com/photos/92202376@N08/8590549046/in/photostream
#import "DraggableViewController.h"

@interface DraggableViewController ()

@end

@implementation DraggableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // create a new button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"Scale9Image.png"]
                      forState:UIControlStateNormal];

    // add drag listener
    [button addTarget:self action:@selector(wasDragged:withEvent:)
     forControlEvents:UIControlEventTouchDragInside];

    // center and size
    button.frame = CGRectMake((self.view.bounds.size.width - 100)/1.6,
                              (self.view.bounds.size.height - 50)/1.9,
                              40, 40);
    button.frame.origin.y;

    [self.view addSubview:button];

}

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
    // get the touch
    UITouch *touch = [[event touchesForView:button] anyObject];

    // get delta
    CGPoint previousLocation = [touch previousLocationInView:button];
    CGPoint location = [touch locationInView:button];
    CGFloat delta_x = location.x - previousLocation.x;
    CGFloat delta_y = location.y - previousLocation.y;

    // move button
    button.center = CGPointMake(button.center.x + delta_x,
                                button.center.y + delta_y);
}
@end

A: See that line where you move the button in -wasDragged?
button.center = CGPointMake(button.center.x + delta_x,
                            button.center.y + delta_y);

You can prevent the button from leaving the triangle by testing the new point to make sure that it's inside the triangle before you move the button. Better, you can simply compute the point inside the triangle that's closest to the new point and use that, so the button will still move as the touch moves outside the triangle, but it will be constrained to the triangle:
CGPoint newPoint = CGPointMake(button.center.x + delta_x,
                                button.center.y + delta_y);
button.center = [self buttonPositionNearestToPoint:newPoint];

Of course, you'll need to implement the -buttonPositionNearestToPoint: method. You'll need a little computational geometry to do that. Check out Point in triangle test for a gentle introduction. barycentric coordinate clamping on 3d triangle may also prove helpful even though it's 3D instead of 2D.


text:
Q: Is it possible to detect a grace period via BillingClient? I'm trying to detect grace period using BillingClient.
The documentation says:

A subscription can go through various state changes throughout its lifecycle, and your app needs to respond to each change. To check the subscriber's state, your app can query using either BillingClient.queryPurchasesAsync() in the Google Play Billing Library or Purchases.subscriptions:get in the Google Play Developer API.

Unfortunately, it seems to me that it is not possible to differentiate between an active subscription and a grace period using BillingClient. In both cases isAutoRenewing flag is set to true and purchaseState is 1. At least that's what I see when I try to reproduce such case in test environment by purchasing subscription using Test card, always approves and then changing to Test card, always declines before subscription is renewed.
Any ideas?

A: I don't think you can since you need the Purchases.subscriptions:get API, as described here:

A subscription can go through various state changes throughout its lifecycle, and your app needs to respond to each change. To check the subscriber's state, your app can query using either BillingClient.queryPurchasesAsync() in the Google Play Billing Library or Purchases.subscriptions:get in the Google Play Developer API.
[ ...]
Grace period if:

*

*expiryTimeMillis is in the future // Purchases.subscriptions:get

*paymentState = pending // Purchases.subscriptions:get

*autoRenewing = true. // Purchases.subscriptions:get or BillingClient


text:
Q: Electromagnetic tensor in CGS units To write the electromagnetic field tensor in CGS units I just have to kick off the c-s from the SI tensor right?
I know this is a stupid question but I need a reliable answer.

A: In S.I units the electromagnetic tensor is
$$T^{\mu\nu}=\frac{1}{\mu_0}[F^{\mu \alpha}F^{\nu}_{\alpha}-\frac{\eta^{\mu\nu}}{4}F_{\alpha\beta}F^{\alpha\beta}]$$
Now, in CGS units, the permitivity and permeability are
$$\epsilon_{0}=\frac{1}{4\pi}$$ and $$\mu_{0}=4\pi$$
Thus, the tensor in cgs units is
$$T^{\mu\nu}=\frac{1}{4\pi}[F^{\mu \alpha}F^{\nu}_{\alpha}-\frac{\eta^{\mu\nu}}{4}F_{\alpha\beta}F^{\alpha\beta}]$$


text:
Q: Cannot add multiple HTML code snippets to wordpress I have a HTML code with a canvas and a button, and all the necessary drawings are inside the draw(canvas) function.

    <canvas id="canvas" width="500" height="400"></canvas>

    <button type="button">Button</button>

I am trying to include this code in a WordPress post, and I have managed to do so (with both the 'WPCode' and 'Insert HTML Snippet' plugins). As long as I only have one figure it works fine, but when I try to add the figure one more time later in the post, it stops working. I should have two buttons and two figures, but instead it is two buttons and just one canvas.
It seems like the two code snippets interfere with each other. If I remove the first one, the second one works just fine. How can I include two identical figures so that they don't interfere?
I have tried inserting two independent HTML code snippets in two different WordPress blocks, expecting them to function independently.

A: If you place the same code twice you are calling the same function at different points and still only referencing the first canvas block while having two blocks with the same id. Set the second block to have the id of canvas2 or similar as below.
Add the canvas block where you first inserted it:
<canvas id="canvas" width="500" height="400"></canvas>

<button type="button">Button</button>

Add the canvas2 later in the article:
<canvas id="canvas2" width="500" height="400"></canvas>

<button type="button">Button</button>

Add the new script at the very end of the article in another code snippet block:


text:
Q: wp.getComments is returning nill, when i called from my iphone app i have called wp.getComments  from my iphone app, but its returning nil,,
following r my parameters can anybody tell me where i gone wrong
NSDictionary *DicCommentStructure = [NSDictionary dictionaryWithObjectsAndKeys:@"",@"Approved",@"50",@"10",nil];

    // Send XMLRPCRequest to the server
    NSArray *arrParameters = [NSArray arrayWithObjects:@"1", @"username", @"password",DicCommentStructure, nil];
    NSString *strServer = [[[NSString alloc] initWithString:@"http://xyz.com/xmlrpc.php"] autorelease];         // the server
    NSString *strMethod = [[[NSString alloc] initWithString:@"wp.getComments"] autorelease];                        // the method
    XMLRPCRequest *objXMLRPCRequest = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:strServer]];
    [objXMLRPCRequest setMethod:strMethod withObjects:arrParameters];

thanx in advance!!


text:
Q: Using Type objects as Type Parameters for Generics in C# I cannot find a way to use a first-class Type object (System.Type instance) as a Type Parameter in a generic construction in C# 3.0 / .NET 3.5. Below is a simplified example of what I want to do:
public void test()
{
    Type someType = getSomeType(); // get some System.Type object

    MyGeneric<someType> obj = new MyGeneric<someType>();  // won't compile
}

Is there any way to use the someType object as a type parameter for a generic?

A: You're trying to determine your type argument at runtime.  .Net generics require that the type arguments are known at compile time. There's really no way to do that outside of switching on the type. You may be able to get a handle to the method via reflection and invoke it, but that's ugly.

A: You can dynamically create an instance of the type :
public void test()
{
    Type someType = getSomeType(); // get some System.Type object
    Type openType = typeof(MyGeneric<>);
    Type actualType = openType.MakeGenericType(new Type[] { someType });
    object obj = Activator.CreateInstance(actualType);
}

However you can't declare a variable of this type, since you don't know the actual type statically.


text:
Q: IBM Worklight v 5.0.6 - Can't navigate multipages on Windows Phone 7.5 environment Hi I'm having trouble with WP 7.5 application development in IBM Worklight v 5.0.6.
I used MultiPageApp Project from ftp://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v506/wl_gs_all_samples.zip for my experiment.
There are many problems I had :
First Problem
I built WP 7.5 environment in worklight without editing the code. Then I run it in MS Visual Studio 2012 with Emulator 7.1 256MB. The problem is only the content of  from MultiPageApplication.html appeared.
MultiPageApplication.html
<!DOCTYPE html>

        <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" name="viewport">
        <title>MultiPageApplication</title>
        <link href="wlclient/css/wlclient.css" rel="stylesheet">
        <link href="images/favicon.png" rel="shortcut icon">
        <link href="images/apple-touch-icon.png" rel="apple-touch-icon">
        <link href="css/MultiPageApplication.css" rel="stylesheet">

Multi page app

MultiPageApplication.js
var pagesHistory = [];
var currentPage = {};

function wlCommonInit(){

    $("#pagePort").load("pages/MainPage.html", function(){
        currentPage.init();
    });
}

At last I solve this by change the URL of jquery load API (manually in MS Visual Studio 2012) from
$("#pagePort").load("pages/MainPage.html",

to
$("#pagePort").load("default/pages/MainPage.html",

Although the code is working, another problem is

Files in native/www are regenerated every time the application is
  built, so any changes made to these files are lost.

what should I do to make the URL correctly generated?
Second Problem
When I want to navigate page from MainPage.html to Page1.html by pressing the "Load Page1" button,
the Page1.html won't load because the method 'init' in MultiPageApplication.js doesn't work. And I got this error from the output log in MS Visual Studio 2012:
Log:"Error in error callback: File564653615 = TypeError: Object doesn't support property or method 'init'"

I've tried changing the jQuery embedded in Worklight with jQueryMobile jquery-1.9.1.min.js and jquery.mobile-1.3.2.min.js, but the same problem occured.
so, how should I fix this problem? Is it because the jQuery embedded in Worklight doesn't work in Visual Studio?
Thanks

A: Please try the solution described here: jQuery Mobile changePage() not working in Windows Phone
Namely:
open jquery.mobile-1.3.2.js and refactor the following:
-        var uri = url ? this.parseUrl( url ) : location,
-          hash = this.parseUrl( url || location.href ).hash;
+        var uri = this.parseUrl( url || location.href ),
+          hash = uri.hash;

and:
-        return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash;
+        return uri.protocol + uri.doubleSlash + uri.host + uri.pathname + uri.search + hash;

Note that I only checked this with the changePage method, but hopefully this fixes the file location for everything, including what you are experiencing.
Note: Be sure to return the application to its original state.


text:
Q: SnapView in a Magazine reader (Windows 8) I am developing a Magazine reader. The users first chooses a magazine, then a issue and the issue content is shown as a series of images (1 image = 1 page) in a FlipView.
How would you display the issue detail in SnapView? Showing the image for a page does not make much sense, is not readebla.e

A: Your page should be not image but composition of text and illustrations. Then you may reflow it to any screen size and orientation, including SnapView (which is fine approximation of sidebar in page layout).

A: You can show list of images for the specific issue in a blured list like a film ribbon.
Also you can add a tip, "In snapped mode images cant be viewed well, please change the view mode"
By the way, i completely agree with Serg Rogovtsev.


text:
Q: Where to start when designing an application that allows plugins I'm building an application, and I'm thinking long-term I would like to be able to allow plugin support. The application I'm creating is a Java based application. How could I allow plugins using a scripting language, or is it better to require plugins to use Java?
Would I need to create some sort of plugin interface to allow the use of plugins?
Any ideas of references of where to start?

A: If you ask me, plugins using Java is better as it is relatively easier than scripting languages. You have to provide some sort of interface to the plugins. After you successfully implemented the plugin architecture, it is also useful for yourself to implement extra-functionality to your application, without breaking the existing code. See how NetBeans or Eclipse works. Those softwares load a number of files in the name of "packages" during start-up. Those packages are actually a kind of plugins. Alternatively, implementing a successful plugin architecture require quite some effort and costs performance (see the load times of Eclipse).
https://stackoverflow.com/questions/465099/best-way-to-build-a-plugin-system-with-java
http://www.javaranch.com/journal/200607/Plugins.html

A: If you, or others with similar skills will be writing the plugins, then why not stay with the host language? If your application addresses a particular (non-software) area of expertise, and you want to give end-users the ability to write their own plugins, then a custom scripting language, well suited to expressing solutions in the end-users' domain of expertise, could make the plugin interface more accessible to them.
In your design you'll need to consider what parts of your application you want to expose to the plugin interface, and how to limit the potential damage from a badly written plugin. Those answers will guide you to the design of the interface.


text:
Q: how we can get url using jquery or javascript? i have url like
http://www.abc.com/xyz/aaa/bbb/login.php?id=23
i want to take upto
http://www.abc.com/xyz/aaa/bbb
How we can do this with javascript / jquery?

A: Here is one possible solution:
var result = url.substring(0, url.lastIndexOf("/"));

Here is another (not the best, however) solution:
var result = url.split("/").slice(0, -1).join("/");

A: To get the current window URL you can use:
window.location.href;
Ad to extract a sub part from it till the last / of you can use the following script:
<script type="text/javascript">
var currUrl = window.location.href;
var modUrl =currUrl.substring(0,currUrl.lastIndexOf("/"));
//modUrl =currUrl.substring(0,currUrl.lastIndexOf("bbb"));  //Incase you have some other criteria to extract the sub URL.
</script>

Hope it helps.


text:
Q: Функция обращается ко всем элементам, а не к выбранному Написал функцию, которая ищет input и присваивает css-свойство соседствующему с ним label. Функция вместо того, чтобы поочерёдно искать все инпуты и рядом стоящие label, берёт самый первый input, делит его ширину на 2.35 и присваивает всем label значение первого инпута.
$(function() {
    var input = $('.input-holder input');
    var width = input.width();
    var label = ('.input-holder input + label');
    label.css('left', width / 2.35);
});

HTML:

    <input id="takeoff_place" class="place focus-input" type="text">
    Пункт отправки
    flight_takeoff

Как это исправить?

A:

$(function() {
  var input = $('.input-holder input');
  var width = input.width();
  var label = $('.input-holder label');
  label.css({
    'left': width / 50,
    'color': 'red'
  });
});

  <input id="takeoff_place" class="place focus-input" type="text">
  Пункт отправки
  flight_takeoff


text:
Q: What is support and service method in java What is support and service method. What is the different between them and can you guys provide sample java code.
I did small research, according to my guess support method is set private or protected visibility to a method?. I'm not sure is it correct.

A: They're pretty arbitrary terms, not directly related to visibility. For example, a "support method" might be used throughout an application, but not really called a "service".
IMO a "service method" is something explicitly designed for use from outside of the application, exposed via a remote procedure call, URL, etc.
A "support method" is just that, something that's used as a utility, but I wouldn't necessarily restrict its visibility or make an assumption. For example, a client library might call service methods via RPC, but the application serving the requests, and client library, and the client application might make use of some of the same support ("utility") methods to perform useful domain- or application-specific tasks.

A: Never heard of these terms as belonging to paradigms and as such having some relation to each other. Interpreting your statement, a service method might be the public API method provided, and a support method might be the internal method of an API implementation.
// API, not to be overriden, but service method for use:
public final void paint();

// One implementation, child of base class
@Override
protected void onPaint(Graphics2D g2, Context ctx) {
    ...

// Base class
protected void onPaint(Graphics2D g2, Context ctx) {
}
public void paint() {
    ...
    onPaint(g2, ctx);
}

This design pattern (service & requirement) allows to pass contextual information to the implementation and full control on usage and especially implementation.


text:
Q: Adonis session not persisting between tests I've built a simple eCommerce application on Adonis JS. I'm trying to test the cart functionality where if the user adds an item to the cart and if it's already there in the cart, then it should simply increase the quantity. For this, I'm hitting the cart API twice to check the functionality. However, my session isn't persisted between requests because of which each time I receive only one quantity.
test('should increase the quantity if user tries to add the same item to cart', async ({ assert, client }) => {
    const menu = await createMenu(client);
    // Simply adds to cart
    await client.post(`/cart/${menu.id}`).send({
        quantity: 1,
    }).end();

    // It should increase the quantity to 2 now.
    const response = await client.post(`/cart/${menu.id}`).send({
        quantity: 1,
    }).end();

    response.assertStatus(200);
    // There should be only one item in cart
    assert.equal(response.body.data.items.length, 1);
    // And quantity of that item should be 2.
    assert.equal(response.body.data.items[0].quantity, 2);
});

A: The way to do it was to use supertest
const supertest = require('supertest');

test('should increase the quantity if user tries to add the same item to cart', async ({ assert, client }) => {

    const BASE_URL = 'http://localhost:4000';
    const agent = supertest.agent(BASE_URL);

    const menu = await createMenu(client);

    // Simply adds to cart
    const result1 = await agent.post(`/cart/${menu.id}`).send({
            quantity: 1,
    }).withCredentials();

    assert.equal(result1.status, 200);

    // It should increase the quantity to 2 now.
    const result2 = await agent.post(`/cart/${menu.id}`).send({
            quantity: 1,
    }).withCredentials();

    assert.equal(result2.status, 200);
    // There should be only one item in cart
    assert.equal(result2.body.data.items.length, 1);
    // And quantity of that item should be 2.
    assert.equal(result2.body.data.items[0].quantity, 2);
});


text:
Q: Android handler can't receive message first time I created two work thread and send message to UI handler,first time Handler   received message from one thread early,but miss the second message later.And when I tried again, all message can be received.Why did second message was miss in first time?
this is UI handler:
   handler=new Handler(){
    @Override
    public void handleMessage (Message msg)
    {
        switch (msg.what){

            case 0:{
                if(msg.arg1==10){
                   //process second thread

                }
                else
                 {//first thread

                 }
            }
            break;
        }
        super.handleMessage(msg);
    }`

this is threand_one handler:
  void get_list(String Msg,double price){

    class runable implements   Runnable{
        @Override
        public void run() {
            Message msg=HelpedHandle.obtainMessage();
            try {
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                int len =40+Msg.length;
                byte  Data[] =generate_Sokect_header(len,NEW_REQUIRE,id);
                long msglen=Msg.length;
                Data=Concat(Data,longTobyte(msglen));
                Data=Concat(Data,doubleTobyte(price));
                Data=Concat(Data,doubleTobyte(0));

                Data=Concat(Data,Msg);
                out.write(Data);
                msg.what =0;
                msg.arg1=-1;

            }
            catch (IOException e){
                msg.what = -1;
            }
            msg.sendToTarget();
        }
        public byte Msg[];
        public double price;
    }
    runable runable1=new runable();
    runable1.Msg=Msg.getBytes();
    runable1.price=price;
    pthreadPool.execute(runable1);

}

This is thread_2:
`void get_context(){
    class runable implements   Runnable{
        @Override
        public void run() {
            while(true) {
                try {
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    int length = inputStream.read(recive);
                    byte flag[] = new byte[4];
                    System.arraycopy(recive, 0, flag, 0, 4);
                    byte len[]= new byte[8];
                    System.arraycopy(recive,8, len, 0, 8);
                    long check=byteTolong(len);
                    if(length!=check)
                        continue;
                            Message msg = handler.obtainMessage();
                            msg.what=0;
                            msg.arg1 = 10;
                            msg.setData(bundle);
                            msg.sendToTarget();
                   }
             }catch{}
     }
   }
 pthreadPool.execute(new runable());
}


text:
Q: Liquibase changesets can not be rerun Our Liquibase script can not be rerun because underlying column is already gone
Consider the following changesets:

*

*A table "foo" is created, and "domain" is one of the columns in this table;

*A constraint (in form of an index) is placed on the column "domain";

*Column "domain" is dropped from the table "foo".

Now when we try to rerun all liquibase scripts (over already existing DB structure), changeset 2 fails with
[ERROR]      Reason: liquibase.exception.DatabaseException: ERROR: column "domain" named in key does not exist

all because the "domain" column in the actual DB is already gone before changeset 2 is run.
Is there any better way to make these changesets runnable other than recreating the "domain" column in the table so that all 3 changesets can run?

*

*there are hundreds of changesets in the system besides the 2 above;

*the solution is strongly preferred to avoid any manual steps because there are dozens of environments in which the changesets must be rerun;

*In a perfect world, a developer would have placed a preConditions on changeset 2 to check that not only the index is missing, but the underlying column exists, but we have to deal with what we have. It is my understanding that rewriting existing changesets is strongly discouraged in liquibase.

A: You can always add a preCondition to the changeSets #2 and #3 to check that the domain column exists, e.g.:
    <preConditions onFail="MARK_RAN">
        <columnExists tableName="foo" columnName="domain"/>
    </preConditions>

If these changeSets will start to fail with the "different checksum error", than you can always provide the new checksum or just add <validCheckSum>ANY</validCheckSum>.
This way you'll be able to run these changeSets in all environments you need.
Rewriting the changeSets is discouraged, but writing preConditions for the changeSets is quire encouraged.

A: According to the comment, your problem is changing liquibase scripts directory location.
What actually happens is liquibase will compare liquibase script's relative path when executing these changesets in your scripts. You can find this relative path in the databasechangelog table and under column filename.
First thing you should understand is problem is not with the checksum. So it will not solve your problem.
The easiest thing that you can do is change the values in column filename in table databasechangelog. If you have more than one liquibase script files I suggest you to change them one by one. Simple sql query like this can do the job.
update databasechangelog set filename='<new_filename>' where filename='<old_filename>'

Note: You can make the situation worse if you did it wrong. Make sure you double check everything before you make any changes.


text:
Q: is there any CHM/html reference for unix/linux C functions (like in man)? i need such reference preferable in CHM format or any other fast-access format. I need all *nix functions + pthread + all sockets (network) functions.
Searching the internet i did not find any, so working from my home on my unix projects is too slow.. i need to man() all the funcs i need in my remote shell.
Thank you

A: I don`t know if such exist. You can build one by yourself - man2html ( available on Unix and Linux ) will produce a html version which can be later converted to chm with HTML Help.

A: Rather than reading Linux-specific man pages I would simply read the documentation in the standard:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/contents.html

A: Yes, there is one since at least 2011. ;-)
(http://onnerby.se/~daniel/chm/)


text:
Q: Simple C Preprocessor substitution So i wrote a simple program to try and get a more fundamental understanding of the #define macro and i want to know what the difference between these two programs are and is there any fundamental reason to use the third program? :
#include<stdio.h>
#define x 7

int main()
{
    int i;
    i = x * x * x;
    printf("%d", i);
    return 0;
}

This program prints out 343 because 7 * 7 * 7 = 343
#include<stdio.h>
#define x 5+2

int main()
{
    int i;
    i = x * x * x;
    printf("%d", i);
    return 0;
}

This program prints out 27 from order of operations.
EDIT
A way to force the second one to print out 343 we could add brackets so we could do the following:
#include<stdio.h>
#define x (5+2)

int main()
{
    int i;
    i = x * x * x;
    printf("%d", i);
    return 0;
}

Would there be any reason to do it this instead of the first way?

A: The macro substitution replaces the text as it is.
Thus the C compiler sees the code
i = 7 * 7 * 7;       // when #DEFINE x 7

in one case, and the following in another
i = 5+2 * 5+2 * 5+2; // when #DEFINE x 5+2

(And due to simple arthihmetic precedence the results are trivially different.)

To make them equivalent one would need to add parenthesis, such as (preferred, see comment):
#define x (5+2)

although the following would "suffice" here
i = (x) * (x) * (x);


text:
Q: Geolocation not working on iOS with Meteor It's been 5 hours i'm struggling with Meteor.
I want to get Geolocation.latLng(). It works perfectly on my browser, I coupled it with GoogleMaps to put a marker on a map. I'm following this example and didn't touch it much.
When I compile on iOS the Geolocation returns weird errors on my simulator (iPhone 6 / iOS 8.3) such as Geolocation failed : Position retrieval timed out, sometimes it's another one which's very similar (note : it asks me if i want to share my location when i launch the app, and i accept)

Sometimes it says it just compiled and I get an old version of my app too.
What's happening ? Is it me or it's really THAT buggy once you try to make a real world project ?
This to-do list tutorial looked very magic but once you understood how it works and you try something real, it's kind of disappointing ... Sounds very unstable and not ready.
Don't hesitate to tell me if i'm doing something wrong ;)
UPDATE : i've searched a lot more and i'm now trying to setup differently the timeout limit of the geolocation package to avoid this error.
Sadly, i realized timeout : Infinity is the default value of the source : sounds like an issue.
Nothing is working so far. If anyone has an idea, let me know on that too ...

A: I finally made it work. First I realized you have to setup the accessRule thank to Lucas's answer but it wasn't enough.
// In a mobile-config.js in the project
App.accessRule('*://maps.googleapis.com/*');

The iOS Simulator provided by Apple seems to have bugs : the position isn't retrieved correctly, or not at all. It's only working if i set the the Debug > Location to City Ride ; even Apple wasn't working properly on my hand.
If nothing works for you, just try all the possible Location, it might be the problem.

A: Have you define an accessRule in your mobile-config.js? If not, try this.
App.accessRule('*://maps.googleapis.com/*');

A: Here, clone this sample app I put together a while back:
https://github.com/ffxsam/whats-nearby
It works on desktop as well as mobile. All you have to do is add a settings.json and add your Google Places API key in there.
{
  "apiKey": "...."
}


text:
Q: Как реализовать авторизацию по токену в .net core? Есть фрон на angular 2, есть бэк на .net core. Необходимо реализовать авторизацию по токену, через сторонние сайты типо вк. после чего все общение бэка с фронтом должно осуществлятся через токен. подскажите как реализовать

A: Во первых надо установить пакеты IdentityServer4.
Сами пакеты:
IdentityServer4
IdentityServer4.AccessTokenValidation
IdentityServer4.AspNetIdentity
IdentityServer4.EntityFramework

Далее необходимо сделать по образцу: https://gist.github.com/gromanev/4da63142825798927375a3da342e65b8
Опять таки важно сопоставлять с официальной документацией и предложенным кодом, ведь я использую внутри свои сервисы которые не привожу в листинге. И Вам предстоит работа с определением где мой код, а где код IdentityServer`a.
Удачи!


text:
Q: Error : malloc():memory corruption in Comparison function for sort The following code is to print the largest number from a list of integers. I am getting:
 *** Error in `./a.out': malloc(): memory corruption: 0x0000000000bfe070 ***

on the list (20 zeros):
 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

However in the above if I put some non zero elements I do not get the error.
This is my code for the  comparison function :
bool comp(int a,int b)
{
     if(a == b)
         return true;
     stringstream ss;
     ss << a;
     string a1 = ss.str();
     stringstream sss;
     sss << b;
     string b1 = sss.str();
     int i = 0;
     int l1 = a1.length();
     int l2 = b1.length();
     while(i < l1 && i < l2)
     {
         if(a1[i] > b1[i])
             return true;
         if(a1[i] < b1[i])
             return false;
         i++;
     }
     if(l1 == l2)
         return true;
     if(l1 < l2)
         if(b1[l1] > a1[0])
             return false;
         else
             return true;
     else
         if(a1[l2] > b1[0])
             return true;
         else
             return false;
}

I am using the stl
 sort(nums.begin(),nums.end(),comp);

where nums is a vector of integers.
EDIT 1 :
This is the entire code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<sstream>

using namespace std;
bool comp(int a,int b)
{
if(a == b)
    return true;
stringstream ss;
ss << a;
string a1 = ss.str();
stringstream sss;
sss << b;
string b1 = sss.str();
int i = 0;
int l1 = a1.length();
int l2 = b1.length();
while(i < l1 && i < l2)
{
    if(a1[i] > b1[i])
        return true;
    if(a1[i] < b1[i])
        return false;
    i++;
}
if(l1 == l2)
    return true;
if(l1 < l2)
    if(b1[l1] > a1[0])
        return false;
    else
        return true;
else
    if(a1[l2] > b1[0])
        return true;
    else
        return false;
}
void largestNumber(vector<int>& nums)
{

sort(nums.begin(),nums.end(),comp);
/*string s = "";
vector<int>::iterator it = nums.begin();
while(it != nums.end())
{
    stringstream ss;
    ss << *it;
    s = s+ss.str();
    it++;
}
return s;*/
}

int main()
{
int n;
cin>>n;
vector<int> arr(n);
for(int i = 0;i<n;i++)
    cin>>arr[i];

largestNumber(arr);/*
string s = largestNumber(arr);
cout<<s<<endl;*/
}

A: Your comp function violates the strict weak ordering rule. Sort requires that the compare function should meet the strict weak ordering rule. If that promise is broken, so is the promise of std::sort to behave correctly. Infact when I compile this under MSVC (VS2015) I get a assertion failure that the compare function doesn't meets the ordering condition.
For eg this line:
 if(a == b)
     return true;

clearly violates the condition. Check this post for more insights.
BTW if you just want to sort the integers in lexicographic order you can just do
bool comp(int a,int b)
{
    return to_string(a) < to_string(b);
}

If you want the equivalent of "bigger number first", just swap the < with >

A: I have used your comp function and created a sample case-study to examine the error. However, I didn't get any error for the array of zeros case. Please check sample program.
Error
However, below scenario causes run-time error.
// Pay attention: Array stores numbers in descending order.
// If we stored in ascending order, there won't be a problem.
for(int i=20; i>0; ++i)
    v.push_back(i);

I hope this would be helpful to find solution.
Sample program
#include <vector>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iterator>

using namespace std;

bool comp(int a,int b)
{
     if(a == b)
         return true;
     stringstream ss;
     ss << a;
     string a1 = ss.str();
     stringstream sss;
     sss << b;
     string b1 = sss.str();
     int i = 0;
     int l1 = a1.length();
     int l2 = b1.length();
     while(i < l1 && i < l2)
     {
         if(a1[i] > b1[i])
             return true;
         if(a1[i] < b1[i])
             return false;
         i++;
     }
     if(l1 == l2)
         return true;
     if(l1 < l2)
         if(b1[l1] > b1[l1-1])
             return false;
         else
             return true;
     else
         if(a1[l2] > a1[l2-1])
             return true;
         else
             return false;
}

int main(int argc, const char *argv[])
{
    vector<int> v;
    for(int i=0; i<20; ++i)
        v.push_back(0);
    sort(v.begin(), v.end(), comp);
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    return 0;
}


text:
Q: Jquery remove effect? Is there any way to remove effect for xxxx element?
For example, when I do this:
$('#xxxx').effect( "bounce",{times:3,distance:20},1000);

and use a setTimeout for display/hide this element - there is problem with bounce effect. When I move very fast on element that calls this effect and start setTimeout method - I think that bounce effect block timer and do not let setTimeout` to finish.
I don't want to stop() effect/animation, i need something that will remove it when mouse leave button.


text:
Q: laravel не устанавливается пакет почему после команды
php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLaravel5"

у меня в папке config не появляется файл image.php
инструкция отсюда
у меня папка проекта laravel ,в этой папке композер и папка projects и в ней файлы, может это на что-то влияет?
[![введите сюда описание изображения][2]][2]

A: Очистить кэш
    php artisan config:cache
    composer update
    php artisan config:cache
    php artisan vendor:publish


text:
Q: Bindtooltip on hover and permanent in leaflet Is it possible to bind 2 different tooltips on a polygon in leaflet?
One on hover and the other set to permanent.
Right now in my code it's taking only one.

A: You can bind any number of tooltips. Answering your specific question, you can define one tooltip to be permanent.
L.rectangle([[48.84, 2.34], [48.86, 2.36]]).bindTooltip("test", {
    permanent: true
}).addTo(map);

L.rectangle([[48.84, 2.34], [48.86, 2.36]]).bindTooltip("hello", {
    permanent: false
}).addTo(map););

See an example here:
https://jsfiddle.net/9d9pcL1a/


text:
Q: No entiendo porque creo que ya uso este tipo de consultas y esta me da error Consulta me genera este error:

Warning: mysqli_query() expects parameter 1 to be mysqli, object given
  in C:\xampp\htdocs\sistema\mi sistema\mi sistema\consultas.php on line
  90
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
  null given in C:\xampp\htdocs\sistema\mi sistema\mi
  sistema\consultas.php on line 91

Mi codigo
$query=$db->query("SELECT * FROM accidente");
$result = mysqli_query($query, $db);
    while ($rows = mysqli_fetch_array($result))

A: La Línea  $query=$db->query("SELECT * FROM accidente") básicamente lo que está haciendo es ejecutar la  consulta pasada por parámetro y el valor devuelto será un mysqli_result (si se ejecuta correctamente) luego le asigna a su variable $query (en caso que exista algún error retornará false)
En la línea $result = mysqli_query($query, $db) ejecutas la consulta en teoría nuevamente , pero hay un error y es que el orden de los parámetros son mysqli_query($db,$query) pero no tu variable ya que si se ejecuto con éxito lo primero tendrás un mysqli_result, en caso de errores un valor FALSE y no una consulta en sí.
Para solucionar esto en primer lugar debe elegir una opción para realizar la query si elige la primera su código sería
$query=$db->query("SELECT * FROM accidente");
while ($rows = $query->fetch_array(MYSQLI_ASSOC)){
   print_r($rows);
}

Si elige la segunda forma sería.
$result = mysqli_query($db,"select * from accidente");
while ($rows = mysqli_fetch_array($result)){
   print_r($rows);
}

Como nota adicional sugiero emplear sentencias preparadas con
  extensión PDO y no estaría de más leer ¿Cómo evitar la
  Inyección SQL ?

A: Hola amigo creo que tu problema es que esta al revez en esta linea
$result = mysqli_query($query, $db);

Si miras la documentación de PHP veras lo siguiente:
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

http://php.net/manual/es/mysqli.query.php
espero te sea de ayuda la respuesta para la solucion seria esta:
$result = mysqli_query($db, $query);


text:
Q: Marca D'agua em imagens com PHP Procuro colocar uma Marca D'agua em cada foto que faço upload, porém preciso saber como por este código eu pego o nome da foto depois que foi colocada a Marca D'agua para eu gravar no banco de dados, uma vez que a classe que faz funcionar este código utiliza MD5 para renomear a foto.
require_once('RDSImage.php');
$image = new RDSImage();
$image->setSourceImage("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/".$imvfoto."");
$image->setPosition(10,10);
$image->setWaterMark('marca.png'); // Texto da legenda
$image->setDestination("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/"); // pasta onde quero salvar a imagem
$image->create();

Este é o trecho da classe que renomeia a foto. Se tiver como impedir que ela seja renomeada, fica até melhor.
private function _generateFileName($filename = null)
    {
        if (!$filename) {
            return $this->getDestination()
                . '/'
                . md5(uniqid(time()))
                . '.'
                . $this->sourceImageExtension;
        }

        return $this->getDestination()
            . '/'
            . $filename
            . '.'
            . $this->sourceImageExtension;
    }

Tentei alterar esta parte aqui:
if (!$filename) {
            return $this->getDestination()
                . '/'
                . md5(uniqid(time()))
                . '.'
                . $this->sourceImageExtension;
        }

Para:
if (!$filename) {
            return $this->getDestination()
                . '/'
                . $filename
                . '.'
                . $this->sourceImageExtension;
        }

Porém ele grava apenas a extensão, exemplo: .jpg
Segue a classe completa:
<?php

/**
 * RDS Image is a PHP class to manipulate images
 *
 * PHP Version 5.3.8
 *
 * @category Pet_Projects
 * @package  RDSImage
 * @author   Rodrigo dos Santos <falecom@rodrigodossantos.ws>
 * @license  http://www.opensource.org/licenses/bsd-license.php BSD License
 * @link     www.rodrigodossantos.ws
 */

/**
 * RDS Image is a PHP class to manipulate images
 *
 * @category Pet_Projects
 * @package  RDSImage
 * @author   Rodrigo dos Santos <falecom@rodrigodossantos.ws>
 * @license  http://www.opensource.org/licenses/bsd-license.php BSD License
 * @version  Release: <1.0>
 * @link     www.rodrigodossantos.ws
 */
class RDSImage
{
    protected $sourceImage;
    protected $sourceImageWidth;
    protected $sourceImageHeight;
    protected $sourceImageExtension;
    protected $newWidth;
    protected $newHeight;
    protected $destination;
    protected $waterMark;
    protected $addWaterMark = false;
    protected $addText = false;
    protected $fontSize = 10;
    protected $fontColor = array(255, 255, 255);
    protected $fontName;
    protected $trueTypeFont = false;
    protected $positionX = 20;
    protected $positionY = 20;
    protected $text;

    /**
     * Defines the source image that is going to be used.
     * Also uses the methods setSourceImageExtension to define the image's extension
     * and getSourceImageSize to define the width and height
     *
     * @param string $image Path to the image
     *
     * @throws InvalidArgumentException If an unsupported image type is informed
     *
     * @return void
     */
    public function setSourceImage($image)
    {
        $this->sourceImage = $image;

        $extension = array();

        if (!@preg_match('@\.(jpg|jpeg|png|gif)@', $this->sourceImage, $extension)) {
            throw new InvalidArgumentException('type of image unsupported');
        }

        $this->setSourceImageExtension($extension);
        $this->getSourceImageSize();
    }

    /**
     * Returns the source image's name and path
     *
     * @return string
     */
    public function getSourceImage()
    {
        return $this->sourceImage;
    }

    /**
     * Gets the source image width and height
     *
     * @return void
     */
    protected function getSourceImageSize()
    {
        $src_size = getimagesize($this->sourceImage);
        $this->sourceImageWidth = $src_size[0];
        $this->newWidth = $src_size[0];
        $this->sourceImageHeight = $src_size[1];
        $this->newHeight = $src_size[1];
    }

    /**
     * Set the source image's extension
     *
     * @param array $extension result array from preg_match
     * function called in setSourceImage method
     *
     * @return void
     */
    protected function setSourceImageExtension($extension)
    {
        $this->sourceImageExtension = $extension[1];
    }

    /**
     * Returns the source image's extension (jpg, gif, png)
     *
     * @return string
     */
    public function getSourceImageExtension()
    {
        return $this->sourceImageExtension;
    }

    /**
     * Returns the source image's width
     *
     * @return int
     */
    public function getSourceImageWidth()
    {
        return $this->sourceImageWidth;
    }

    /**
     * Returns the source image's height
     *
     * @return int
     */
    public function getSourceImageHeight()
    {
        return $this->sourceImageHeight;
    }

    /**
     * Set the new image's width and
     * calculates the proportional width if only the height is not provided
     *
     * @param int $width The new image's width (pixels)
     *
     * @return void
     */
    public function setNewWidth($width)
    {
        $this->newWidth = $width;

        if (!$this->getNewHeight()) {
            $this->newHeight = ( $this->getSourceImageHeight() * $this->newWidth )
                / $this->getSourceImageWidth();
        }
    }

    /**
     * Returns the new image's width
     *
     * @return type
     */
    public function getNewWidth()
    {
        return $this->newWidth;
    }

    /**
     * Set the new image's height and
     * calculates the proportional height if only the width is not provided
     *
     * @param int $height The new image's height (pixels)
     *
     * @return void;
     */
    public function setNewHeight($height)
    {
        $this->newHeight = $height;

        if (!$this->getNewWidth()) {
            $this->newWidth = ($this->getSourceImageWidth() * $this->newHeight )
                / $this->getSourceImageHeight();
        }
    }

    /**
     * Returns the new image's height
     *
     * @return mixed;
     */
    public function getNewHeight()
    {
        return $this->newHeight;
    }

    /**
     * Set the destination folder
     *
     * @param string $destination Destination folder's path
     *
     * @return void
     */
    public function setDestination($destination)
    {
        $this->destination = $destination;
    }

    /**
     * Returns the destination folder
     *
     * @return string
     */
    public function getDestination()
    {
        return $this->destination;
    }

    /**
     * Generates the new filename for the image if none is provided
     * and prepends the destination folder to the filename.
     *
     * @param string $filename The new image's name
     *
     * @return string
     */
    private function _generateFileName($filename = null)
    {
        if (!$filename) {
            return $this->getDestination()
                . '/'
                . md5(uniqid(time()))
                . '.'
                . $this->sourceImageExtension;
        }

        return $this->getDestination()
            . '/'
            . $filename
            . '.'
            . $this->sourceImageExtension;
    }

    /**
     * Set the font size to use on the image
     *
     * @param mixed $fontSize The font size
     *
     * @return void
     */
    public function setFontSize($fontSize)
    {
        $this->fontSize = $fontSize;
    }

    /**
     * Returns the font size to use on the image
     *
     * @return mixed
     */
    public function getFontSize()
    {
        return $this->fontSize;
    }

    /**
     * Set the position X and Y for the text to be used on the image
     *
     * @param int $positionX The position X where the text will be showed
     * @param int $positionY The position Y where the text will be showed
     *
     * @return void
     */
    public function setPosition($positionX, $positionY)
    {
        $this->positionX = $positionX;
        $this->positionY = $positionY;
    }

    /**
     * Returns the position X
     *
     * @return int
     */
    public function getPositionX()
    {
        return $this->positionX;
    }

    /**
     * Returns the position Y
     *
     * @return int
     */
    public function getPositionY()
    {
        return $this->positionY;
    }

    /**
     * Defines the font color in RGB format, where each index represents
     * a part of the color's code. Ex: array(255, 255,255) is white.
     * For a RGB chart please see http://www.tayloredmktg.com/rgb/
     *
     * @param array $color Font's color code in RGB format
     *
     * @return void
     */
    public function setColor(array $color)
    {
        $this->fontColor = $color;
    }

    /**
     * Returns the font color's array in RGB format
     *
     * @return array
     */
    public function getColor()
    {
        return $this->fontColor;
    }

    /**
     * Define if a true type font is going to be used
     *
     * @param boolena $flag true or false
     *
     * @return void
     */
    public function trueTypeFont($flag = true)
    {
        $this->trueTypeFont = $flag;
    }

    /**
     * Is a true type font going to be used?
     *
     * @return boolean
     */
    public function isTrueTypeFont()
    {
        return $this->trueTypeFont;
    }

    /**
     * Set the font to be used on the image
     *
     * @param string $font The font name like 'Arial', 'Verdana', etc.
     *
     * @return void
     */
    public function setFontName($font)
    {
        $this->fontName = $font;
    }

    /**
     * Returns the font to be used on the image
     *
     * @return string
     */
    public function getFontName()
    {
        return $this->fontName;
    }

    /**
     * Set the text to be written on the image
     *
     * @param string $text A text or phrase
     *
     * @return void
     */
    public function setText($text)
    {
        $this->addText = true;
        $this->text = $text;
    }

    /**
     * Returns the text to be written on the image
     *
     * @return string
     */
    public function getText()
    {
        return $this->text;
    }

    /**
     * Writes an text to the image
     *
     * @param string $image The image's path
     *
     * @return void
     */
    protected function addText($image)
    {
        if ($this->isTrueTypeFont()) {
            imagettftext(
                $image, $this->fontSize, 0, $this->getPositionX(),
                $this->getPositionY(), $this->fontColor, $this->fontName, $this->text
            );
        } else {

            $fontColor = imagecolorallocate(
                $image, $this->fontColor[0], $this->fontColor[1], $this->fontColor[2]
            );

            imagestring(
                $image, $this->fontSize, $this->getPositionX(),
                $this->getPositionY(), $this->text, $fontColor
            );
        }
    }

    /**
     * Sets the watermark's path
     *
     * @param string $image Path to watermark
     *
     * @return void
     */
    public function setWaterMark($image)
    {
        $this->addWaterMark = true;
        $this->waterMark = $image;
    }

    /**
     * Return the watermark' path
     *
     * @return string
     */
    public function getWaterMark()
    {
        return $this->waterMark;
    }

    /**
     * Adds a watermark to the image
     *
     * @param string $thumb Path to the water mark
     *
     * @return void
     */
    protected function addWaterMark($thumb)
    {
        $pathinfo = pathinfo($this->getWaterMark());

        switch (strtolower($pathinfo['extension'])) {
        case 'jpg':
        case 'jpeg':
            $waterMark = imagecreatefromjpeg($this->waterMark);
            break;
        case 'png':
            $waterMark = imagecreatefrompng($this->waterMark);
            break;
        case 'gif':
            $waterMark = imagecreatefromgif($this->waterMark);
            break;
        default:
            break;
        }

        $waterMarkWidth = imagesx($waterMark);
        $waterMarkHeight = imagesy($waterMark);

        imagecopy(
            $thumb, $waterMark, $this->getPositionX(), $this->getPositionY(), 0, 0,
            $waterMarkWidth, $waterMarkHeight
        );
    }

    /**
     * Creates the new image
     *
     * @param string $filename New image's name
     *
     * @return string New image's path and name
     * @throws UnexpectedValueException
     */
    public function create($filename = null)
    {
        $destination = $this->getDestination();

        if (!$destination) {
            throw new UnexpectedValueException(
                'Destination folder has not been informed'
            );
        }

        $extension = ($this->sourceImageExtension == 'jpg')
        ? 'jpeg' : $this->sourceImageExtension;

        $functions = array(
            'imagecreatefrom' . $extension,
            'image' . $extension,
        );

        $thumbnail = imagecreatetruecolor(
            $this->getNewWidth(), $this->getNewHeight()
        );

        imagecopyresized(
            $thumbnail, $functions[0]($this->sourceImage), 0, 0, 0, 0,
            $this->getNewWidth(), $this->getNewHeight(),
            $this->getSourceImageWidth(), $this->getSourceImageHeight()
        );

        $filename = $this->_generateFileName($filename);

        if ($this->addText) {
            $this->addText($thumbnail);
        }

        if ($this->addWaterMark) {
            $this->addWaterMark($thumbnail);
        }

        switch ($extension) {
        case 'jpeg':
            imagejpeg($thumbnail, $filename, 100);
            break;
        case 'gif':
            imagegif($thumbnail, $filename);
            break;
        case 'png':
            imagepng($thumbnail, $filename, 9);
        default:
            break;
        }

        return $filename;
    }

}

A: $filename é fornecido pelo método create, para ignorar o nome em MD5 basta colocar o parametro quando for criar a foto.
Exemplo de código que salva a foto como teste.jpg
require_once('RDSImage.php');
$image = new RDSImage();
$image->setSourceImage("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/teste.jpg");
$image->setPosition(10,10);
$image->setWaterMark('marca.png'); // Texto da legenda
$image->setDestination("/home/roteirodoimovelc/public_html/cp/clientes/".$cliente."/".$cod."/"); // pasta onde quero salvar a imagem
$image->create( 'teste' );

A: Se o arquivo não tiver um nome, ele vai gerar um:
if (!$filename) {
            return $this->getDestination()
                . '/'
                . md5(uniqid(time()))
                . '.'
                . $this->sourceImageExtension;
        }

Se tiver nome, ele vai usar o nome ($filename) conforme você definiu. Acredito que seja apenas tirar o "!" que fica tudo certo.
if ($filename) {
            return $this->getDestination()
                . '/'
                . $filename
                . '.'
                . $this->sourceImageExtension;
        }

Antes de vc alterar a linha . md5(uniqid(time())) ia dar problema, mas como vc passa a usar o $filename fica certo.