text:
Q: How to prove this equation (given two inequalities)? How to prove that:
$$\frac{au+bv}{a+b} < y$$
given that:
$$u<y, v < y$$
Here, a, b are positive integers and u, v and y are real numbers between 0 and 1 (inclusive).

A: Hint: After multiplying through to clear the fraction and rearranging a bit, this is equivalent to asking whether
$$a (y - u) + b (y - v)$$ is positive.

A: Geometrically the point $\alpha x+\beta y$ where $\alpha+\beta=1$ lies in the segment $[x,y]$. Take in your case
$$\alpha=\frac{a}{a+b}\quad\text{and}\quad \beta=\frac{b}{a+b}$$
Can you take it from here?

A: $$au+bv < (a+b)y$$ and thus $$\frac{au+bv}{a+b} < \frac{(a+b)y}{a+b} = y$$

A: Well the other posters have great answers but you can also see that if $v < y$ then $vb < yb$ since $b > 0$ and we can also see that $ua < ya$ for the same reason. Then we can see that:
\begin{eqnarray}
   ua +vb < ya + yb
\end{eqnarray}
From there its pretty simply algebraic manipulations to get your inequality (Remember you can do a lot of this because $a$ and $b$ are positive, otherwise we would have to reverse the inequality sign)!

A: Note that
$\dfrac{au + bv}{a + b} = \dfrac{a}{a + b} u + \dfrac{b}{a + b} v \tag{1}$
and
$\dfrac{a}{a + b} + \dfrac{b}{a + b} = 1; \tag{2}$
now if $u = v$, (1) and (2) show that
$\dfrac{au + bv}{a + b} = v < y \tag{3}$
by hypothesis; otherwise we can assume $u < v$ in which case (1) and (2) yield
$\dfrac{au + bv}{a + b} = \dfrac{a}{a + b} u + \dfrac{b}{a + b} v < \dfrac{a}{a + b} v + \dfrac{b}{a + b} v  = v < y. \tag{4}$
QED.
Points worth of note:  the restriction $0 < u, v, y < 1$ is not necessary for the result, as long as $u, v < y$;  also the expression (1) shows that $(au + bv) / (a + b)$ is in fact a weighted average of $u, v$ with coefficients $0 < a/a + b, b / a + b < 1$; the assumptions on $a, b$ easily show this to be the case.  Indeed, taking $u < v$, $(au + bv) / (a + b)$ is precisely the real number which is $b / a+ b$ of the way between $u$ and $v$, going in the positive direction, since
$u + \dfrac{b}{a + b}(v - u) = (1 - \dfrac{b}{a + b}) u + \dfrac{b}{a+ b} v = \dfrac{au + bv}{a + b}, \tag{5}$
which provides another way of seeing  $(au + bv) / (a + b) < y$.
Hope this helps.  Happy New Year to One and All,
and as always,
Fiat Lux!!!

A: Here is a generalization that you may find useful.
Suppose that $w_1, w_2 \cdots w_n>0$ and $x_1, x_2, \cdots x_n$ are any numbers. Then
if all $x_1$ are greater than $m$ and less than $M$ i.e.
$$
m < x_1, m < x_2, \cdots m <x_n$$
and
$$ x_1<M, x_2<M, \cdots x_n < M$$
Then
$$
m < \frac{w_1 x_1 + w_2 x_2 \cdots +w_n x_n} {w_1 + w_2 \cdots+ w_n} < M
$$
Proof: First consider
$$
\frac{w_1 (x_1-m) + w_2 (x_2-m) \cdots + w_n (x_n-m)} {w_1 + w_2 \cdots +w_n}$$
Each term on the numerator and denominator is positive. So the ratio is positive.
Hence
$$
0<\frac{w_1 (x_1-m) + w_2 (x_2-m) \cdots + w_n (x_n-m)} {w_1 + w_2 \cdots +w_n}
= \\
\frac{w_1 x_1 + w_2 x_2 \cdots +w_n x_n} {w_1 + w_2 \cdots+ w_n}
-
\frac{w_1 m + w_2 m \cdots +w_n m} {w_1 + w_2 \cdots+ w_n}
$$
Factor out $m$ from the second sum on the right to get
$$
0<
\frac{w_1 x_1 + w_2 x_2 \cdots +w_n x_n} {w_1 + w_2 \cdots+ w_n}
-
m
$$
The other inequality can be obtained by considering
$$
\frac{w_1 (M-x_1) + w_2 (M-x_2) \cdots + w_n (M-x_n)} {w_1 + w_2 \cdots +w_n}$$
Note:
$$
\frac{w_1 x_1 + w_2 x_2 \cdots +w_n x_n} {w_1 + w_2 \cdots+ w_n}
$$
is called the weighted average, $w_1$, $w_2$ etc. are called the weights. The result basically says that the average has to be between the min and max of the numbers whose average you are calculating.


text:
Q: MissingMethodException when passing an implementing class instead of an interface I'm developing a script on Jira workflows (using Adaptavist Scriptrunner v.6.34) and I'm facing an issue in which groovy does not accept an interface implementation as a parameter to a function whose signature allows the implemented interface.
Code
import com.atlassian.jira.issue.link.DefaultRemoteIssueLinkManager;

(...)

def remoteLink = DefaultRemoteIssueLinkManager.getRemoteIssueLinksForIssue(issue)

(issue is a build variable of type com.atlassian.jira.issue.IssueImpl)
What happens
groovy.lang.MissingMethodException: No signature of method: static com.atlassian.jira.issue.link.DefaultRemoteIssueLinkManager.getRemoteIssueLinksForIssue() is applicable for argument types: (com.atlassian.jira.issue.IssueImpl) values: [ADA-24684]
Possible solutions: getRemoteIssueLinksForIssue(com.atlassian.jira.issue.Issue)
    at Script6.run(Script6.groovy:32)

*

*The method documentation is here

*The method signature expects a parameter of type Issue (an Interface)

*The parameter I am passing is of type IssueImpl
I don't understand how groovy does not accept an interface implementation.
What I tried so far

*

*Conversion of my variable to type Issue

*Casting my variable to type Issue

*Conversion of my variable to type MutableIssue (the first-level inherited interface)

*Casting my variable to type MutableIssue

*Conversion of my variable to type AbstractIssue (the first-level inherited class)

*Casting my variable to type AbstractIssue
All those situations returned the original exception.
I've printed the methods and interfaces of the classes and everything matches the documentation, so no version mismatch here.
I don't know what else to do as it is going beyond my java/groovy knowledge. I've asked to colleagues which are java experts and they are not finding a reason for this behaviour. Any ideas?

A: DefaultRemoteIssueLinkManager.getRemoteIssueLinksForIssue(issue)

That is attempting to invoke a static method named getRemoteIssueLinksForIssue on the DefaultRemoteIssueLinkManager class.  There does not appear to be any such method, and the error you are seeing is consistent with that.
The method you linked at docs.atlassian.com/software/jira/docs/api/8.19.0/com/atlassian/jira/issue/link/DefaultRemoteIssueLinkManager.html#getRemoteIssueLinksForIssue-com.atlassian.jira.issue.Issue- is an instance method, not a static method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GParted after upgrade Ubuntu 14.04 LTS from 12.04 LTS (WinXP on same HDD) I have been rnning Ubuntu 12.04LTS and WinXP on one disk (grub booting), no probs.
Today I upgraded to Ubuntu 14.04 LTS and since the the gparted doesn't start (via "sudo gparted"):
the window opens but there is a bar going back and forth saying: "dev/sda/ are being searched" (translated from German /dev/sda/ wird durchsucht").
the following is displayed in the terminal:
computer@computer:~$ sudo gparted

no talloc stackframe at ../source3/param/loadparm.c:4864, leaking memory

libparted : 2.3
(gpartedbin:11255): GLib-CRITICAL **: Source ID 7 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 6 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 26 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 29 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 28 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 34 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 33 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 37 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 36 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 40 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 39 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 43 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 42 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 48 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 47 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 51 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 50 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 54 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 53 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 59 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 58 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 62 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 61 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 65 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 64 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 70 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 69 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 73 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 72 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 76 was not found when attempting to remove it
(gpartedbin:11255): GLib-CRITICAL **: Source ID 75 was not found when attempting to remove it
(gpartedbin:11255): glibmm-CRITICAL **:
unhandled exception (type Glib::Error) in signal handler:
domain: g_convert_error
code  : 1
what  : Ungültige Bytefolge in Konvertierungseingabe

I didn't find anything in google to help...
I am a beginner and running out of ideas how to solve that....
Thanks in advance!
Greets,
tobi


text:
Q: How does Mule API Console work? Does anyone know where the web content of the API Console is located - I would expect the css, html and js to be bundled in the app, where does the api console get these files from?

A: Answered Here: http://forum.mulesoft.org/mulesoft/topics/api-console-where-is-the-web-content?rfm=1
(It is within the APIKit libs)


text:
Q: Open Venmo from Another App iOS I know it's possible to open other apps from within an app using URL schemes, but to my knowledge those URLs need to be created by the developers. I'm trying to allow users of my app to open the Venmo app. Is this possible to do? I couldn't find any "public" URL schemes for Venmo. Ideally my app would be able to open Venmo directly to a specific users' profile. I'm using Swift.

A: Please note that the correct answer here is no longer correct
Venmo and Paypal had shut down their SDK  service for new merchants. All their SDK's becomes legacy and there is no news as of now for them to be back.
From their official site, they are suggesting you to use a their party SDK called Brain Tree. If you want to do transactions, that should be your only options for now.
You can reverse engineer their current legacy SDK to make your app switch to their apps, but that's it. Without app key or app secret, I don't believe you can open a payment page to a specific user and get a call back to indicate if the payment goes through or not

A: Venmo has an SDK, and it allows you to open the app and go straight to a transaction.
From the SDK source it's possible to reverse-engineer the URL scheme but I would recommend not doing that, and it might not even work. I would suggest just implementing the SDK and let it handle it, apparently it will even call back your app when finished.
Venmo does have a page that shows you how to create a "suggest payments" link with a scheme. https://developer.venmo.com/paymentlinks I assume that iOS would direct users to the app but you would have to check. Good luck.

A: Yes, you can open other apps. Its called mobile deep linking
Here you can find the good article for the same.
https://www.programmableweb.com/news/how-to-implement-deep-linking-ios/how-to/2015/07/14
For your question about venmo app, you will need to use their SDK to open venmo app and accept payment
Here is the link for venmo iOS SDK
https://github.com/venmo/venmo-ios-sdk


text:
Q: Getter for Windows handles So I've been learning C++ for several months now, and I ran into a weird occurrence with my IDE. (Jetbrains CLion FTW!)
My IDE can generate getters for members, automatically determining the type, const or not, and other keywords. Obviously the generation is not perfect, so I find myself usually not using this feature. So at the moment I'm focusing on the Windows API, which requires working with handles. So something really weird happens when I generate a getter to a handle (HINSTANCE, HWND, HDC, etc...).
Say I have a member defined as follows:
HDC m_hDeviceContext;

Then when my IDE generates a getter it looks something like this:
const HDC__* getDeviceContext() const...

I'm so confused to why the type is HDC__. It makes sense that it is a pointer, hence a handle is declared as a pointer (typedef struct name##__ *name) in winnt.h.
Could anyone give me some insight on why this is occurring? Is it a bug with my IDE, because whenever I see examples of getters that return a handle, they usually just return straight that handle type.

A: HDC is defined as a typedef for an opaque struct pointer:
typedef const struct HDC__ *HDC;

or in older windows version as a dummy type expanded from DECLARE_HANDLE(HDC):
typedef struct HDC__{int i;}*HDC;

The purpose if this definition is to prevent confusion between different types of handles that would all be just integers if typedefed as WORD or LONG, or DWORD.  Making them pointers to different structures prevents compilation in case of mismatches. Microsoft has been doing this for at least 20 years.
Your IDE probably looks at the debugging information instead of parsing the header files, and it does not reverse the effect of the typedef.
In C++, struct tags are implicitly typedefed in the current namespace.  So struct HDC__ also creates the type HDC__.  For some reason your IDE assumes that.  If you are compiling as C++, it should not be a problem.  If you were compiling as C, too bad, this bug would probably be the least of your problems.


text:
Q: Multiple login implementation I'm in the phase of designing a database which will have following entities among others:
-Organization,
-Organization_branch,
-Organization_staff
The concept is to allow ****MULTIPLE** organizations** to store their branch and staff details in SINGLE DATABASE.
However, I need some guideline as to how shall i implement the tables to allow each organization to login uniquely and perform various operations on their records only. As well as to allow each organization staff to login and perform various operations.
===================================
Organization table to store data of various organizations
Organization_Id,
Name,
Short_name,
Email,
Password,
===================================
Organization_branch table to store data of various branches of each organization
Branch_id,
Organization_Id,
Location,
Cellphone,
Email,
Password,
===================================
Organization_staff table to store data of various staff of each organization
Staff_id,
First_name,
Last_name,
Cellphone,
Designation,
Email,
Password,
Branch_id,
Organization_Id,


text:
Q: DDB query syntax in java using filter and group by if possible I am new in DDB and I have the data listed below in my DDB table.

Object
Item
Category
Name
RecommendedDate

book
item1
Category1
Name1
20220101

book
item2
Category1
Name2
20220101

book
item1
Category1
Name1
20220102

book
item2
Category1
Name2
20220102

book
item3
Category1
Name3
20220102

book
item3
Category2
Name1
20220102

What is the recommendation to create the GSI based on to fetch the following data:
GetItems(Object,Category) -->   GetItems(book,Category1)

Should only return rows that have the latest RecommendedDate filtered by Object and Category. What does the query look like?

Object
Item
Category
Name
RecommendedDate

book
item1
Category1
Name1
20220102

book
item2
Category1
Name2
20220102


text:
Q: Shift between MDI child forms I have a MDI form, and I want to be able to shift between the child forms.
Is there any method to do this?
I know there I can use CTRL+F6 to achieve this, and I could simulate those keys; but I would like an easy solution.

A: I completely forgot to add the answer, but here it is:
this.SelectNextControl(this.ActiveControl, true, true, true, true);

A: you can use:
this.MdiChildren[i].BringToFront()
where i is the index of the form you want to bring to front (they are sorted by first one to open is the first, second is the second etc)
btw,
ctrl+tab is easier then ctrl+F6...
(works in almost any windows tab based program (f.e. chrome), unlike ctrl+f6)


text:
Q: Reledpar paragraphed footnotes width within sized ledgroup Background of the question
The goal is to typeset Greek fragments and their translations side-by-side. The style guide prescribes that the Greek should be set with a hanging indent of 8mm. The notes (printed directly beneath the fragment) should be flush with the main body of the text.
Problem:
When using the ledgroupsized enviroment of reledmac and the paragraph footnotes setting (\Xarrangement[A]{paragraph}) the notes are flush with the left margin of the sized ledgroup. When on the normal arrangement setting, they follow the left margin of the document.
I want the alignment of the normal arrangement with the structure of the paragraph. Is there a way to achieve this?
Code exemplifying the problem:
\documentclass[11pt]{book}
\usepackage[%
  series={A, B, C, D},
  noend,
  noeledsec,
  ]{reledmac}
\usepackage[parledgroup]{reledpar}

\Xarrangement[A]{normal}

\Xarrangement[B]{paragraph}

\Xarrangement[C]{twocol}

\Xarrangement[D]{threecol}

\begin{document}
\numberlinefalse

\begin{pages}

\numberlinetrue
\lineation{pstart}

% Text to be typeset on the left page; editions
\begin{Leftside}
\beginnumbering

\pstart[%
 \section*{ Title for original text }
]

\begin{ledgroupsized}[r]{107mm}
Ipsa eveniet \edtext{}{\Afootnote{Footnote series A: normal form}}
laborum \edtext{}{\Bfootnote{Footnote series B: paragraph form}}doloremque alias necessitatibus consequatur aut et. Id nostrum in facilis iusto omnis nemo est. Ea voluptas sunt aut alias quo. Repellendus \edtext{}{\Dfootnote{Footnote series D: three columns}}harum sit pariatur velit assumenda dolores. Quisquam consectetur molestiae dolores et est et.

Qui eos sit dolore aliquam eveniet. Velit minu\edtext{}{\Cfootnote{Footnote series C: two columns}} s suscipit aut inventore voluptatibus doloremque dolores. Ea omnis porro consequatur reprehenderit et aliquid ut blanditiis.
\end{ledgroupsized}
\pend
\end{Leftside}

% Text to be typeset on the right page; translations
\begin{Rightside}
\beginnumbering

\pstart[%
\section*{English translation}
]

\begin{ledgroup}
Stet oportere no vel, nec in affert regione deseruisse. Case natum appareat ad eam. Vim an veniam essent discere, ex iuvaret euripidis mei. Pri elitr ignota audire te, mel et decore expetendis, ne vel prima saperet vulputate. Atqui vidisse conclusionemque pri no, pro ne sumo nihil verterem.

Te vix quem essent vidisse. Mucius apeirian lobortis quo no. Nam diam denique ex. Antiopam iracundia vituperatoribus ne vel, amet ridens expetendis at vel, at quot mazim errem vis. Omnium neglegentur disputationi duo id, usu posse tincidunt ne, eos quaeque explicari liberavisse ei.
\end{ledgroup}
\pend
\endnumbering
\end{Rightside}
\end{pages}

\pagebreak
\Pages[mainmatter]
\end{document}
% End of document

Output:


text:
Q: How a^n b^n where n>=1 is not regular?
This is the simple finite automata I tried, what am I doing it wrong?

A: This matches , not . Aka ababab, not aaabbb.

A: The b transition leads to a final state which halts the machine. Your machine will only halt if given a sequence of 'ab' of length 1 or more.

A: The language a^n b^n where n>=1 is not regular, and it can be proved using the pumping lemma.  Assume there is a finite state automaton that can accept the language. This finite automaton has a finite number of states k, and there is string x in the language such that n > k.  According to the pumping lemma, x can be decomposed such that x=uvw, and any finite automaton that accepts x must also accept uv*w.  v is non-empty and can be made to consist of only a's or only b's since n > k.  Let v consist of only a's. If the finite automaton accepts x = uvw, it must also accept x = uvvw, which has more a's than b's and is not of the form a^n b^n.  This is a contradiction, so a^n b^n cannot be a regular language.

A: This matches (ab)^n, not a^nb^n.
What you're looking for is Pumping lemma for regular languages.
Examples:
Let L = {a^mb^m | m ≥ 1}.
Then L is not regular.
Proof: Let n be as in Pumping Lemma.
Let w = a^nb^n.
Let w = xyz be as in Pumping Lemma.
Thus, xy^2z ∈ L, however, xy^2z contains more a's than b's.


text:
Q: Powershell : open ie without generating temporary files I wrote a scrip in Powershell to open ie and get webpage content automatically every minute to check if my API for website is working correctly:
$ie = New-Object -com internetexplorer.application
$ie.navigate($url)
...
$ie.Quit()

After a month my disk C is strangely filled up with IE temporary files, nearly 20GB. I think maybe it's related to my script. The version is Internet Explorer 10.
So how can I open ie without generating these files ? Thanks.

A: I believe it is better to say not how not to generate cache files at opening but how to clear them after this. As far as I see it now here you can try to clear those files by yourself as here. Or you can set up IE to clear them by itself as per here. Also here some help.


text:
Q: Laradock - Running Redis queues with Supervisor throwing the error - Call to undefined function Moontoast\Math\bcadd() I'm running a Laravel project on Laradock. I have a Job class that handles a Notification class that sends mail. The Job uses Redis for the queue driver and everything is well set up
I have Supervisor all set up and working. Below is my .conf file that is executed by Supervisor when the Job runs:
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/artisan queue:work redis --sleep=3 --tries=5 --daemon
autostart=true
autorestart=true
numprocs=8
user=root
redirect_stderr=true
stdout_logfile=/var/www/worker.log

This is set up in Laradock's php-worker>supervisord.d directory. I also have Laravel Horizon set up to monitor my Redis queues. When the Job is executed, Supervisor runs the Job and this is confirmed in my worker.log file that logs the processing of the Job, as defined in the above .conf file, as shown below:
[2019-10-14 12:18:27][21] Processing: App\Jobs\NewStaffAdded
[2019-10-14 12:18:30][21] Processing: App\Jobs\NewStaffAdded
[2019-10-14 12:18:31][21] Processing: App\Jobs\NewStaffAdded
[2019-10-14 12:18:33][21] Processing: App\Jobs\NewStaffAdded
[2019-10-14 12:18:35][21] Processing: App\Jobs\NewStaffAdded

When i visit my Horizon dashboard, i find that the Job failed. Clicking on the failed Job to learn more details, i get this exception:
Symfony\Component\Debug\Exception\FatalThrowableError: Call to undefined function Moontoast\Math\bcadd() in /var/www/vendor/moontoast/math/src/Moontoast/Math/BigNumber.php:506

Looking aroud for possible solutions for the above exception, i see suggestions that the cause is absence of the Bcmath module for PHP but I've run the following command and confirmed I have this module:
dpkg --list | grep -i bcmath

Shows I have the Bcmath module for my PHP version(7.3). So don't know why I'm getting the mentioned exception, which is preventing my queue from being executed.

A: The issue was down to not having the Bcmath module in Laradock's .env file under the PHP_WORKER section set to true. Firstly the module has to be installed in your workspace, then turn it on under BOTH the PHP_FPM AND PHP_WORKER sections. My mistake was that i had only set true under PHP_FPM section so had to do the same under PHP_WORKER section


text:
Q: .net TransactionScope Exception My Code something like this
try
{
    using (TransactionScope iScope = new TransactionScope())
    {
        try
        {
            isInsertSuccess = InsertProfile(account);
        }
        catch (Exception ex)
        {
            throw;
        }

        if (isInsertSuccess)
        {
            iScope.Complete();
            retValue = true;
        }
    }
}
catch (TransactionAbortedException tax)
{
    throw;
}
catch (Exception ex)
{
    throw;
}

Now what happen is that even if my value is TRUE a TransactionAbortedException Exception occurs randomly, but data get's inserted/updated in DB.
Any idea what went wrong?

A: As  the TransactionAbortedException documentation says,

This exception is also thrown when an attempt is made
  to commit the transaction and the
  transaction aborts.

This is why you see the exception even after calling Transaction.Complete: the Complete method is not the same thing as Commit:

calling this method [TransactionScope.Complete] does not guarantee
  a commit of the transaction. It is
  merely a way of informing the
  transaction manager of your status

The transaction isn't committed until you exit the using statement: see the CommittableTransaction.Commit documentation for details. At that point any actions participating in the transaction may vote to abort the transaction and you'll get a TransactionAbortedException.
To debug the underlying problem you need to analyze the exception details and stack trace. As Mark noted in a comment, it may well be caused by a deadlock or another interaction with other database processes.


text:
Q: VLOOKUP two different items, use whichever one has a number I have a list of financial metrics in column A, rest of the columns are the time periods the financial data is for.
Let's say I'm trying to calculate a ratio, but the financial metrics in A are not entirely unique, in the sense that a metric type may have more than one associated metric depending on how the company reports the metric.
For example, let's say I need Depreciation Expense on the income statement... that item may be reported as Depreciation, or DepreciationAndAmortization, or something else.
Any ideas how the formula in the ratio I'm trying to calculate can lookup the metric in A1, use the number immediately to the right as part of the formula... and if the metric Depreciation for example is 0, it would look for the next one I specify, like DepreciationAndAmortization, and use that one instead as the first one isn't reported.

A: If the alternatives are say in E2 and E3 then:
=MAX(VLOOKUP(E2,A:B,2,0),VLOOKUP(E3,A:B,2,0))

ie try both and take whichever is larger.

A: If I understand correctly, this should do it:
=MAX(INDEX(B:B,MATCH("*depreciation*",A:A,)),INDEX(B:B,MATCH("*depreciation*",A:A,)+MATCH("*depreciation*",INDEX(A:A,1+MATCH("*depreciation*",A:A,)):INDEX(A:A,100+MATCH("*depreciation*",A:A,)),)))

A: About your concern on the answer of Excel Hero that returns Value error, you can use the function "iferror" and returns "0" if the value/date you're looking for isn't available.
       =IFERROR(MAX(INDEX(B:B,MATCH("*depreciation*",$A:$A,)),INDEX(B:B,MATCH("*depreciation*",$A:$A,)+MATCH("*depreciation*",INDEX($A:$A,1+MATCH("*depreciation*",$A:$A,)):INDEX($A:$A,100+MATCH("*depreciation*",$A:$A,)),))),0)


text:
Q: How do i dynamically assign table IDs? I am writing a PHP script which is running a for loop. I am creating multiple tables inside the loop and i want to dynamically name the tables based on the loop.
I have already tried the following code but it doesn't work:
<table id="gameweek_history<? echo $i; ?>">

<table id ="gameweek_history<? echo $i; ?>">
<button onclick="doCSV(<? echo $i; ?>)">Export HTML Table To CSV File</button>


text:
Q: Passing real time data from model to controller (Swift) I'm using a server which sends data to the app in real time (for example: NewMessageRecieved, NewImageUploaded etc...).
I have a few UIViewControllers that present this data and all of them should update according to the server that was sent from the server.
I thought about creating a model class called RealTimeManager which will get the update from the server and will send it to all of the registered ViewControllers.
But what is the best way to register the ViewControllers? Using an array of delegates? Is it a good way to do it?
What do you think about my method generally? If you have a better idea instead feel free to share with me.
Thank you!


text:
Q: Allow the draggable content exceed but not within the parent boundary in Jquery? I am using Jquery ui and it provide a function for me to make draggable content. It has an option 'containment' that force the draggable item move within the box.
However, for my case, the content (image) must exceed the screen , how can I force it not to drag inside the screen?
Thanks
$("#popup").draggable({
    addClasses:true,
    scrollSpeed: "200",
    containment: "parent",
    //appendTo: "body",
    helper: function(){
        // Create an invisible div as the helper. It will move and
        // follow the cursor as usual.
        return $('

').css('opacity',0);
    },
    drag: function(event, ui){
        // During dragging, animate the original object to
        // follow the invisible helper with custom easing.
        var p = ui.helper.position();
        $(this).stop().animate({
            top: p.top,
            left: p.left
        },1000,'easeOutCirc');
    }
});


text:
Q: python Fruitful functions explanation I'm learning python I couldn't understand what exactly does this piece of code do, its giving an unexpected output. could anyone please explain this please.
#! /usr/bin/python

dx = int(raw_input("ENTER THE VALUE dx:"))
dy = int(raw_input("ENTER THE VALUE dy:"))

def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print "dx is", dx
    print "dy is", dy
    return 0.0

print distance

Thank you.

A: It doesn't do anything, because you never call the function. It'll just print the memory address of the function definition, which isn't very useful.
If you did print distance(), you would at least call it, and it would print dx and dy, but then also print 0.0 - because that's what you're returning from the function.

A: What do you expect it to do?
I assume to mean to call the function, e.g. print distance(x1, x2, y1, y2), but this will just result in 0.0 since that is the value you are returning.  You also seem to be asking the user for the answers (i.e. dx and dy), whereas you need x1, x2, y1, y2 for the function.  Without knowing exactly what you expect, here is some code which might do what you want:
def distance(x1, y1, x2, y2):
    dx = x2 - x1
    dy = y2 - y1
    print "dx is", dx
    print "dy is", dy

x1 = int(raw_input("ENTER THE VALUE x1:"))
x2 = int(raw_input("ENTER THE VALUE x2:"))
y1 = int(raw_input("ENTER THE VALUE y1:"))
y2 = int(raw_input("ENTER THE VALUE y2:"))

distance(x1, x2, y1, y2)

A: Well, the first 2 lines of code read two values, dx and dy. Next you define a function whose purpose is to calculate (and probably print AND return) the distance of two points, x1,y1 and x2,y2, but instead it returns 0.0 all the time
In the final statement, you are probably missing the parentheses, since what
print distance does is to print some info on the function object, something like <function distance at 0xZZZZZZZZZ>.
A fruitful function is one that returns a value, so probably, what you wanted to do is the following:
px1 = int(raw_input("X1:"))
py1 = int(raw_input("Y1:"))
px2 = int(raw_input("X2:"))
py2 = int(raw_input("Y2:"))

def distance(x1,y1,x2,y2):
    dx = x2 - x1
    dy = y2 - y1
    return dx, dy # return a tuple with the first element being dx and the second dy

print distance(px1,py1,px2,py2)

where I changed the names of input variables so that what the function does is more clear.
Short answer: "fruitful" functions return a value that you can use


text:
Q: Calendar entries categorized but not colored in Exchange environment In a small three-user environment running Outlook 2007 on Exchange 2010, all users previously just used one user's calendar as their main calendar.  New employee #4 has been set up with his own calendar per the owner's request, they use colored categories for their calendar events, and his categorized activities are not showing up as colored on the other users' Outlook calendars - only his own.  What settings should I look at to enable the correct color coding again?

A: I've found that if a user renames the default categories or in any way uses the default colors for their own custom categories it will not color in the items on the calendar. Everyone must use the default color scheme or all use the same custom categories. Maybe by pushing them out to all OL clients.

A: I just extensively tested this, and it should show the category colors, but I tested with Owner's permissions. I suggest that you test with Owner's permissions just to make sure you do not have any other issue. Once you change them, close and re-open Outlook, and close and re-open the shared calendar too, just in case. I am not 100% sure if you need to really close and re-open, but better to be sure.
I did back the permissions off, and with just Free/Busy, I did not see the colors.


text:
Q: Best way to Query for single Entity based on ONE property value? The ask: a function to retrieve a single Entity from the Google App Engine Datastore based on a property that is not its Key or otherwise return null if no such object is found.
Here is the function I have currently:
public Entity find(DatastoreService datastore, String kind, String property, String value) {
    Filter propertyFilter =
        new FilterPredicate(property, FilterOperator.EQUAL, value);

    Query q = new Query(kind).setFilter(propertyFilter);

    List<Entity> results =
        datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());

    if (results.isEmpty()) {
        return null;
    }

    return results.get(0);
}

Is there a one-shot API I could use instead or are there any optimization suggestions?

A: You could use PreparedQuery#asSingleEntity():
public Entity find(DatastoreService datastore,
        String kind, String property, String value)
        throws TooManyResultsException {
    Filter propertyFilter =
        new FilterPredicate(property, FilterOperator.EQUAL, value);

    Query q = new Query(kind).setFilter(propertyFilter);

    return datastore.prepare(q).asSingleEntity();
}

The only real difference between this and your code is that the underlying query sets a LIMIT of 2.


text:
Q: Wine Applications Uninstalled still appear Applications within Wine that I uninstalled still appear in the applications menu.

A: sudo apt-get install alacarte

Once installed, alt-F2 and type alacarte to launch, scroll down to "wine" on the left hand side, click on the program you want to remove and click "delete".
Log out and back in again, and those icons should have gone.
Hope that helps..


text:
Q: Entering printer username and password I am attempting to print to a Konica Minolta Bizhub C220. It requires me to authenticate to print. In other posts I see many people who receive some sort of pop-up asking them to authenticate but this does not happen for me. Instead, the data file is sent correctly, the printer processes it, and stops before printing because it requires authentication. In Windows, there is an option to enter a username and password; is there something similar the printer properties in Ubuntu that I'm missing?

A: Stop cups with sudo service cups stop and edit  /etc/cups/printers.conf with your preferred editor.At the top of the file there should be a
AuthInfoRequired username,password

Now I had some mixed results with this and with one printer I has to it out and with another I could put in a username, password. After editing start cups with sudo service cups start and retry printing it.
Also make sure the printer is using ipp.
By the way: from the "view print queue" you can also enter username and password to unlock a job by right clicking a job and pick "authentication"

A: After another couple of weeks fiddling with things I never did manage to get past the "Login Error" problem. I've given up and simply disabled user authentication on our printer... we're a small organization so it makes little difference anyways.

A: In /etc/cups/cupsd.conf comment out for whichever sections you want to disable authentication
AuthType Default
Require user @SYSTEM

Then sudo service cups restart


text:
Q: CherryPy authentication timeout I added digest authentication to my CherryPy server, and I wanted to know on what criteria the users' authentication is revoked and they are prompted to enter credentials again. Deleting cookies doesn't force a prompt, but using Incognito or another browser does.
My config:
{ 'tools.auth_digest.on': True,
  'tools.auth_digest.realm': 'localhost',
  'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
  'tools.auth_digest.key': key,
  'tools.auth_digest.accept_charset': 'UTF-8' }

Thanks

A: You need to have the proper HTTP response so that the browser clear out the user credentials, basically responding with  401 Unauthorized and a challenge in how to authenticate with the WWW-Authenticate header.
Here is an implementation using a custom CherryPy tool and a Cookie that is used as way to communicate the intention to the browser and the backend (HTTP auth is stateless and we have to go back and forth to deauth and redirect).
import cherrypy
from cherrypy.lib import auth_digest

REALM = 'localhost'
KEY = '24684651368351320asd1wdasd'
CHARSET = 'UTF-8'

@cherrypy.tools.register('before_handler')
def with_logout_handler():
    if cherrypy.request.cookie.get('Unauthorize') is not None:
        response = cherrypy.response
        response.headers['WWW-Authenticate'] = auth_digest.www_authenticate(
            realm=REALM,
            key=KEY,
            accept_charset=CHARSET
        )
        # delete the cookie that was used to mark the intention to logout
        response.cookie['Unauthorize'] = 1
        response.cookie['Unauthorize']['expires'] = 0
        raise cherrypy.HTTPError(
            401, 'You are not authorized to access that resource')

class App:
    @cherrypy.expose
    @cherrypy.tools.with_logout_handler()
    def index(self):
        return ('Welcome {}! Do you want to logout?'
                .format(cherrypy.request.login))

    @cherrypy.expose
    def logout(self):
        """
        Set a cookie to give it a clue to the index method to
        remove the user credentials from the following requests.

        This will be handled by the tool `with_logout_handler`.
        """
        cherrypy.response.cookie['Unauthorize'] = 1
        raise cherrypy.HTTPRedirect("/")

def main():
    users = {
        'foo': 'bar'
    }
    cherrypy.quickstart(App(), config={
        '/': {
            'tools.auth_digest.on': True,
            'tools.auth_digest.realm': REALM,
            'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
            'tools.auth_digest.key': KEY,
            'tools.auth_digest.accept_charset': CHARSET
        },
    })

if __name__ == '__main__':
    main()


text:
Q: delayed_job: how to check for presence of a particular job based on a triggered method I have a method like this that goes through an array to find different APIs and launch a delayed_job instance for every API found like this.
def refresh_users_list
  apis_array.each do |api|
    api.myclass.new.delay.get_and_create_or_update_users
  end
end

I have an after_filter on users#index controller to trigger this method. This is creating many jobs to be triggered that will eventually cause too many connections problems on Heroku.
I'm wondering if there's a way I can check for the presence of a Job in the database by each of the API that the array iterates. This would be very helpful so I can only trigger a particular refresh if that api wasn't updated on a given time.
Any idea how to do this?

A: *

*In config/application.rb, add the following
config.autoload_paths += Dir["#{config.root}/app/jobs/**/"]

*Create a new directory at app/jobs/.

*Create a file at app/jobs/api_job.rb that looks like
class ApiJob < Struct.new(:attr1, :attr2, :attr3)

  attr_accessor :token

  def initialize(*attrs)

    self.token = self.class.token(attr1, attr2, attr3)
  end

  def display_name
    self.class.token(attr1, attr2, attr3)
  end

  #
  # Class methods
  #
  def self.token(attr1, attr2, attr3)
    [name.parameterize, attr1.id, attr2.id, attr3.id].join("/")
  end

  def self.find_by_token(token)
    Delayed::Job.where("handler like ?", "%token: #{token}%")
  end
end

Note: You will replace attr1, attr2, and attr3 with whatever number of attributes you need (if any) to pass to the ApiJob to perform the queued task. More on how to call this in a moment

*For each of your API's that you queue some get_and_create_or_update_users method for you'll create another Job. For example, if I have some Facebook api model, I might have a class at app/jobs/facebook_api_job.rb that looks like
class FacebookApiJob < ApiJob
  def perform
    FacebookApi.new.get_and_create_or_update_users(attr1, attr2, attr3)
  end
end

Note: In your Question you did not pass any attributes to get_and_create_or_update_users. I am just showing you where you would do this if you need the job to have attributes passed to it.
Finally, wherever your refresh_users_list is defined, define something like this job_exists? method
def job_exists?(tokens)
  tokens = [tokens] if !tokens.is_a?(Array) # allows a String or Array of tokens to be passed

  tokens.each do |token|
    return true unless ApiJob.find_by_token(token).empty?
  end

  false
end

Now, within your refresh_users_list and loop, you can build new tokens and call job_exists? to check if you have queued jobs for the API. For example
# Build a token

def refresh_users_list
  apis_array.each do |api|
    token = ApiJob.token(attr1, attr2, attr3)
    next if job_exists?(token)

    api.myclass.new.delay.get_and_create_or_update_users
  end
end

Note: Again I want to point out, you won't be able to just drop in the code above and have it work. You must tailor it to your application and the job's you're running.

Why is this so complicated?
From my research, there's no way to "tag" or uniquely identify a queued job through what delayed_job provides. Sure, each job has a unique :id attribute. You could store the ID values for each created job in some hash somewhere
{
  "FacebookApi": [1, 4, 12],
  "TwitterApi": [3, 193, 44],
  # ...
}

and then check corresponding hash key for an ID, but I find this limiting, and not always sufficient for the problem When you need to identify a specific job by multiple attributes like above, we must create a way to find these jobs (without loading every job into memory and looping over them to see if one matches our criteria).
How is this working?
The Struct that the ApiJob extends has a :token attribute. This token is based on the attributes passed (attr1, attr2, attr3) and is built when a new class extending ApiJob is instantiated.
The find_by_token class method simply searches the string representation of the job in the delayed_job queue for a match based on a token built using the same token class method.


text:
Q: How to validate .csv file in rails 4 I am using rails 4. I am having employee attendance model. In that I have to upload .csv file alone. It won't allow any other format. So, How to validate file format. whether imported file was other than csv.
Model
class EmpAttendance < ActiveRecord::Base
    attr_accessible :emp_id,:in_time,:out_time,:date,:status

    def self.import(file)
            CSV.foreach(file.path, headers: true) do |row|
            @emp_attendance  = EmpAttendance.find_by_emp_id_and_date(row['emp_id'],row['date']) || EmpAttendance.new
            @emp_attendance.emp_id                = row['emp_id']
            @emp_attendance.in_time               = row['in_time']
            @emp_attendance.out_time              = row['out_time']
            @emp_attendance.status                = row['status']
            @emp_attendance.date                  = row['date']
            @emp_attendance.save!
        end
    end
end

Controller
def import
    if params[:file].present?
     EmpAttendance.import(params[:file])
     flash[:notice] = "Sucessfully Created."
     redirect_to emp_attendances_path
    else
     flash[:error] = "No File Chosen"
     redirect_to emp_attendances_path
    end
 end

View (Index.html.erb)

Add Driver Details

     <% if flash[:notice].present? %>

        <button type="button" class="close" data-dismiss="alert">×</button>
        <%= flash[:notice] %>

<% end %>
<% if flash[:error].present? %>

        <button type="button" class="close" data-dismiss="alert">×</button>
        <%= flash[:error] %>

<% end %>

Employee Attendance

<%= form_tag import_emp_attendances_path, multipart: true do %>
<%= file_field_tag :file %>
  <%= submit_tag "Import", :class => 'btn btn-primary' %>
<% end %>

Please Help me..

A: The API Docs mentions the accept option:
file_field_tag :file, accept: 'text/csv'

:accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.

A: When I do csv imports, I do two things:

*

*put the data-rows into intermediate hash-objects. Then I check basic things like that nr of columns is big enough. Also this decouples the csv-format from the format in the database.

*insert all data in one transaction. When an object does not validate, nothing is imported, and there is a clear state. The user is not left with half imported data. writing many objects in one transactions also tend to be faster.


text:
Q: How to speed up string construction from characters in a doubly-nested list? A common speedup for string concatenations is changing something like
s = ""
for x in list:
    s += some_function(x)

to
slist = [some_function(elt) for elt in somelist]
s = "".join(slist)

However, how could this apply if your 'for' was doubly nested? For example...
s = ""
for x in list:
    for y in x:
        s += some_function(y)

A: ''.join(func(c) for s in somelist for c in s)

A: string_list = []
for x in list:
    for y in x:
        string_list.append(some_function(y))

the_string = ''.join(string_list)


text:
Q: How to get user local time at Page_Load I have a web page written in ASP.NET and I need to retrieve the end user's local time at Page_Load. I thought about using Javascript to get the local time (by using new Date()) but the problem is that the script is run after the server events.
Any ideas on how to accomplish this?
EDIT: My page is quite complex: it displays a chart with lots of calculated fields from a database, object/fields selection lists, etc; The customer now requested that it should  consider the user's timezone and that the timezone should be determined automatically by the web page. The user date is important to determine the chart interval (which day to display data on).
Data loading (since it is so complicated) is done in both Page_Load and Page_PreRender. Giving up these events would require a full page rewrite.
FINAL SOLUTION INSPIRED BY ANSWER:
Here is how I solved the problem eventually. I am keeping the local date in a cookie. Here is the method that sets the cookie:
function SetLocalDateCookie() {
    var cookieName = 'LOCALDATE';
    var localDate = new Date();
    var realMonth = localDate.getMonth() + 1;
    var localDateString = localDate.getFullYear() + "/" + realMonth + "/" + localDate.getDate();
    setCookie(cookieName, localDateString, 2);
    try {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + 2);
        document.cookie = cookieName + "=" + escape(localDateString) + ";expires=" + exdate.toGMTString();
    }
    catch (e)
    { }
}

In my Master page I call this method on $(document).ready.
On the page where I use this cookie I added the following code to Page_Init:
if (string.IsNullOrEmpty(CookieHandler.Instance.GetCookie(CookieKeys.LocalDate)))
{
    Response.ClearContent();
    Response.Write(@"<form id='local' method='post' name='local'>
                        <script type='text/javascript'>
                            SetLocalDateCookie();
                            document.getElementById('local').submit();
                        </script>
                    </form>");
    Response.Flush();
    Response.End();
}

Then I can just use the cookie value in the C# code.
Thank you for your answers/comments!

A: I'll explain a bit the following code and what lefts for you to do.
At the first request off this page, the code checks if the LocalTime is not already stored in Session and if not it will write a form element, a hidden input and a javascript which will post that form with the local time. The response ends, so your report won't get the chance to be generated.
This submit will immediately create a POST request with the localTime set, then ASP .Net stores this POST value into the Session.
I also added a 302 redirect (Response.Redirect) to the original page, because of the usability. The User made initially a GET request, not a POST, so if he/she wants to refresh the page, the browser will reiterate the last action, which was that form.submit() and not the GET request.
You have now the local time. But you don't have to read it at every request since it can be compared to the UTC time, then with the server's time.
edit: You need to parse the UTC time into a DateTime, but probably it's easy to find the format, though might depend on the user's culture (not sure about this statement).
public ReportPage()
{
    this.Init += (o, e) =>
    {
        // if the local time is not saved yet in Session and the request has not posted the localTime
        if (Session["localTime"] == null && String.IsNullOrEmpty(Request.Params["localTime"]))
        {
            // then clear the content and write some html, a javascript code which submits the local time
            Response.ClearContent();
            Response.Write(@"<form id='local' method='post' name='local'>
                                <input type='hidden' id='localTime' name='localTime' />
                                <script type='text/javascript'>
                                    document.getElementById('localTime').value = new Date();
                                    document.getElementById('local').submit();
                                </script>
                            </form>");
            //
            Response.Flush();

            // end the response so PageLoad, PagePreRender etc won't be executed
            Response.End();
        }
        else
        {
            // if the request contains the localtime, then save it in Session
            if (Request.Params["localTime"] != null)
            {
                Session["localTime"] = Request.Params["localTime"];
                // and redirect back to the original url
                Response.Redirect(Request.RawUrl);
            }
        }
    };
}

A: I don't think this would be possible, you can't get the time off the client's local machine at server side.
The only way to achieve this would be using some javascript (as this is client based, so it will use the client's current date/time). But as you've stated, this will be after your server events have been ran, and your web page has been rendered into HTML and sent to the client.
One alternative would be to capture the clients time before the Post Back, but it wouldn't be possible to do this with an inital Page_Load.

A: How about you place a hidden textbox on the page, attach an OnChange-eventhandler to it in C# and use an OnLoad JavaScript function to set the value to the value you need from the client?

A: As far as I'm aware, there isn't any way to get the users local time in the Page_Load event as that is executed on the server-side, and would therefore only be aware of the server's local date time.
To get the user's local time you would need to either execute an asynchronous call to the server upon the page loading in JavaScript, or store the local time in a hidden field and then read it on post-back.

A: Or just use an interstitial page that contains nothing but the js to get local time and redirects to your current page passing the time information via query string or session variable or post


text:
Q: select distinct groups in django I'm using Django. All my data have a column called 'group' that they belong to. I want to select all the distinct group names from the database. For example, 'groupA', 'groupB', and also get the number of objects that have this group.  For example 'groupA':3.
How can I do this in Django?
I tried the following to get distinct groups.
groups = Animal.objects.values('group').distinct()

return render(request, 'group.html', {'groups', groups})

but I simply  got the error message other_dict must be a mapping (dictionary-like) object.

A: This {'groups', groups} should become {'groups': groups}
To get the list of groups:
{% for g in groups %}
   {{g.group}}
{% endfor %}


text:
Q: Kernel won't connect in Anaconda on my Mac Kernel doesn't work and in my terminal I get a syntax error.
I'm using a Mac, I've used Anaconda before. Never had any problems.
File "/Users/aydanaslanova/random.py", line 3
    random_number = random.randint(1,10).
                                         ^
SyntaxError: invalid syntax
This is the error I am getting. No clue what I'm doing wrong. Did bunch of research still can't fix it.
Kernel should connect. Please help, I would greatly appreciate it.

A: renaming /Users/aydanaslanova/random.py worked


text:
Q: cannot echoing result from table I can echo $row_count but I am unable to print $first.
Account table contain fname and lname.
Can anyone fix this problem?
public function getAccountInfoAll(){
        $acc_info = $this->con->query("SELECT * FROM account");
        $results = $acc_info->fetchAll();
        $row_count = $acc_info->rowCount();
        echo $row_count.' rows selected';
        while ($row = $acc_info->fetchAll())
          {
          $first = $row['fname'];
          echo $first;
          }
        }

A: I'm guessing your using PDO, so here's what you did wrong :
$acc_info = $this->con->query("SELECT * FROM account");
$acc_info->execute();
$results = $acc_info->fetchAll(PDO::FETCH_ASSOC);
$row_count = $acc_info->rowCount();
echo $row_count.' rows selected';
foreach($results AS $row) {
   $first = $row['fname'];
   echo $first.'<br />';
}

A: Something like this:
public function getAccountInfoAll(){
    $acc_info = $this->con->prepare("SELECT * FROM account");
    $acc_info->execute();

    $row_count = $acc_info->rowCount();
    echo $row_count.' rows selected';

    while ($row = $acc_info->fetch(PDO::FETCH_ASSOC)) {
      $first = $row['fname'];
      echo $first;
    }
}

More information on prepared statements.


text:
Q: Neo4j Cypher Regular expression not matching I am trying to perform matching this property in my edge

TargetObject: hklm\\software\\microsoft\\windows\\currentversion\\run\\xyz

why will this regular expression fail
MATCH (n)-[r]->(m) where r.TargetObject=~'hklm\\\\software\\\\microsoft\\\\windows\\\\currentversion\\\\run.*' return n, r, m

Only the following can work
MATCH (n)-[r]->(m) where r.TargetObject=~'hklm\\\\.*' return n, r, m

A: Lets see if I can bring some clarity to this.
The regex hklm\\\\s.* is in a string object, which will escape the \ when created and thus be saved as hklm\\s.*. Then once the regex is evaluated it is handled as a new string/regex object that also escapes the \. This means that the regex you search on is hklm\s.*, which doesn't match the target string (which has double \'s).
The regex hklm\\\\.* will then be hklm\.* which matches the target (since . matches any character), in difference to hklm\s.*.
To get the correct regex in the end you'll need more \'s (double the amount) in the original query regex. The regex hklm\\\\\\\\s.* will become hklm\\s.* when evaluated, which should match your target.
I tried this with a small example using Neo4j browser and adding the extra \'s does work then.
Hope this helps,
Therese
Neo4j employee

A: the only workaround is to use this expression r.TargetObject=~'hklm\\\\.*s.*'


text:
Q: Problems with html tags putted out via php my problem is basically this block of code:
  echo
  "
".
    ...
  "
";

Neither this way (above) nor that way (below) works:
  echo
  "
".
   ...
  "
";

I guess due to the fact that I'm putting this HTML-Tag out with PHP I "ran out" of different types of quotes because when I put the same code out just without PHP I'm led to the page like I want and everything works perfectly fine. Is another kind of quotes or is there another solution. I'm sorry for any mistakes in this post aswell as I'm new to this I'm not a nativ speaker in English.
Thank you for helping me!


text:
Q: Document version column in spreadsheet view I try to open MOSS document library in spreadsheet view and when I add version of document, I see it in regular view and don't see in spreadsheet view.
When I try to export to Excel I get the same problem.

A: May be that the library supports versioning - in that case the document might not be displayed as it is still draft. What happens if you remove versioning?


text:
Q: ui-router with codeigniter gives 404 when refreshing the page or pasting the URL with html5mode(true) I'm using codeiginiter with angular-js and ui-router just like in this seed project , and i wanted to remove the /#/ from the url, so i used:
$urlRouterProvider.otherwise('/');
 $locationProvider.html5Mode(true);

in my app.js .config and I also added <base href="/"> on index.php.
Now I don't have the /#/ on the URL but when I refresh the page I get a 404, also, if I copy a working URL(which I get to it from the main view) and paste it in the URL line I also get a 404 message.
I've seen this question but i don't want to override my 404, i don't think that's wise.
and ideas?

A: Thanks to xkcd149's link to this answer I figured out that changing the routing in the codeiginiter 3 so that you would always go through your CI root controller should look like this:
on /application/config/routes.php:
$route['default_controller'] = 'home'; //can have any name you want
$route['exampleUrl'] = 'home';
$route['anotherUrl/(:any)'] = 'home'; //this url passes a parameter
$route['anotherUrl/(:any)/(:any)'] = 'home'; //this one passes 2 parameters

Hope this helps someone.


text:
Q: ASP MVC HTML Helpers - Good or Bad? I understand the reason for having the HTML helpers in ASP.NET MVC and extending this to provide your own, but I am wondering whether using HTML helpers is a good idea.
I thought one of the benefits of ASP.NET MVC is control over the HTML. If you start hiding it away in helper functions that generate HTML don't you start losing visibility? I guess this isn't such a problem when you are generating simple controls such as a button, but I have seen the use of html helpers to create grids and more complex HTML output.
Now I also understand the reason for doing so is to keep things DRY, avoiding duplication. But is there not a danger of having something akin to code-behind here? In addition, what if you are working in collaboration with designers? Generally the designer would be creating the markup and applying styling. If you start injecting your view with helpers that generate markup, doesn't this make such collaboration difficult?

A: Great comment, Matt.  There's still the question of whether in a "pure" MVC implementation, HTML helpers are a good idea.  I think that's the magic word, "pure".  Whenever I slow down to think about the "proper" way of doing things, I'm really trying to see if a particular approach fits in with the purist's vision.  So, would a purist use HTML helpers?
I'm about 8/10 purist and I wouldn't use them.  I've seen this argument transcend technologies and raised the issue with MVC in PHP and the Zend framework.  It just doesn't feel right and to me, that's the best measure one can come up with.

A: There's definitely nothing wrong with helpers. They're used to keep your views clean and declarative. There's a saying that goes something like "if there's an "if" statement in your view, you're doing it wrong". They're used in many prominent MVC frameworks like Ruby On Rails and Cake PHP. Check out this post. "Purist" or not, helpers are a good thing and not to be confused with bad practice or leaky abstractions.

A: "Control over the HTML" is microsoft marketing-speak, and is how they are choosing to brand the platform. The point of ASP.net MVC is that it is a more simple, and a better fit for webapps then the whole stateful event-driven model of webforms, and something that pretty much everyone outside of the microsoft space moved to years ago. Microsoft can't say that though, because they have a huge investment in webforms, and it is a key part of their enterprise story.
That being said, if you have business logic in your helpers you are using them wrong. It is basically code behind for presentation logic only that is duplicated across multiple pages, and the goal is to keep scriptlet tags in the markup as simple as possible.
As long as you use the helpers the way they should be used, it should be fairly trivial for the designers to learn how to use. Just remember that the goal is to keep things simple, if they end up making things more complex, it means they are not being used correctly.

A: I think one important point that the others haven't mentioned is portability of your views.
You can move your HTML, javascript and CSS to an application on another platform immediately. You don't have to convert all the ugly HTMLHiders.. sorry, HTMLHelpers.. to actual HTML.
While I have the highest regard for the .NET framework that reduces my development time and makes my job easy, I strongly feel that views should be non-proprietary.
You can gain almost all of the benefit from the framework in the model and controller anyway. Injecting dependencies on the framework in your presentation layer is not at all worth the tradeoff, IMO.


text:
Q: Testing the existence of specific fields from a list I'm trying to validate whether a list has an specific list of fields, it keeps returning all the existing fields from the list, how do I make this things work? Is there a better way to achieve what I'm trying?
sp.web.lists.getByTitle("SliceBox").fields.select("Title","Body","Link","Picture","Visible").get()
    .then( (fields: any[]) => {
        console.log("> number of fields returned:", fields.length);

        fields.forEach(f => {
            console.log("> field:", f);
        })
    })
    .catch( err => {
        console.log("> fields failure: ", err);
});

A: We will have to use 'filter' in above scenario
 sp.web.lists.getByTitle("SliceBox").fields.filter("((Title eq 'Title') or (Title eq 'Body'))").get()

We can include more 'or' for more filters.
When we use 'select', it only return those selected properties within that field. Means, if we use select('Title') it will only return 'Title' property of all fields.


text:
Q: Multiple Jenkins Nodes in Pipeline Currently we have a jenkins pipeline with 4 stages. Setup, Build, Deploy, Teardown. Deploy and Teardown prompt for manual user input. Because of this, we don`t want manual user input to take up an executor. So, we want to use agent none. However, when resuming, there is no guarentee we get the same jenkins workspace. Stash/unstash says it uses alot of resources, so if you have large files not to use it. Is there a way to get the exact slave, and when resuming, run back on that same slave?
I have something like this now I also tried agent gcp at top level, and putting agent none in manual input
pipeline {
agent none

 environment {
    userInput = false
 }

stages {
    stage('Setup') {
        agent { node { label 'gcp' } }
        steps {
            deleteDir()
            dir('pipelines') {
                checkout scm
            }
            dir('deployment_pipelines'){
                git branch: __deployment_scripts_code_branch, credentialsId: 'jenkins', url: __deployment_scripts_code_repo
            }
            dir('gcp_template_core'){
                git branch: __gcp_template_code_branch, credentialsId: 'jenkins', url: __gcp_template_code_repo
            }
            dir('control_repo'){
                 git branch: _control_repo_branch, credentialsId: 'jenkins', url: _control_repo
            }

            // Copy core templates to the project
            sh('bash deployment_pipelines/deployment/setup.sh gcp_template_core/gcp_foundation/ control_repo')
        }
    }

    stage('Build') {
        agent { node { label 'gcp' } }
        steps {
            sh('printenv') //TODO: Remove. Debug only
            sh('python deployment_pipelines/deployment/build.py control_repo --env ${_env_type_long}')
        }
    }

    stage('Deploy') {
        agent { node { label 'gcp' } }
        steps {
            sh('python deployment_pipelines/deployment/deploy.py control_repo --env ${_env_type_short}')
        }
    }

     stage('Release') {
        steps {
            agent none
            script {
                sh('python deployment_pipelines/deployment/set_manual_approvers.py deployment_pipelines/config/production-release-approvers.yaml -o approver.txt')
                def approvers = readFile('approver.txt')

                try {
                    userInput = input(
                        message: 'Do you want to proceed with Release?',
                        submitter: approvers)
                } catch(err) { // input false
                    //def user = err.getCauses()[0].getUser() //need script approval for getUser()
                    userInput = false
                    // echo "Aborted by [${user}]"
                }
                agent { node { label 'gcp' } }
                if(userInput)
                {
                    sh("echo 'Do Release'")
                }
            }
        }
    }
    stage('Teardown'){
        agent { node { label 'gcp' } }
        steps {
             script {
                def approvers = readFile('approver.txt')

                try {
                    userInput = input(
                        message: 'Do you want to proceed with Teardown?',
                        submitter: approvers)
                } catch(err) { // input false
                    //def user = err.getCauses()[0].getUser() //need script approval for getUser()
                    userInput = false
                    // echo "Aborted by [${user}]"
                }
                if(userInput)
                {
                    sh("echo 'Do Teardown'")
                }
            }
        }
    }
}

post {
    always {
        echo 'DO TEARDOWN REGARDLESS'
    }
}
}

A: agent none should be above step block in stage('Release'). You can refer https://jenkins.io/doc/book/pipeline/syntax/#agent for syntax and flow


text:
Q: about JPA's transaction for create table and drop table with native query anyone can help me. this is a problem i've spent much
time on it. I'm using JTA'S BMT transaction, and I'm going to execute
3 steps in same transaction:

*

*Insert one row to a table with entitymanager;

*Drop a table if it exists with native query;

*Create a table with native query; I wrote a wrong sql for native query in purpose, and rollbacked.

These 3 steps in same one transaction, but step 1 is always successful. I'm wondering if native query("drop table and create table") is not supported by JPA's transaction. Thank you guys in advance!! code like this:
try {
    tx.begin();
    table1 t1 = new table1();
    t1.setC1(c1);
    t1.setC2(c2);
    EntityManager em = emf.createEntityManager();
    em.persist(t1);
    Query query1= em.createNativeQuery("drop table if exists table2").executeUpdate();
    Query query2= em.createNativeQuery("xxxxxxxxxxxxxxxx").executeUpdate();
    tx.commit();
    rt = true;
} catch (Exception e) {
    try {
        tx.rollback();
    } catch (Exception e1) {
        PUB.log(e, PUB.getLineInfo());
    }
}

this is the declarations:
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MainSessionBean implements MainSessionBeanRemote {
    @PersistenceUnit(unitName = "CC2016JPA2")
    static EntityManagerFactory emf;
    @Resource
    UserTransaction tx;


text:
Q: Cannot start a tcp based WCF service I am developing a tcp base WCF service and I am getting this notorious WCF Exception while trying to launch the service in the host application:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.ServiceModel.dll
Additional information: Service 'WcfServiceWas.MathService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

This problem was described many times before and the proposed solution is to name a service exactly as it is defined in the class library, the problem is this solution does not work for me.
What is wrong with the this configuration that the hosting service refuses to start the Service?
Service Interface (IMathService.cs):
namespace WcfServiceWas
{
   [ServiceContract]
   public interface IMathService
   {
      [OperationContract]
      OperationResult Add(int x, int y);

      [OperationContract]
      int Subtract(int x, int y);
    }
}

Service implementation (MathService.cs):
namespace WcfServiceWas
{
    public class MathService : IMathService
    {
        public OperationResult Add(int x, int y)
        {
            return new OperationResult { Result = new MyInteger { Value = x + y } };
        }

        public int Subtract(int x, int y)
        {
            return x - y;
        }
    }
}

Svc file (MathService.svc):
<%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceWas.MathService" CodeBehind="MathService.cs" %>

Web.Config:
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
  </system.web>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServiceWas.MathServiceBehavior" >
            <serviceMetadata httpGetEnabled="false" />
            <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
      <services>
        <service name="WcfServiceWas.MathService" behaviorConfiguration="WcfServiceWas.MathServiceBehavior" >
            <endpoint contract="WcfServiceWas.IMathService" binding="netTcpBinding" address="" />
            <endpoint contract="IMetadataExchange" binding="mexTcpBinding" address="mex" />
            <host>
                <baseAddresses>
                    <add baseAddress="net.tcp://localhost:999/MathServiceX/"/>
                </baseAddresses>
            </host>
        </service>
      </services>
  </system.serviceModel>
</configuration>

Service host:
class Program
{
    static void Main(string[] args)
    {
        using (var myServiceHost = new ServiceHost(typeof(MathService)))
        {
            myServiceHost.Open();
        }
    }
}

Update: app.config of the hosting application has to contain wcf configuration as well.

A: You need to define your bindings section, under <system.serviceModel> add the below <bindings>  configurations :
<bindings>
  <netTcpBinding>
    <binding name="netTcpBindingConfiguration" sendTimeout="00:01:00">
      <security mode="None" />
    </binding>
  </netTcpBinding>
</bindings>

and edit the line <endpoint contract="WcfServiceWas.IMathService" to add the bindingconfiguration in it, as follows:
<endpoint contract="WcfServiceWas.IMathService"
          binding="netTcpBinding"
          bindingConfiguration="netTcpBindingConfiguration"
          address="" />

Save these config changes and restart the service, it should work fine now.
Update:
so it appeared out that for self-hosting applications, configurations of WCF must be within the app.config of the host itself, and the  section is not a must to appear within the System.ServiceModel, since it will take default bindings , the msdn documentation illustrates this more
http://msdn.microsoft.com/en-us/library/ee530014%28v=vs.110%29.aspx


text:
Q: Dagger2 Maven: Missing POM for com.google.devtools.ksp:symbol-processing-api:jar:1 I am new to Dagger. Here's my pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>trace-ingester</artifactId>
    <groupId>com.pandepra</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>trace-ingester-deploy</artifactId>

  <properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming-kafka-0-10_${scala.version.major}</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-sql_${scala.version.major}</artifactId>
    </dependency>

    <dependency>
      <groupId>com.typesafe</groupId>
      <artifactId>config</artifactId>
    </dependency>

    <dependency>
      <groupId>com.pandepra</groupId>
      <artifactId>trace-ingester-module</artifactId>
      <version>1.0-SNAPSHOT</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming_${scala.version.major}</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka-clients</artifactId>

    </dependency>

    <dependency>
      <groupId>com.google.dagger</groupId>
      <artifactId>dagger</artifactId>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <annotationProcessorPaths>
            <path>
              <groupId>com.google.dagger</groupId>
              <artifactId>dagger-compiler</artifactId>
              <version>2.38.1</version>
            </path>
          </annotationProcessorPaths>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
          <execution>
            <id>create-fat-jar</id>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <artifactSet>
                <excludes>META-INF/*.SF</excludes>
                <excludes>META-INF/*.DSA</excludes>
                <excludes>META-INF/*.RSA</excludes>
                <includes>
                  <include>org.apache.spark:spark-streaming-kafka-0-10_${scala.version.major}</include>
                  <include>org.apache.spark:spark-sql_${scala.version.major}</include>
                  <include>org.apache.spark:spark-streaming_${scala.version.major}</include>
                  <include>com.typesafe:config</include>
                </includes>
              </artifactSet>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.pandepra.traceingester.TraceIngesterApplication</mainClass>
                </transformer>
              </transformers>
              <finalName>trace-ingester-uber-jar</finalName>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

The application runs fine from Intellij. However, while doing maven clean install, I get the following error:
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:compile (default-compile) on project trace-ingester-module: Resolution of annotationProcessorPath dependencies failed: Missing:
[ERROR] ----------
[ERROR] 1) com.google.devtools.ksp:symbol-processing-api:jar:1.5.20-1.0.0-beta03
[ERROR]
[ERROR]   Try downloading the file manually from the project website.
[ERROR]
[ERROR]   Then, install it using the command:
[ERROR]       mvn install:install-file -DgroupId=com.google.devtools.ksp -DartifactId=symbol-processing-api -Dversion=1.5.20-1.0.0-beta03 -Dpackaging=jar -Dfile=/path/to/file
[ERROR]
[ERROR]   Alternatively, if you host your own repository you can deploy the file there:
[ERROR]       mvn deploy:deploy-file -DgroupId=com.google.devtools.ksp -DartifactId=symbol-processing-api -Dversion=1.5.20-1.0.0-beta03 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
[ERROR]
[ERROR]   Path to dependency:
[ERROR]         1) com.google.dagger:dagger-compiler:jar:2.38.1
[ERROR]         2) com.google.dagger:dagger-spi:jar:2.38.1
[ERROR]         3) com.google.devtools.ksp:symbol-processing-api:jar:1.5.20-1.0.0-beta03
[ERROR]
[ERROR] ----------
[ERROR] 1 required artifact is missing.
[ERROR]
[ERROR] for artifact:
[ERROR]   com.google.dagger:dagger-compiler:jar:2.38.1
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR]   central (https://repo.maven.apache.org/maven2, releases=true, snapshots=false)
[ERROR] Path to dependency:
[ERROR]         1) com.google.dagger:dagger-compiler:jar:2.38.1

The official docs don't require us to add any other dependency. What am I doing wrong? It's a multi-module project, with a parent.

A: Add this:
  <repositories>
    <repository>
      <id>google-maven</id>
      <name>Google Maven Repo</name>
      <url>https://maven.google.com</url>
    </repository>
  </repositories>

Refer: https://github.com/google/dagger/releases#:~:text=New%20in%20Dagger-,New%20breaking%20changes,-Add%20the%20Google


text:
Q: What does the with-open macro do behind the scenes in clojure? Visually, with-open looks similar to let. I know with-open is for a different purpose but I cannot find a clear answer as to what with-open is doing. And, what is the first argument in with-open?
The documentation says this:

"bindings => [name init ...]
Evaluates body in a try expression with names bound to the values
of the inits, and a finally clause that calls (.close name) on each
name in reverse order."

I do not understand this. I would really appreciate if someone explained what with-open actually does?

A:
what does it do?

A macroexpanded example, with some formatting and after removing unnecessary explicit usages of clojure.core/...:
(macroexpand-1
  '(with-open [reader (some-fn-that-creates-a-reader)]
     (read-stuff reader)))
=>
(let [reader (some-fn-that-creates-a-reader)]
  (try
    ;; This `with-let` is just a no-op, like `(let [] ...)` - an artifact of the implementation.
    (with-open [] (read-stuff reader))
    (finally (. reader close))))

As you can see, it's exactly the same as let, but it wraps the body in a try form and closes the values provided in the binding vector in the finally form.

when should I use it?

When you need for something to be closed at the end, regardless of whether the code in the body was successful or not.
It's a common pattern for reading/writing files with an explicit reader/writer or for using other IO that needs to be opened and closed explicitly.


text:
Q: Including the weights argument in gam() and glmmTMB() yields significant p-values even with random data I'm analysing the effect of x (proportion) on y (proportion) with a random effect RE (categorical). I using the beta regression family and logit link. I'm investigating the reliability of the summary p-value. I've done this by creating some random x-values and running the exact same analysis as on my real data. Against my expectations, the p-value was also very significant with randomly generated x-values. Then I started experimenting with different models, excluding arguments etc. I've boiled it down to the weights = argument, which makes the model either very significant, or not at all if not included. I have no clue why this would be the case, and how I could get around this problem. Below I have provided some data and code.
library(mgcv)
library(glmmTMB)

rm(list = ls())

df <- data.frame(y = c(0.661904761904762, 0.406192519926425, 0.694285714285714, 0.0142857142857143, 0.0142857142857143, 0.0584415584415584, 0.257142857142857, 0.701154401154401, 0.625521669341894, 0.871428571428571, 0.930204081632653, 0.452995391705069, 0.0483709273182957, 0.5, 0.484821428571429, 0.0142857142857143, 0.0345238095238095, 0.248148148148148, 0.795866569978245, 0.661904761904762, 0.985714285714286, 0.985714285714286, 0.985714285714286, 0.550746268656716, 0.208571428571429, 0.0142857142857143, 0.0142857142857143, 0.0142857142857143, 0.0142857142857143, 0.0142857142857143, 0.14030888030888, 0.101142857142857, 0.573982970671712, 0.0142857142857143, 0.0142857142857143),
                 pointWeight = c(3, 233, 10, 89, 4, 22, 44, 99, 89, 17, 35, 341, 57, 36, 128, 39, 144, 54, 394, 12, 46, 229, 55, 67, 5, 28, 2, 160, 124, 294, 555, 425, 302, 116, 48),
                 Random_x = c(0.413296794, 0.347613463, 0.349795504, 0.961276169, 0.95789013, 0.035865447, 0.324590684, 0.44398489, 0.199835127, 0.53304746, 0.03317392, 0.9666195, 0.306412904, 0.208397613, 0.461614514, 0.209814992, 0.136107136, 0.107251692, 0.742954177, 0.620547648, 0.724865263, 0.290264773, 0.877152686, 0.26345651, 0.113437669, 0.333750829, 0.167373418, 0.431189319, 0.158608563, 0.026153635, 0.443326766, 0.450652285, 0.787105741, 0.833940574, 0.040695708),
                 RE = c("M", "H", "H", "H", "H", "H", "H", "H", "H", "K", "K", "K", "K", "K", "K", "K", "K", "K", "M", "M", "M", "M", "M", "ME", "ME", "ME", "P", "P", "P", "P", "P", "P", "V", "V", "K"))

# Using gam()
# With the 'weights =' agrument included.
mygam1 <- mgcv::gam(y ~ Random_x + s(RE, bs="re"), family=betar(link="logit"), data = df, weights = pointWeight)
summary(mygam1)
# Random_x: P value < 0.001

# Without the 'weights =' agrument.
mygam2 <- mgcv::gam(y ~ Random_x + s(RE, bs="re"), family=betar(link="logit"), data = df)
summary(mygam2)
# Random_x: P value = 0.945

# Using glmmTMB()
# With the 'weights =' agrument included.
myglmm1 <- glmmTMB(y ~ Random_x + (1|RE), data = df, beta_family(link = "logit"), weights = pointWeight)
summary(myglmm1)
# Random_x: P value < 0.001

# Without the 'weights =' agrument.
myglmm2 <- glmmTMB(y ~ Random_x + (1|RE), data = df, beta_family(link = "logit"))
summary(myglmm2)
# Random_x: P value = 0.855

The data looks like this, so you would definitely not expect a significant relationship between x and y.

Does anyone know what the problem is here? Why is there such a big difference in significance by either including or excluding the weights argument? I understand that it influences the model, but here it means that both models are significant, while it clearly shouldn't be. Does it have to do with my weights?


text:
Q: react-hls-player streaming video I am using react-hls-player in my project . this is my sample code
 const playerRef = useRef();
    return (
      <ReactHlsPlayer
          playerRef={playerRef}
          src="http://sample.vodobox.com/planete_interdite/planete_interdite_alternate.m3u8"
          autoPlay={false}
          controls={true}
          width="100%"
          height="auto"

      />
  );

i want to know is there any way to change hls video quality ?

A: react-hls-player uses hls.js under the hood. You can get the HLS player instance by using ref.
You can change the level(video quality) by setting currentLevel in hls.js
See the documentation for more information.
Update:
It seems like react-hls-player does not expose hls instance. You can see from source code that playerRef is a reference to video tag. So you cannot access hls API.
You can do two things:

*

*Patch the package and expose hls instance.

*Write your own React component.

A: you can use this package, it supports a callback for the HLS Player object as soon as it becomes available in the component. You can then use this HLS object to change the video quality by setting the currentLevel the documentation is available here


text:
Q: SQL find lack of specific string against multiple ID's in same table ID  can eat
1   apples
1   pears
2   grapes
2   pears
3   apples
3   oranges
3   pears
4   oranges
5   apples
6   pears
6   oranges

Using the above table as an example of data. How can I find the ID of all people who cannot eat apples?

A: Group by the id and take only those groups having no apples entry
select id
from your_table
group by id
having sum(case when can_eat = 'apples' then 1 else 0 end) = 0

A: Simply select the id's except those who can eat apples:
select id from tablename
except
select id from tablename where caneat = 'apples'

A: SELECT Sheet1.ID
FROM Sheet1 LEFT JOIN (SELECT Sheet1.ID
FROM Sheet1
WHERE (((Sheet1.caneat)="apples"))
GROUP BY Sheet1.ID)  AS CanEatApplesList ON Sheet1.ID = CanEatApplesList.ID
WHERE (((CanEatApplesList.ID) Is Null))
GROUP BY Sheet1.ID;

A: This is one of the simplest version of possible solutions:
SELECT DISTINCT a.ID
FROM TableName a
WHERE can_eat NOT in ('apples')
AND a.ID NOT in (SELECT distinct b.ID
FROM TableName b WHERE b.can_eat = 'apples');


text:
Q: problem getting dynamic xml i have an ASP.net page that generates dynamic xml but the get statement of a jquery ajax request won't recognize the file.  this solution worked with a php doc getting the dynamic xml. The asp.net page that generates xml works fine. The ajax request never succeeds. any ideas as to why much appreciated
<%@ Page Language="C#" AutoEventWireup="true"  Debug="true" ContentType="text/xml" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>

A: You are not setting the mime type of the response to text/xml, so the browser will not recognize it as  XML.
Make sure you add a:
Response.ContentType("text/xml");

before you save to the output stream.

A: @Chris , can you try firebug .net panel and see if you are getting results for the ajax...so that we can eliminate the issue.It shows the errors also if there are any.


text:
Q: Adjust Bootstrap image resizing I am trying to make a card div with two images inside, an up arrow and a down arrow.
When in full screen the images look okay and are the full size but due to Bootstraps responsive design, when i reduce the page resolution using the developer console in chrome, the images get smaller and smaller until they cannot be seen on a small device, such as a mobile.
How can i limit how small the images will go?
Thanks.

Title

Description

Points: 0
Replies: 0

      Edit

  Delete

https://jsfiddle.net/5a87h3ky/
I had to remove the original sources for the images due to confidentiality

A: You can set the minimum size of the image using the min-width: px; attribute.
This will prevent the image from getting any smaller than the given size.

A: There are several ways of controlling the size of images with CSS or in HTML. To control your arrows you can use min-height and max-height and also set min-width and max-width.
For example take image_arrow_up.jpg, you can set it's size with:

Another way would be to use percentages, although this is not as concrete as min and max:
<!DOCTYPE html>

Another option is to use CSS with the image-set function, or with scrset + sizes:
.img {
  background-image: url(examples/images/image-384.jpg);
  background-image:
    -webkit-image-set(
      url(examples/images/image-384.jpg) 1x,
      url(examples/images/image-768.jpg) 2x,
    );
  background-image:
    image-set(
      url(examples/images/image-384.jpg) 1x,
      url(examples/images/image-768.jpg) 2x,
    );
}

It also helps to make sure the original image is sized appropriately. For example make the original arrow image sized for a "regular" desktop monitor rather than an oversized arrow that may shrink in unexpected ways.  Or you can use an image management service, such as Cloudinary or 3Scale to create responsive quality images.


text:
Q: Conditional expectations and Brownian bridge I'm currently working about Brownian Bridge and I have to compute the following expectation
\begin{equation} E[W_tW_s\vert W_T]\end{equation}
We consider here that the Brownian bridge is defined as a Brownian motion conditioned to hit 0 at time T, and for $(W_t)_{t≥0}$ a Brownian motion, we give that for $s≤ t ≤ 1$,
\begin{equation} E[W_s \vert W_t = x] = \frac{s}{t}x \text{  and   } Var[W_s \vert W_t = x] = \displaystyle\frac{s(t-s)}{t}\end{equation}
I found 2 different ways to do it that seems good, but I find a different result. Can somebody explain me why there is this difference, and if there's a mistake where it is ?
Method 1 (this is the result I'm supposed to find)
\begin{equation}E[W_tW_s\vert W_T = 0] = E[E(W_s W_t \vert W_t) \vert W_T] = E[W_t E[W_s \vert W_t]  \vert  W_T] = E[W_t^2 \frac{s}{t} \vert W_T] = \frac{s}{t} Var(W_t \vert W_T) = \frac{s}{t} t \frac{(T-t)}{T} = \displaystyle\frac{s(T-t)}{T}\end{equation}
Method 2 (not the same result but (I think) mathematically true)
\begin{equation}E[W_tW_s\vert W_T = 0] = E[(W_t - W_s)W_s + W_s^2 \vert W_T] = E[W_t - W_s \vert W_T] E[W_s \vert W_T] + E[W_s W_s\vert W_T] =  Var(W_s\vert W_T) = \displaystyle\frac{s(T-s)}{T}\end{equation}
Thanking you in advance !

A: I am not convinced by the use (?) of a tower property in method 1, nor of the independence in method 2. Suppose $s<t<T$. Note
$$\begin{bmatrix}
W_T\\
W_t\\
W_s
\end{bmatrix}\sim \mathcal{N}(0,\Sigma),\,\quad \Sigma=\begin{bmatrix}
T&t&s\\
t&t&s\\
s&s&s
\end{bmatrix}$$
So we use the conditional density
$$(W_t,W_s)|W_T=w\sim \mathcal{N}(\mu(w),\Gamma),\,\quad \mu(w)=\begin{bmatrix}
wt/T\\
ws/T\\
\end{bmatrix},\,\quad \Gamma=\begin{bmatrix}
t&s\\
s&s
\end{bmatrix}-\frac{1}{T}\begin{bmatrix}
t^2&ts\\
ts&s^2
\end{bmatrix}$$
Now recall
$$\textrm{Cov}[W_t,W_s|W_T]=E[W_tW_s|W_T]-E[W_t|W_T]E[W_s|W_T]$$
So
$$E[W_tW_s|W_T=w]=s-\frac{st}{T}+\frac{st w^2}{T^2}$$


text:
Q: Enable Resource Governor I have setup an SQL Server 2008 R2 SP1 in my infrastructure. One of my SQL jobs consumes much CPU usage and when this happens all other queries take too long to respond.
After research I read about Resource Governor. This feature throttles CPU usage for defined resources. I have two questions after all information I have found:

*

*Does SQL server or SQL agent needs restart to be enabled?

*How can I configure Resource Governor for only one SQL job?


text:
Q: When to use Workflows When to use workflows and what do you get doing the same thing in workflows that could do otherwise as well? Is there a benefit or its just an overhead?
Are persistence, Transactions and SLA tracking really a feature that workflows can only help you with or be used for those purposes?

A: Firstly What are Workflows,
As per how Microsoft defines it:
Windows Workflow simplifies the authoring of long-running reactive programs by providing:
Activities that access external input.
The ability to create Bookmark objects that can be resumed by a host listener.
The ability to persist a workflow's data and unload the workflow, and then reload and reactivate the workflow in response to the resumption of Bookmark objects in a particular workflow. Source
And when to use them,

It seems from above that workflows give you ability to pause and resume the execution. But! that won't be true, because you could also pause background threads and resume them, so sayings Workflows are doing some magic there is not true. Only reason you would want to use them is to give users the control to reorder execution or add more tasks by just drag and drop of activities so non technical end users can benefit from your complex blocks of code.

When not to use them

Most of the time workflow is just a fancy word for you. Its observed often workflows are implemented where activities are not really resume-able, and shuffling them really breaks things, and your order of execution is not to be changed by end users but it will be the same mostly and you can make changes to execution in code when you need, then be assured workflows are just adding to your complexity.

it is often thought that SLA based tracked execution, logging what's done, or concept of transactions(ACID) is what you get when you use workflows. That is as well not true, you can have them all with same amount of dev efforts otherwise as well.

Also see: When to Use workflow engines?


text:
Q: select first character before and after an expression I have a string that is show in UI as Some Company Name, but in HTML it is Some html text S<!--START CompanyName-->ome Company Nam<!--END CompanyName-->e some html text. Don't ask me why.
How to select S<!--START CompanyName-->ome Company Nam<!--END CompanyName-->e
with Regex in C#? Of course, the Some Company Name can be any other company name.
P.S. A pattern can be repeated more then once.
P.P.S. CompanyName in comments is a tag.

A: I assume that you have the company name within a larger piece of HTML and that the company is "delimited" using comments in a weird way like you describe.

So you want to extract the red text that is "delimited" using the blue text. You want to ignore the green text.
In that is correct you can extract the company name like this:
var text = "bla bla S<!--START CompanyName-->ome Company Nam<!--END CompanyName-->e more bla bla";
var regex = new Regex(@"(?<begin>.)<!--START CompanyName-->(?<middle>[^<]+)<!--END CompanyName-->(?<end>.)");
var match = regex.Match(text);
if (match.Success) {
  var companyName = match.Groups["begin"].Value + match.Groups["middle"].Value + match.Groups["end"].Value;
  Console.WriteLine(companyName);
}

Briefly, you create a pattern that matches the red and blue text and then "grab" red text by adding groups. The groups are then concatenated to create the final result.
If you want to find all company names "delimited" like that in a text you can use the Regex.Matches method:
var companyNames = regex.Matches(text).Cast<Match>()
  .Select(match => match.Groups["begin"].Value + match.Groups["middle"].Value + match.Groups["end"].Value);

If you simply want to replace the company name with another name (and without the HTML comment) you can use Regex.Replace where the groups have been removed from the pattern:
var text = "bla bla S<!--START CompanyName-->ome Company Nam<!--END CompanyName-->e more bla bla";
var regex = new Regex(@".<!--START CompanyName-->[^<]+<!--END CompanyName-->.");
var newText = regex.Replace(text, "ACME Industries");

If you want to keep the HTML comments you will have to put the groups back into the pattern and do a slightly more advanced replacement.

A: *

*Remove all html comments from the string.

*Search for the string you are looking for.

*

*Find the string with comment (probably using this comment as base).

*Remove the comment from the result.


text:
Q: How do I rearrange dates in R? Here is just one date that I have (out of more than 6,000)
02/01/15

This is expressed as January 2nd, 2015. And I would like the date to instead look like the following,
2015/01/02

I read up on this thread: Changing date format to "%d/%m/%Y"
But unless my R does not work properly, none of the answers give the correct format, instead I get this output,
0002/01/15

A: You can do:
format(as.Date("02/01/15", format = "%d/%m/%y"), "%Y/%m/%d")

[1] "2015/01/02"

A: The lubridate package is very useful for date and time manipulation
library(lubridate)
x <- lubridate::dmy('02/01/15')
format(x, format = ('%Y/%m/%d'))