text:
Q: How to prove this geometry inequality (1) with $2(DF+EF)\ge BC$ There is a picture which hope to illustrate the configuration:
$\triangle ABC$ is such that $\angle A=\dfrac{2\pi}{3}$, and $F$ is the midpoint of $BC$, and $D,E$ lie on $AB,AC$ respectively, such that $DE ||BC$.
Show that:
$$2(DF+EF)\ge BC$$
maybe use cosine  theorem,let $\dfrac{BD}{AB}=k,AB=c,BC=a,AC=b$, and in $\Delta ABC$ we use cosine theorem we have
$$a^2=b^2+c^2+bc\tag{1}$$
and $$DF^2=BD^2+BF^2-2BD\cdot BF\cos{\angle B}
=(kc)^2+\dfrac{a^2}{4}-2kc\cdot\dfrac{a}{2}\dfrac{a^2+c^2-b^2}{2ac}=k^2c^2+\dfrac{a^2}{4}-\dfrac{k(a^2+c^2-b^2)}{2}$$
the same as
$$EF^2=\dfrac{a^2}{4}+(kb)^2-\dfrac{k(a^2+b^2-c^2)}{2}$$
it is equivalent
$$\sqrt{4k^2c^2+a^2-2k(a^2+c^2-b^2)}+\sqrt{4k^2b^2+a^2-2k(a^2+b^2-c^2)}\ge a,0\le k\le 1\tag{2}$$
I have tried some inequality (AM-GM,Cauchy-Schwarz,$\cdots$) to prove $(2)$, but didn't see the solution.

A: As you did, let us set $k:=BD/AB$.
If $1/2\le k\lt 1$, then letting $M,N$ be the midpoint of the side $AB,AC$ respectively, we have
$$2(DF+EF)\gt 2DE\ge 2MN=BC$$
In the following, we consider the case when $0\lt k\lt 1/2$.
By the law of cosines,
$$BC^2=AB^2+AC^2-2AB\cdot AC\cos\angle{BAC}\iff a^2=c^2+b^2+cb\tag1$$
By the way,
$$2(DF+EF)\ge BC$$
is equivalent to
$$2DF\ge BC-2EF$$
Since both sides are non-negative, this is equivalent to
$$4DF^2\ge BC^2-4BC\cdot EF+4EF^2$$
which can be written as
$$4BC\cdot EF\ge (BC+2DF)(BC-2DF)+4EF^2$$
Since $BC-2DF\ge 0$, the both sides are non-negative, and so this is equivalent to
$$(4BC\cdot EF)^2\ge ((BC+2DF)(BC-2DF)+4EF^2)^2,$$
i.e.
$$8BC^2\cdot EF^2-BC^4-16EF^4-16DF^4+8BC^2\cdot DF^2+32EF^2\cdot DF^2\ge 0$$
Using that
$$4DF^2=4k^2b^2+a^2-2k(a^2+b^2-c^2)$$
$$4EF^2=4k^2b^2+a^2-2k(a^2+b^2-c^2)$$
this is equivalent to
$$2a^2(4k^2b^2+a^2-2k(a^2+b^2-c^2))-a^4-(4k^2b^2+a^2-2k(a^2+b^2-c^2))^2-(4k^2c^2+a^2-2k(a^2+c^2-b^2))^2+2a^2(4k^2c^2+a^2-2k(a^2+c^2-b^2))+2(4k^2b^2+a^2-2k(a^2+b^2-c^2))(4k^2c^2+a^2-2k(a^2+c^2-b^2))\ge 0,$$
i.e.
$$16k^4(b^2-c^2)^2-32k^3(b^2-c^2)^2-8k^2(a^2(b^2+c^2)-2(b^2-c^2)^2)+8a^4k-3a^4\color{red}{\le} 0$$
Here, let
$$f(k):=16k^4(b^2-c^2)^2-32k^3(b^2-c^2)^2-8k^2(a^2(b^2+c^2)-2(b^2-c^2)^2)+8a^4k-3a^4$$
So, we want to prove that $f(k)\le 0$ for $0\lt k\lt 1/2$.
Now,
$$f'(k)=64(b^2-c^2)^2k^3-96(b^2-c^2)^2k^2-16(a^2(b^2+c^2)-2(b^2-c^2)^2)k+8a^4$$
$$\begin{align}f''(k)&=192(b^2-c^2)^2k^2-192(b^2-c^2)^2k-16(a^2(b^2+c^2)-2(b^2-c^2)^2)\\&=192(b^2-c^2)^2\left(k-\frac 12\right)^2-16a^2(b^2+c^2)-16(b^2-c^2)^2\end{align}$$
With $f''(1/2)\lt 0,f'(0)\gt 0$ and
$$f'\left(\frac 12\right)=8a^2(a^2-b^2-c^2)\gt 0$$
we know that $f(k)$ is increasing for $0\lt k\lt 1/2$, and using $(1)$ gives
$$f\left(\frac 12\right)=-3b^2c^2\lt 0$$
It follows from this that $f(k)\le 0$ for $0\lt k\lt 1/2$. $\blacksquare$

A: This is not a complete solution, just some simplification.
Square both sides of (2) and using (1) to get rid of $a^2$, we obtain:
$$2\sqrt{c^2+b^2(1-2k)^2+bc(1-2k)}\sqrt{b^2+c^2(1-2k)^2+bc(1-2k)}+((b^2+c^2)(1-2k)^2+2bc(1-2k))\ge bc\tag{3}$$
Let $\kappa=1-2k$, thus $-1\le \kappa \le 1$. Then (3) becomes
$$2\sqrt{c^2+b^2\kappa^2+bc\kappa}\sqrt{b^2+c^2\kappa^2+bc\kappa}+((b^2+c^2)\kappa^2+2bc\kappa)\ge bc\tag{4}$$


text:
Q: How to checkout and merge branches to master - GITPYTHON I need to merge all my branches to the master using python. branch local path,buildno getting via environment variables. I have the following code to checkout each branch and merge to master. but it gives some errors when executing the code.
from git import Repo
import git

def mergeRepo(user, buildno, repo, branches, gdwlocalpath, ref="master" ):

branch_list = branches.split(",")
repo = git.Repo(gdwlocalpath)
repo.git.checkout(ref)
current = repo.active_branch
remote_branches = []
for ref in repo.git.branch('-r').split('\n'):
    remote_branches.append(ref.replace("origin/","").strip())
print(remote_branches)

mergeFailure = False
mergeResult = None
prefix='origin/'

for branch in branch_list:
    if branch in remote_branches:
        print(prefix+branch)
        current=repo.git.checkout(prefix+branch)
        master = repo.git.checkout('master')
        base = repo.merge_base( master,current)
        repo.git.index.merge_tree(master, base=base)
        repo.index.commit("Merge into master",parent_commits=(current.commit, master.commit))
        current.checkout(force=True)
    else:
        print("Branch doesn't exist:",branch)

when I execute the code, it gives the following error. (I manually modified the om.docker.dev/xxx/releasekit/VERSION and commit to bug branch and pushed to the bug branch' and trying to execute the script, expected behaviour is new VERSION file should be merge with the master.
error is actually  correct,as my bug branch is ahead of 1 commit to master, but I need to merge that commit to master. but it gives 128 exit code.
if conflict happens it should display an error. (I dont have any exceptions at the moment). if I want to add any exceptions for merge failures and merge conflict how should I modify this. second question is why it is giving exit code 128.
im using python 3.6
 Traceback (most recent call last):
  File "./SingleMergeUp.py", line 82, in <module>
    mergeRepo(username,buildno,arguments.repo,arguments.sources,gdwpath)
  File "./SingleMergeUp.py", line 40, in mergeRepo
    base = repo.merge_base( master,current)
  File "/Users/ab/.virtualenvs/python_core/lib/python3.6/site-packages/git/repo/base.py", line 490, in merge_base
    lines = self.git.merge_base(*rev, **kwargs).splitlines()
  File "/Users/ab/.virtualenvs/python_core/lib/python3.6/site-packages/git/cmd.py", line 440, in <lambda>
    return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
  File "/Users/ab/.virtualenvs/python_core/lib/python3.6/site-packages/git/cmd.py", line 834, in _call_process
    return self.execute(make_call(), **_kwargs)
  File "/Users/ab/.virtualenvs/python_core/lib/python3.6/site-packages/git/cmd.py", line 627, in execute
    raise GitCommandError(command, status, stderr_value)
git.exc.GitCommandError: 'git merge-base Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits) ' returned with exit code 128
stderr: 'fatal: Not a valid object name Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)'

A: I don't think you're using the API properly.
>>> current=repo.git.checkout('origin/master')
>>> current
''
>>> master = repo.git.checkout('master')
>>> master
'Your branch is ahead of \'origin/master\' by 1 commit.\n  (use "git push" to
publish your local commits)'

I don't think you mean to pass these strings to merge-base. Passing the branch names has the desired effect:
>>> repo.merge_base('origin/master', 'master')
[<git.Commit "5999d3082d4051acd9d107eb3e70b3ee0e14d33f">]

To simplify the recipe a bit, if you're trying to merge all remote branches into local master this should do the job:
repo = git.Repo(gdwlocalpath)
repo.git.fetch()
remote_branches = repo.git.branch('-r').splitlines()

repo.git.checkout(ref)
for branch in remote_branches:
    repo.git.merge(branch)

If there are merge conflicts then you should get a GitCommandError.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Comparing raster - pixel colors using PyQGIS? I would like to compare satellite pictures (raster) infra - red.
I have 2 rasters from the same area. I would like the compare pixels with the same xy coordinate using PyQGIS.
10 different values between the same= O and totaly different = 10.
10 different red colors.
So I can compare leaf green the state of the vegetation.
How do I start and which why to go?

A: If you want compare values in 2 raster files, I recommend to use raster calculator in QGIS.

*

*Load 2 rasters to QGIS

*Raster -> Raster calculator

*write "B4@1" - "B5@1" in Raster calculator expression area.

*give any name for output layer

*pressOK

The above steps gives you a raster that values are differences of 2 rasters.
To obtain values of that raster at coordinates of points layer,

*

*Open attribute table of points layer

*Toggle to editing mode (Ctrl + E)

*Open field calculator (Ctrl + I)

*Write expression raster_value('out',1,make_point($x, $y)). out should be replace your created raster name.

*pressOK

You will get new laster layers values at each point in attribute table.


text:
Q: Convert data from CSV file time series I have data like this in my csv file
Date          AAPL      MSFT       GOOG
8/19/2014   100.53  45.78787879     522.7956989
8/18/2014   99.16   45.56565657     517.0967742
8/15/2014   97.98   45.24242424     511.7204301
8/14/2014   97.5    44.71717172     508.1362007
8/13/2014   97.24   44.52525253     506.5232975
8/12/2014   95.97   43.95959596     499.9641577
8/11/2014   95.99   43.63636364     498.8888889
8/8/2014    94.74   43.63636364     494.4086022
8/7/2014    94.48   43.66666667     493.5842294
8/6/2014    94.96   43.17171717     493.5483871

I am reading it like this
price_data <- read.csv("C:\\Prices.csv")

I want to convert it time series. I have seen question at R - Transform Data frame to Time Series and Convert data frame with date column to timeseries. But, in my case I have more than one column to be converted. No of columns can be varying.
One solution seems to be separate each column and convert to time series and then merge back using cbind.
What is best way to do it.
EDIT
I want to calculate component VaR, using this data. I also have positions of symbol as
MSFT 1000
AAPL 1520
GOOG 398

VaR in package "PerformanceAnalytics" accepts time series. Is there any other way I can pass this data to function?

A: Try this:
Lines <- "Date          AAPL      MSFT       GOOG
8/19/2014   100.53  45.78787879     522.7956989
8/18/2014   99.16   45.56565657     517.0967742
8/15/2014   97.98   45.24242424     511.7204301
8/14/2014   97.5    44.71717172     508.1362007
8/13/2014   97.24   44.52525253     506.5232975
8/12/2014   95.97   43.95959596     499.9641577
8/11/2014   95.99   43.63636364     498.8888889
8/8/2014    94.74   43.63636364     494.4086022
8/7/2014    94.48   43.66666667     493.5842294
8/6/2014    94.96   43.17171717     493.5483871"

library(PerformanceAnalytics)
library(zoo)
z <- read.zoo(text = Lines, header = TRUE, format = "%m/%d/%Y")

rets <- diff(z, arithmetic = FALSE) - 1
VaR(rets)

giving:
            AAPL         MSFT         GOOG
VaR -0.005010481 -0.001461903 -0.001090975


text:
Q: Make scrollviewer not capture control left and control right in WPF I have a WPF application where I have defined custom commands that use the key gestures Ctrl + ← and Ctrl + →.  My window has a TextBox and a ScrollViewer and when the TextBox has focus Ctrl + ← and Ctrl + → move the cursor to the beginning of the next or previous word, which is fine.
But on the ScrollViewer it makes the horizontal scroll move as if I had pressed just ← or → .  What's the easiest way to allow the Ctrl + ← and Ctrl + → events to bubble up from my ScrollViewer to the Window where the Command is defined?

A: So I got this working by doing the following
public class MyScrollViewer : ScrollViewer
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
        {
            if (e.Key == Key.Left || e.Key == Key.Right)
                return;
        }
        base.OnKeyDown(e);
    }
}

I think the trick is to understand that the event starts at the top and works it's way down.  Then on the way back up each "layer" checks the Handled boolean and if it isn't set to true it will determine if it will do something and set it if it does.  I needed to short circuit this behavior for my shortcuts so that Handled would still be false when it made it's way back up to the Window level.

A: You must override ScrollViewer's PreviewKeyDown event and set e.Handled = true and pass on the event to parent using something like (this.Parent as FrameworkElement).RaiseEvent(e); if the keys pressed were one of the key combination you assigned to your commands.


text:
Q: How to get individual bytes from a SQL binary field I have a binary field in SQL Server which I want to read one byte at time in a SQL function.  In code I would use a byte array. Is there an equivalent in SQL?
I couldn't find anything with google.

A: You could loop through the binary field using SUBSTRING.
declare @BinaryColumn binary(5)

set @BinaryColumn = convert(binary,'abcde')

declare @Counter int, @ColumnLength int
set @Counter = 1
set @ColumnLength = LEN(@BinaryColumn)

while (@Counter <= @ColumnLength) begin
    select SUBSTRING(@BinaryColumn, @Counter, 1)
    set @Counter = @Counter + 1
end /* while */

A: Varbinary as a type will act as a byte array, and you can read an individual byte from it using substring.

A: The SUBSTRING function should be sufficient. A quick example, assuming table MyTable with column SomeData, binary(10) not null:
DECLARE
  @OneByte  binary(1)
 ,@Loop     int

SET @Loop = 0
WHILE @Loop < 10
 BEGIN
    SET @Loop = @Loop + 1

    SELECT @OneByte = substring(SomeData, @Loop, 1)
     from MyTable

    --  Process accordingly
 END

There are fancier set-based ways to do this, but for short values this should be adequate.


text:
Q: Get task id of scheduled task in celery I am scheduling a celery task in django using apply_async. I need to get the task ID when i schedule the task.
I need to get the task ID so that I can revoke the scheduled task if user chooses to cancel.
  def some_function:
      the_fn_to_be_called.apply_async(kwargs={my_arguments}, countdown=countdown_in_secs)

A: apply_async returns an AsyncResult which has an id attribute.

A: You can set a custom task_id like below.
  from celery import uuid

  def some_function:
      task_id = uuid()

      // Do something with task_id

      the_fn_to_be_called.apply_async(kwargs={my_arguments}, countdown=countdown_in_secs, task_id=task_id)

or
  def some_function:

      // Do something with task_id
      async_result = the_fn_to_be_called.apply_async(kwargs={my_arguments}, countdown=countdown_in_secs)
      task_id = str(async_result)


text:
Q: Run JavaScript function for every two times a button is clicked For my web app, I need some javascript code which will run every two times a button is clicked. I've tried so many different things but I can't quite get it right. Because I'm a rookie coder I can't get any code demos on what I've done but I would really appreciate your help anyways.

A: Here's a simple approach using an index to keep track of even/oddness:

const fn = e => outElem.innerHTML += "clicked!
";
const outElem = document.getElementById("output");
let i = 0;

document.getElementById("btn").addEventListener("click", e => i++ & 1 ? fn(e) : false);
<button id="btn">click</button>

A: Well you can do that:

var clicked = 0;

function myFunction() {

  clicked++;

  console.log(clicked)

  if (clicked === 2) {
    alert('i like cats');
    clicked = 0;
  };

};
<button onclick="myFunction()">click me twice!</button>

A: Here is one way to do it. Replace the action method with your custom method
<button onclick="clicked()">Click Me</button>

function action() {
  console.log('Do something here')
}
var counter = 0;
function clicked() {
  if (counter === 2) {
    action();
    counter = 0;
  }
  counter++;
}
<button onclick="clicked()">Click Me</button>

A: Try this

<button onclick="clickFunction()">click me twice!</button>


text:
Q: Fourier series with half range
Question What are $a_0,a_n,b_n$ equal to with range $-L\leq x \lt0$, rather than the standard $-L\leq x \leq L$?

For example:
$$f(x)=2x^2,\quad-1\leq x\leq0$$
Instead of $f(x)=2x^2,\quad-1\leq x\leq1$
$a_0 = \frac{1}{2L} \int_{-L}^L f(x) \, dx$
$a_n=\frac{1}{2L}\int_{-L}^L f(x) \cos nx \,dx$
$b_n=\frac{1}{2L} \int_{-L}^L f(x) \sin nx \,dx$

I assumed I would just take the Fourier Cosine series, e.g.
$$a_0 = \frac{1}{L}\int_0^L f(x) \, dx=\int_0^1 2x^2 \, dx=\frac23$$
$$a_n = \frac{2}{L}\int_0^L f(x) \cos\left(\frac{n\pi x}{L}\right) \, dx = 2\int_0^1 2x^2 \cos(n\pi x) \, dx=(-1)^n\frac{8}{n^2\pi^2}$$
But this doesn't appear to be right when subbed in to give:
$$f(x) = a_0+\sum_{n=1}^\infty a_n \cos\left(\frac{n\pi x}{L}\right)=\frac23 + \sum_{n=1}^\infty (-1)^n\frac{8}{n^2\pi^2} \cos(n\pi x)$$

A: Hey you have a few things that you are doing wrong. First of all the fact that the function is defined on the interval [-1,0] doesn't mean that you have to try and expand it. You can really just use the formula's for the coefficients on the range [-1,0]. The formula's bounds are between -L and L but the  bounds can be used between any two points with difference 2L which is the period. In your case the period is 1 so the integral of the function on [-L,L] is the same as the integral on the ranges [-1,0]. Another thing that you don't really seem to get is that you can't just arbitrarily calculate the cosine and sine series and expect it to equal the function. You can only say that when the function you are finding the Fourier series for is even for the cosine series and odd for the sine series. In your case the function is neither which means you have to calculate all of the coefficients. Hope that helps

A: Here is what happens to the Fourier Series of a function when the function is restricted from $[-1,1]$ to $[-1,0]$.
Multiplication of functions is equivalent to convolution of their Fourier series. The Fourier series for $[x\lt0]$ is
$$
\begin{align}
\frac12\int_{-1}^0e^{-i\pi nx}\,\mathrm{d}x
&=\left[\frac{i}{2\pi n}e^{-i\pi nx}\right]_{-1}^0\\
&=\frac{i}{2\pi n}\left(1-e^{i\pi n}\right)\\[2pt]
&=\frac{i}{2\pi n}\left(1-(-1)^n\right)\tag{1}
\end{align}
$$
for $n\ne0$ and $\frac12$ for $n=0$.
Using complex exponentials instead of trigonometric functions, we can write
$$
f(x)=\sum_{n=-\infty}^\infty c_ne^{i\pi n}\tag{2}
$$
where $c_0=a_0$ and
$$
c_n=\frac{a_n-ib_n}2\quad\text{and}\quad c_{-n}=\frac{a_n+ib_n}2\tag{3}
$$
If we extend $a_{-n}=a_n$ and $b_{-n}=-b_n$, then both sides of $(3)$ hold for all $n\ne0$.
The convolution of the coefficients gives
$$
\begin{align}
\tilde{a}_0
&=\frac12a_0+\frac{i}{\pi}\sum_{\substack{k=-\infty\\k\ne0}}^{\infty}\frac{1-(-1)^k}{2k}\frac{a_k-ib_k}2\\
&=\frac12a_0+\frac1\pi\sum_{k=1}^\infty\frac{b_{2k-1}}{2k-1}\tag{4}
\end{align}
$$
and for $n\ne0$,
$$
\frac{\tilde{a}_n-i\tilde{b}_n}2
=\frac{i}{\pi}\frac{1-(-1)^n}{2n}a_0+\frac12\frac{a_n-ib_n}2+\frac{i}{\pi}\sum_{\substack{k=-\infty\\k\ne0,n}}^{\infty}\frac{1-(-1)^{n-k}}{2(n-k)}\frac{a_k-ib_k}2\tag{5}
$$
which can be split into
$$
\begin{align}
\tilde{a}_n
&=\frac12a_n+\frac2\pi\sum_{k=1}^\infty\frac{[n-k\text{ is odd}]}{n^2-k^2}kb_k\tag{6}
\end{align}
$$
and
$$
\begin{align}
\tilde{b}_n
&=\frac12b_n-\frac{2[n\text{ is odd}]}{n\pi}a_0-\frac2\pi\sum_{k=1}^\infty\frac{[n-k\text{ is odd}]}{n^2-k^2}na_k\tag{7}
\end{align}
$$


text:
Q: North of <> I haven't succeed with a research of the phrase below cited from the House M.D. - Love Hurts, episode 7x06.
Dr. Lisa Cuddy:

The two of you have a combined IQ north of 300.

What does north of xxx means in case of using with a number, not direction?
Where is likely the usage of this phrase and in what situations?
Do exist another phrases using others of he world sides (sout, west, east) in a similar context?

A: The sentence means that they have a combined IQ above 300.
You can find the definition here: http://dictionary.cambridge.org/pt/dicionario/ingles/north-of-sth

A: On a standard map, north is on top, south on the bottom (and east / west right and left respectively).
This image is the base for using north / south figuratively:

*

*If something is north of, it's above or over,

*if it's south of, it's below the value or threshold mentioned in the context.

So you can rephrase your example as

... a combined IQ over 300.

(East and west are rarely used in a similarly figurative sense.)


text:
Q: Custom UpdateView in Python I am trying to get a custom UpdateView to work in Python/Django.  I believe that the code that I've writtten is mostly correct, as it seems to be returning the proper Primary Key ID in the URL when I click on the associated dropdown.  The problem is that I am not seeing any of the data associated with this record on the screen in update mode.  The screen appears in edit mode, but there is no data.  I suspect the problem is perhaps the django template in the html form?  However, I have played with the form and used {{ form }} and it too returns a blank form.  I've played with this all afternoon and I'm out of guesses.  Here is my view:
def updating_document(request, pk):
    doc = get_object_or_404(Doc, pk=pk)
    form = Update_Doc_Form(request.user, request.POST)
    if request.method == 'GET':
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('App:main_procedure_menu'))
    else:
        print("Form is invalid!")
    return render(request,'Doc/update_doc.html',{'form':form })

I also have an associated form...
Form.py
   class Update_Doc_Form(forms.ModelForm):

     class Meta:
        model = Doc
        exclude = ['user']

        doc_name = forms.CharField(widget=forms.TextInput)
        description = forms.CharField(required=True,widget=forms.Textarea)
        team = forms.CharField(widget=forms.Select)
        document = forms.CharField(required=True,widget=forms.Textarea)

        def __init__(self, *args, **kwargs):
            super(Update_Doc_Form, self).__init__(*args, **kwargs)
            self.fields['doc_name'].widget.attrs['class'] = 'name'
            self.fields['description'].widget.attrs['class'] = 'description'
            self.fields['team'].widget.attrs['class'] = 'choices'
            self.fields['team'].empty_label = ''

I'm a newbie, but I do want to use a custom UpdateView so that I can alter some of the fields and pass user information.  I feel like the code is close, just need to figure out why it's not actually populating the form with data.  Thanks in advance for your help!

A: What a difference a day makes.  Found an answer on SO this morning.  Not sure how to credit the person or issue number....
The answer was to add the following line of code to my form:
    user = kwargs.pop('object_user')

I also needed to add the following function to my View:
def get_form_kwargs(self):
    kwargs = super(ViewName,self).get_form_kwargs()
    kwargs.update({'object_user':self.request.user})
    return kwargs

This question was answered originally in 2013 by Ivan ViraByan.  Thanks Ivan!
I ultimately went with a standard class based UpdateView and scrapped my plans for the custom UpdateView once I was able to figure out how to use the Class Based View(UpdateView) and "pop" off the user information when passing it to the form based on Ivan ViraByan's answer in 2013.
The code above allows you to get the user but not pass it to the ModelForm so that you don't get the unexpected user error.


text:
Q: JS object sorting using coupled ID I have an array of objects:
{name: "bla-1", price: 100 }
{name: "bla-1", price: 150 }
{name: "bla-1", price: 150 }
{name: "bla-2", price: 600 }

I need the output on page to look this like
bla-1 (100) - 1
bla-1 (150) - 2
bla-2 (600) - 1

Can't find solution for this sorting. Any ideas?
Thanks!

A: Use the Array reduce and map methods:
reduced = data.reduce(function (previous, current) {
        var string = current.name + " (" + current.price + ") - ";
        if (!previous[string]) {
            previous[string] = 1;
        } else {
            previous[string]++;
        }
        return previous;
    }, {});
final = Object.keys(reduced).map(function (key) {
    return (key + reduced[key])
});

(where data contains your array of objects)
DEMO


text:
Q: Dependency injected controllers in Play with @ This is not a blocking issue, but I would like to understand how Play handle controller injection better.
In Play document about Routing in 2.4, it is said that:

Play supports generating two types of routers, one is a dependency injected router, the other is a static router. The default is the static router, but if you created a new Play application using the Play seed Activator templates, your project will include the following configuration in build.sbt telling it to use the injected router:
routesGenerator := InjectedRoutesGenerator
The code samples in Play's documentation assumes that you are using the injected routes generator. If you are not using this, you can trivially adapt the code samples for the static routes generator, either by prefixing the controller invocation part of the route with an @ symbol, or by declaring each of your controllers as an object rather than a class.

So, to my understanding, with routesGenerator := InjectedRoutesGenerator in build.sbt, if I use @ prefix for controller invocations, it is the same as making a controller as a singleton object. This goes against the fact that I have been declaring my controllers as class that has some injections (using @Inject), and I prefix all my controller invocations with @ so that IntelliJ does not report error.
So, what does the @ really do my the controller invocations?

A: The @ is an option for the StaticRoutesGenerator, it has nothing to do with the Injected one.
When you follow the recommended way with InjectedRoutesGenerator, your controllers must be a class, in which dependencies will be injected (automatically if you use runtime DI, or manually if you use compile-time DI). In the route file, you just have to reference the class without @.
If you choose the StaticRoutesGenerator, the router follows the same behavior as with Play 2.3 and lower. Controllers are by default object, and you can add a @ to reference a class.
I hope this has addressed your concerns.


text:
Q: How Do I Auto Adjust the Screen Calibration on an ASUS monitor? I'm trying to help a remote user who has an Asus VH196T-P monitor. Part of her screen is cutoff even though the resolution is set properly.
Typically this is an extremely simple problem to solve as you simply hit the "Auto" button on most monitors and it will recalibrate itself and display things on the monitor correctly. However, it appears that Asus monitors (or at least this one) do not have that "Auto" button.
I've tried to have her go through the different menu options with me on the phone but I haven't been able to pinpoint where exactly this option is.
Can one of you out there with an Asus monitor please help me out? I've spent too much time on what should be a ridiculously simple problem (and would be if it wasn't remote).

A: I had this issue previously and there was a trick on the Asus website

*

*Press [MENU] key to enter OSD menu,
then scroll to [System Setup] page
and select [Reset] to restore default
setting

*Press [SPLENDID] key for 4~5 seconds to auto adjust the monitor setting

*You can also enter OSD menu > [Image] > [Position] to adjust the vertical and horizontal position of the image


text:
Q: why isn't int converted to double in printf?
Possible Duplicate:
How is conversion of float/double to int handled in printf?

main()
{
    printf("%f",1);
}

The output I expected was 1.000000,i.e the int 1 being upcasted to double 1.000000 , but it gave 0.000000. Why is it so ?

A: When a non-matching argument is provided to the formatting directive (in this case an int to a %f) the resulting behavior is undefined.
This question, or some variation of it, comes up periodically, see   What is printf's behaviour when printing an int as float? and problem with printf function? for examples/more information.


text:
Q: when hue oozie workflow failed those error logs need to store into hive table Can you please someone help me to get the oozie error logs to hive table when jobs get failed. suggest me the approach how to do as i am new to this.

A: Write a shell script to pick up oozie job logs using:
oozie job -oozie http://localhost:11000 -info <wfid>
oozie job -oozie http://localhost:11000 -log <wfid>

redirect results of it into a file, which you may load into a hive table. Then use a oozie shell action trigger this step at failure.


text:
Q: Athena subquery not working - incorrect table name I'm trying to write an athena query that uses a subquery in the where clause because I want to place a restriction on an array-type field. I don't want to do a cross join unnest since I don't want to flatten each row.
Example query:
SELECT
  foo.some_scalar_field,
  foo.some_other_scalar_field
FROM "fake_db"."table_name"
WHERE EXISTS (SELECT NULL FROM foo.some_array_field as T(item) WHERE item = "THING")

When I do this, I get an error saying that "foo" isn't a valid table name. I'm a bit new to athena, however a previous SQL engine I used to use supported this kind of query. Is doing this not possible in Athena?
Edit;;
I went ahead and added an unnest:
SELECT
  foo.some_scalar_field,
  foo.some_other_scalar_field
FROM "fake_db"."table_name"
WHERE EXISTS (SELECT NULL FROM UNNEST(foo.some_array_field) as T(item) WHERE item = "THING")

Now i get an error that the correlated subquery here is not supported. It seems like Athena doesn't support correlated subqueries?

A: There is no need for unnest and correlated subqueries, just use array functions. Something along this lines:
SELECT
  foo.some_scalar_field,
  foo.some_other_scalar_field
FROM "fake_db"."table_name"
WHERE any_match(foo.some_array_field, item -> item = "THING")


text:
Q: Watchkit app extension not launching My watchkit app extension has suddenly stopped launching. I have a breakpoint in (void)awakeWithContext:(id)context, but that does not get called.
I am running the WatchKit app extension, and all the certificates are in order. I have a 42mm screen set as the external hardware display. I have tried re-starting XCode.

A: I had during the course of development cleared my DerviedData. This removes the WatchKit extension from the list of embedded binaries in the app. To fix this, you have to
1. Rebuild the project.
2. Click on Add Embedded Binaries, select the "App Name WatchKit extension.appex" file.
This solved the problem for me.


text:
Q: check date exist or not in database asp mvc and jquery hello i want  to check if date existe in database or not and if existe  the user receive a message error so i work with asp mvc and try to find soltion but no success can you help me please
this is my controller to get the date event :
    [HttpPost]
    public JsonResult Checkdate(DateTime StartDate)
    {
        return Json(!db.Events.Any(u => u.StartDate== StartDate), JsonRequestBehavior.AllowGet);

    }

this is my script :
     function CheckAvailability() {
            var StartDate = $('#txtStart').val();
            $.ajax({
                type: "POST",
                url: "/Home/Checkdate",
                data: '{StartDate: "' + StartDate + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var message = $("#message");
                    if (response) {
                        //Email available.
                        message.css("color", "green");
                        message.html("date is available");
                    }
                    else {
                        //Email not available.
                        message.css("color", "red");
                        message.html("date is NOT available");
                    }
                }
            });
        };
        function ClearMessage() {
            $("#message").html("");
        };

this is my html :
           <input type="text" id="txtStart" class="form-control" onkeyup="ClearMessage()"/>
          <input id="btnCheck" type="button" value="Show Availability" onclick="CheckAvailability()" />


text:
Q: What happens if a HttpClient.execute() is interrupted? I am calling HttpClient.execute() in a background thread. Does it throw an IOException, when I interrupt the thread?

A: No, at least I haven't ever seen it do so. Note that you can interrupt a download by checking Thread.currentThread().isInterrupted() as you copy from the httpEntity.getContent().
There is more discussion on closing connections in other states here http://old.nabble.com/Close-interrupt-HTTP-connections-td30299655.html


text:
Q: Задержка между кликами JavaScript Есть простой слайдер, при нажатии на кнопку next включается следующая картинка. Можно ли как-то сделать задержку между кликами чтоб новая картинка успевала занимать свое место? Типа сделал клик, а на следующий клик программа откликнется только через секунду.

A: Можно как-то так...

var button = document.querySelector("button"),
    d_num = document.getElementById("num"),
    num = +document.getElementById("num").textContent;

button.addEventListener("click", () => {
  num++;
  d_num.textContent = num;
  button.setAttribute("disabled", "disabled");
  setTimeout(() => {
    button.removeAttribute("disabled");
  }, 1000)
});

0

<button>Click me</button>


text:
Q: asciidoc: custom list symbols Is it possible in asciidoc to choose your own list symbols. In my case I would like to use check marks, but question applies to any symbol in general.
For example, I would like the output to look like:
✓ Apples
✓ Bananas
✓ Cherries

etc

A: The asciidoctor User Manual mentions custom markers as a feature (squares, circles and discs seems to be the only possibilities).
[square]
* one
* two
* three

In your case you can maybe use the checklist as a replacement.
- [ ] not checked
- [X] checked


text:
Q: if window.location == index (homepage) I wanna do a jquery action on every site except the homepage (index).
I can not find out how to setup the if-statement with window.location
thanks for your help

A: You can do:
if(window.location.pathname != "{ do something }")
{
  //run home page jquery.
}
But if prefer PHP like
<?php if ( !is_home() ) { ?>
    ====  jquery code here =====
<?php } ?>
Good luck!! :)

A: This should do what you are looking for as the pathname will be a single / if you are at the home page in MVC. I am not sure about webforms but would assume the same if not it would be the page name such as /Default.aspx.
(function selfRunning() {
if (window.location.pathname.length > 1) {
    alert(window.location.pathname);
}

})();


text:
Q: More memory-optimised version of Bitmap.createScaledBitmap? I fully understand that "premature optimization is the root of all evil." However, I have gotten to a point where I believe that the optimization I wish to do can no longer be considered "premature".
I'm writing an Android application that, among other things, streams a live image feed from a USB device, performs some image processing with OpenCV, converts the frame into a bitmap, and then renders that bitmap to a SurfaceView in real time.
I got everything working, (the live feed is correctly rendered to the SurfaceView) and Android Studio's "Profiler" tool indicates that I've done my memory management well (notice that the garbage collector does not run once in the 10 seconds shown below):

However, because the image I'm streaming is low resolution (320x180), when I render it directly to the SurfaceView, it actually ends up being physically pretty small on the device's screen.
Thus, I decided to scale the bitmap to the maximum size that would fit in the SurfaceView before rendering it to the screen. However, after doing this, I was horrified to find that the memory usage graph now looks horrendous! (The garbage collector runs more than once per second!)

Here are the relevant snippets of code:

*

*Before scaling the bitmap (clean memory graph):
canvas = getHolder().lockCanvas();
openCvMat = frameQueue.take();
Utils.matToBitmap(openCvMat, bitmapFromMat);
mat.release();
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bitmapFromMat, 0, 0, null);
getHolder().unlockCanvasAndPost(canvas);

*After scaling the bitmap (horrendous memory graph):
canvas = getHolder().lockCanvas();
openCvMat = frameQueue.take();
Utils.matToBitmap(openCvMat, bitmapFromMat);
mat.release();
canvas.drawColor(Color.BLACK);
Bitmap scaled = scaleBitmapToViewport(bitmapFromMat);
canvas.drawBitmap(scaled, 0, 0, null);
scaled.recycle();
getHolder().unlockCanvasAndPost(canvas);

*scaleBitmapToViewport() method:
private Bitmap scaleBitmapToViewport(Bitmap bitmap)
{
    //Landscape
    if((canvas.getHeight() * aspectRatio) < canvas.getWidth())
    {
        return Bitmap.createScaledBitmap(bitmap, (int) Math.round(canvas.getHeight() * aspectRatio), canvas.getHeight(), true);
    }
    else //Portrait
    {
        return Bitmap.createScaledBitmap(bitmap, canvas.getWidth(), (int) Math.round(canvas.getWidth() / aspectRatio), true);
    }
}

So it seems that Bitmap.createScaledBitmap() is the culprit. Does anyone know another method to accomplish the same that doesn't give the garbage collector a run for its money?

A: Instead of scaling the bitmap itself like you're doing - can't you scale while drawing?
I'm looking at canvas.drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint) - note that it takes both source and destination rectangles.
You'll want to set the source to your (small) image dimensions and the dest to the dimensions of your surface.


text:
Q: How to resolve java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) in android Getting above exception when using ThreadPoolExecutor for parallel asyncthread execution.
The first time I request to the server which is long running process.
Meanwhile, I send one more request to the server which is executing correctly but first request which still has to run, but stopped after second request.


text:
Q: How to crop AVCaptureScreenInput to a swiftui view frame? I want to use AVCaptureScreenInput to capture a part of the screen in a SwiftUI App. Specifically, I want to only capture the area defined by a View in my app. I tried reading the view position with GeometryReader and translate that frame to screen coordinates using NSWindow.convertToScreen(_) then set AVCaptureScreenInput.cropRect to that CGRect but the captured area is always wrong. What's the correct way to get the cropRect that matches a SwiftUI view?
struct RecorderView: View {
    let window: NSWindow
    let input: AVCaptureScreenInput

    var body: some View {
        GeometryReader { geometry -> AnyView  in
            let previewFrame = geometry.frame(in: .global)
            let screenFrame = self.window.convertToScreen(previewFrame)
            self.input.cropRect = screenFrame
            return AnyView(Spacer().frame(width: 200, height: 200, alignment: .center))
        }
    }
}

A: Converting works correctly (of course if window is correct there), so the important part is how to read a view rect and pass it to recording engine.
The proposed approach is to use view modifier with preference key.

Here is demo part (tested with Xcode 13.3 / macOS 12.2)
VStack {
    HStack {
        // !!! view area to record !!!
        DemoView()
            .gettingInWindow(rect: $viewRect)   // << detect here !!

        Spacer()
    }
    Button(recording ? "Stop" : "Start") {
        if !recording && !validate(destinationURL) {
            return
        }
        recording.toggle()
    }
}
.onChange(of: recording) {
    if $0 {
        // here transfer viewRect, which is window coordinates, to recorder !!
        recording = recorder.startRecording(to: destinationURL, in: viewRect)
    } else {
        recorder.stop()
    }
}

Complete findings & code is here


text:
Q: Use of Parentheses Am I correct in refusing to use parentheses around the area code for my telephone number? Those three digits are not at all incidental.

A: The area code (STDs as we call them in the UK) becomes less and less meaningful as more people adopt mobile phones - where you need to always dial the prefix - and other non-geographical ranges increase in popularity.
There's a convention to wrap the area code in brackets for legibility, however this is (ab)used by many British people when writing their numbers in international format, which I believe just confuses things.
Example 1, a valid "5+6" standard UK number: 01234 567890. Its international format, when being dialed from most overseas countries, is 44 1234 567890 - the leading zero is dropped.
However, if you saw a UK number written as +44 (0)1234 567890, what would you think you'd need to do to dial it from the US? You would be correct in thinking you'd need to drop the leading zero, but now UK people looking at the number written like that might be thinking "hang on, what does that mean?"
The bracket used like that just confuses things and is a hangover from a previous generation of telephone systems. I've decided brackets are only really useful for people reading their own country's numbers - simple, consistent number groupings (and spacing) makes it just as simple for everyone, plus there's no ambiguity over whether the bracketed numbers are required or whether you have to drop some of them depending on where the call is originating from.
I understand that when dialing the UK from the US or Canada, one must first dial the US overseas exit code 011, then the international format number - making our example 011 44 1234 567890. The bracket isn't that confusing, but it's certainly not helpful, and it's not being consistently used. (Because if you're used to seeing the prefix completely enclosed with brackets, and you've never had it explained, what does it mean if four of the five are not?)
Example 2: if I call the US from the UK, I dial 001 555 123 4567. Australia to US would dial 0011 555 123 4567.
The brackets neither hinder nor help, and for that reason I've long proposed they be scrapped for clarity. The same with dashes - they're a linguistic hangover and serve no purpose, the formatting equivalent of a coccyx.
Thus ends the direct answer. Read on for geeky stuff...

As an aside, certain areas of the UK have different number formats with their own anachronisms - making the case for dropping parantheses even stronger (this usually due to population density). All London numbers only ever begin 020, with two following blocks of four, e.g. 020 7123 4567 — yet people regularly misinterpret this as xxxx yyy zzzz, e.g. 0207 123 4567, mostly because there's not been enough raising of awareness by Ofcom (who oversee UK telecoms). The cities of Birmingham and Manchester (to name but two) use the format xxxx yyy zzzz - e.g. 0121 234 5678 or 0161 234 5678 - the area code being 0121/0161 and the rest just zones of exchanges.
Historically, billing for 'local' calls was less than 'national' calls (where your call would physically exit your exchange (American name = Central Office/CO) and be trunked to the destination exchange. Nowadays, the UK's telephone network is entirely IP from the moment your call reaches the frame in your exchange; it's converted back to analogue for the final copper loop to your callee.
Billing rates were normalised quite a few years ago; it costs no less to dial locally than it does nationally - the only difference being that if I lived in Manchester and called someone else in Manchester, I could omit the area code.
A handful of areas in the UK also have archaic assignments of extraordinarily-numbered prefixes: Kendal and its subsidiary exchanges are technically 0153 94, 0153 95 and 0153 96, but local residents mostly write them as 6 digit prefixes and 5 digit numbers; an example is 015395 60123. You'd never know this when dialing the full number, unless you were in the locality - and all the shops usually just list the last five digits (making it a great puzzle for those who don't live in the area)!
If you're interested in this kind of stuff, there's a great Wikipedia article to get you started.

A: The choice of how to write down or print a telephone number consisting of three-digit area code and seven-digit main number is a matter of personal preference undoubtedly influenced by popular convention. The main forms that I've seen used on business cards in the United States are

(XXX) XXX-XXXX

and

XXX-XXX-XXXX

although I have occasionally also seen

XXX.XXX.XXXX

In none of these three cases is there any doubt what the numbers mean or how to dial them successfully, so it can hardly be argued that any of the forms is wrong in some existentially significant way.
As for the argument that the form (XXX) XXX-XXXX is logically flawed because it treats the first three digits as "incidental," I think that StoneyB's comment (above) is dispositive:

These are conventions which make the numbers easier to read and remember. Moreover, the area code is 'incidental' when the call is local.

What he means, of course, is that if you are dialing from a phone that has the same area code that the call recipient's phone has, you should not dial the first three numbers of the ten-digit set. The area code is relevant only in situations where you are dialing from a different area code—and in that sense the inclusion of the area code (in parentheses) makes sense as a way of indicating that the person placing the call may or may not need to dial those three numbers.


text:
Q: How to set default DISPLAY for all SSH sessions? I'm SSH-ing to my PC from my phone, and I have to run export DISPLAY=:0.0 every time. Is there any way I can set it on my PC so that I don't have to do it on my phone?

A: You can write at the end of your .bashrc file:
export DISPLAY=:0.0

You can also have a condition for ssh
if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_CONNECTION" ]; then
    export DISPLAY=:0.0
fi


text:
Q: xamarin barcode scanning with torch I'm trying to use xzing barcode scanner in my xamarin android application but I need to also turn on the torch so that I scan in low light conditions.
I'm using xamarin essentials to attempt to turn on the torch but I keep getting the following error message.
     Torch for camera "0" is not available due to an existing camera user

I have a xaml page that contains my scanner
<Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <forms:ZXingScannerView
                IsScanning="{Binding IsScanning}"
                IsAnalyzing="{Binding IsAnalyzing}"
                Result="{Binding Result, Mode=TwoWay}"
                ScanResultCommand="{Binding ScanCommand}" />
            <forms:ZXingDefaultOverlay
                x:Name="scannerOverlay"
                BottomText="Place the red line over the barcode you'd like to scan." />
            <Button Grid.Row="1" Text="Toggle Flash" Command="{Binding FlashToggleCommand}"></Button>
        </Grid>

Then I have the following code behind the command to toggle the torch
public Command FlashToggleCommand
    {
        get { return new Command(async () =>
        {
            try
            {

                // Turn On
                await Flashlight.TurnOnAsync();

                //// Turn Off
                //await Flashlight.TurnOffAsync();
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
            }
            catch (Exception ex)
            {
                // Unable to turn on/off flashlight
            }

        }); }
    }

But I keep on dropping into the exception block with the error message above
I'm assuming that the barcode scanner is utilizing the camera, does anyone know how to get the flashlight/torch to turn on whilst the zxing scanner is also running?

A: You can add button in your scan layout, achieve the button click event like following code.
 private void Button_Clicked(object sender, System.EventArgs e)
        {
            zxingView.ToggleTorch();

        }

NOTE:zxingView is
<zxing:ZXingScannerView x:Name="zxingView" Grid.Row="1" OnScanResult="Handle_OnScanResult" IsScanning="true" WidthRequest="200" HeightRequest="200" />

And I notice you used MVVM in the forms:ZXingScannerView, as Jason said. you can use IsTorchOn property. Bind a property and use Button click command to control it.
<Button Text="click" Command="{Binding FlashToggleCommand}"></Button>
<zxing:ZXingScannerView x:Name="zxingView" Grid.Row="1" OnScanResult="Handle_OnScanResult" IsScanning="true" IsTorchOn="{Binding TouchON}"
                                WidthRequest="200" HeightRequest="200" />

background code.
public PartialScreenScanning()
        {
            InitializeComponent();
            this.BindingContext = new MyViewModel();
        }

Then create a MyViewModel.cs.
   public class MyViewModel: INotifyPropertyChanged
    {
        public MyViewModel()
        {

        }
        bool _touchON=false;
        public Command FlashToggleCommand
        {
            get
            {
                return new Command(async () =>
                {

                    TouchON = !TouchON;
                });
            }
        }

        public bool TouchON
        {
            set
            {
                if (_touchON != value)
                {
                    _touchON = value;
                    OnPropertyChanged("TouchON");

                }
            }
            get
            {
                return _touchON;
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Here is runnning GIF.


text:
Q: I need to log hangfire to a different SQL table than nlog We have nlog saving all logs to a specific database table. Hangfire is automatically logging to the same table. My manager wants the two logs separated; nlog in one table and hangfire in another. I'm completely new to hangfire and I was hoping someone might have a suggestion.

A: In case you are using ASP.NET Core, in the Startup class you can specify the exact storage for all Hangfire tables:
public void ConfigureServices(IServiceCollection services)
{
    services.AddHangfire(config => config.UseXXXStorage());
}

The way how to implement custom logger you can also look into hangfire-docs


text:
Q: How to check special conditions before saving data with Hibernate Sample Scenario
I have a limit that controls the total value of a column. If I make a save that exceeds this limit, I want it to throw an exception. For example;
Suppose I have already added the following data: LIMIT = 20

id
code
value

1
A
15

2
A
5

3
B
12

4
B
3

*

*If I insert (A,2) it exceeds the limit and I want to get exception

*If I insert (B,4) the transaction should be successful since it didn't exceed the limit

*code and value are interrelated

What can I do
I can check this scenario with required queries. For example, I write a method for it and I can check it in the save method. That's it.
However, I'm looking for a more useful solution than this

*

*For example, is there any annotation when designing Entity ?

*Can I do this without calling the method that provides this control every time ?

What examples can I give ?

*

*@UniqueConstraint checking if it adds the same values

A: Neither Hibernate nor Spring Data JPA have anything built-in for this scenario. You have to program the transaction logic in your repository yourself:
@PersistenceContext
EntityManager em;

public addValue(String code, int value) {
    var checkQuery = em.createQuery("SELECT SUM(value) FROM Entity WHERE code = :code", Integer.class);
    checkQuery.setParameter("code", code);

    if (checkQuery.getSingleResult() + value > 20) {
        throw new LimitExceededException("attempted to exceed limit for " + code);
    }

    var newEntity = new Entity();
    newEntity.setCode(code);
    newEntity.setValue(value);
    em.persist(newEntity);
}

Then (it's important!) you have to define SERIALIZABLE isolation level on the @Transactional annotations for the methods that work with this table.
Read more about serializable isolation level here, they have an oddly similar example.
Note that you have to consider retrying the failed transaction. No idea how to do this with Spring though.

A: Using transaction
The most common and long-accepted way is to simply abstract in a suitable form (in a class, a library, a service, ...) the business rules that govern the behavior you describe, within a transaction:
@Transactional(propagation = Propagation.REQUIRED)
public RetType operation(ReqType args) {
    ...
    perform operations;
    ...
    if(fail post conditions)
        throw ...;
    ...
}

In this case, if when calling a method there is already an open transaction, that transaction will be used (and there will be no interlocks), if there is no transaction created, it will create a new one so that both the operations and the postconditions check are performed within the same transaction.
Note that with this strategy both operation and invariant check transactions can combine multiple transactional states managed by the TransactionManager (e.g. Redis, MySQL, MQS, ... simultaneously and in a coordinated manner).
Using only the database
It has not been used for a long time (in favor of the first way) but using TRIGGERS was the canonical option used some decades ago to check postconditions, but this solution is usually coupled to the specific database engine (e.g. in PostgreSQL or MySQL).
It could be useful in the case where the client making the modifications is unable or unwilling (not safe) to check postconditions (e.g. bash processes) within a transaction. But nowadays it is infrequent.
The use of TRIGGERS may also be preferable in certain scenarios where efficiency is required, as there are certain optimization options within the database scripts.

A: You should use a singleton (javax/ejb/Singleton)
@Singleton
public class Register {
  @Lock(LockType.WRITE)
  public register(String code, int value) {
    if(i_can_insert_modify(code, value)) {
      //use entityManager or some dao
    } else {
      //do something
    }
  }
}


text:
Q: How do I access specific parameters of a wx.EVT_LISTBOX event? I am trying to design a GUI where one of the components is a wx.ListBox with multiple selection capability (style = wx.LB_MULTIPLE.) I also have another panel where I want to set the text to match the long description of the last item selected on the ListBox.
I am aware that I can bind the ListBox to a function in this manner:
listbox_obj.Bind(wx.EVT_LISTBOX, self.set_description)
However, when I define the method...
def set_description(self, event):
...how do I extrapolate from the event parameter which item in the ListBox was the LAST one selected, and whether the item was selected or de-selected?

A: I think that you are going to have to track the data yourself.
For example:
import wx

class TestListBox(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.OldSelections= []
        self.NewSelections = []
        self.aList = ['zero', 'one', 'two', 'three', 'four', 'five',
                      'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
                      'twelve', 'thirteen', 'fourteen']
        self.lb = wx.ListBox(self, wx.NewId(), choices=self.aList, style=wx.LB_EXTENDED)
        self.lb.Bind(wx.EVT_LISTBOX, self.EvtMultiListBox)
        self.lb.SetSelection(0)
        self.Show()

    def EvtMultiListBox(self, event):
        self.NewSelections = self.lb.GetSelections()
        print('EvtMultiListBox: %s\n' % str(self.lb.GetSelections()))
        for i in self.NewSelections:
            if i not in self.OldSelections:
                print (self.aList[i],"was added")
        for i in self.OldSelections:
            if i not in self.NewSelections:
                print (self.aList[i],"was removed")
        self.OldSelections = self.NewSelections
        print("\n")

if __name__ == '__main__':
    app = wx.App()
    TestListBox(None)
    app.MainLoop()

A: EVT_LISTBOX generates wx.CommandEvent. (see https://wxpython.org/Phoenix/docs/html/wx.CommandEvent.html)
For the list box event there is: IsSelection and GetSelection.


text:
Q: Why are 2.1A USB chargers 10W not 10.5W? This has baffled me ever since the iPad was released a few years back.  Why do power supplies designed for tablets output 2.1A but are marketed as 10W?  If anything, 10.5W rounds up to 11...  Or why don't they just use 2.0A supplies?

A: More than likely, at the full 2.1 amps load current, the output voltage will have dropped slightly below 5 volts to 4.76 volts - still an acceptable voltage for its use.
Note 4.76 volts x 2.1 amps = 9.996 watts
Come to think of it I believe the old standard for TTL power supplies is 5V +/5% = 4.75 volts to 5.25 volts. See here for confirmation. Also this picture: -

Taken from here.


text:
Q: Mapbox GL JS markers show/hide Using Mapbox GL JS and following the provided example which shows how to attach markers to the map
// add markers to map
geojson.features.forEach(function(marker) {

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
    .addTo(map);
});

how can I hide/show on click event different markers

A: Something like this?
function hide() {
    let markers = document.getElementsByClassName("marker");
    for (let i = 0; i < markers.length; i++) {
        markers[i].style.visibility = "hidden";
    }
}

function show() {
    let markers = document.getElementsByClassName("marker");
    for (let i = 0; i < markers.length; i++) {
        markers[i].style.visibility = "visible";
    }
}


text:
Q: React-query doesn't refresh the component I've got a problem with react-query. I've got a component which includes components that show a loading spinner if the integrationDetails query is fetching. But when the query finishes fetching, my component doesn't update at all. I tried creating state and then using that, but the problem persits.
UPDATE: The component does in fact update, but the child component  doesn't.
...

  const currentWorkspace = useGetCurrentWorkspaceDetail();
  const integrationDetails = useGetIntegrationDetails();
  useEffect(() => {
    integrationDetails.refetch(); //force refetch the query whenever I enter the page.
//problem persists even if I comment this part out
  }, []);

  useEffect(() => {
    console.log(integrationDetails.isFetching); //this logs true and then false.
  }, [integrationDetails]);

  if (currentWorkspace.isLoading) {
    return (

        <LoadingSpinner />

    );
  }

  return (

          <Card>
            <CardTabs tabs={["1"]}>

Global Tracking Code

                  <StatusStripe
                    isLoading={integrationDetails.isFetching}
                    ...
                  />

                ...

A: Your first useEffect would be just like componentDidMount and it will only be called on first render as you have passed an empty list i.e [] in its second argument.
You could have written your logic in your second useEffect where you know when the data is fetched and you can do your state setting or binding there.


text:
Q: Does GlobalScope.launch create a new thread or run in the same thread? I have the question from this code.
https://kotlinlang.org/docs/reference/coroutines/basics.html
fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello,") // main thread continues while coroutine is delayed
    Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}

I replace delay(1000L) with Thread.sleep(1000L). If GlobalScope.launch block will run in the same thread, the Thread.sleep(1000L) will block the thread. However it seems not.
fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        Thread.sleep(1000L)
        println("World!")
    }
    println("Hello,") //
    Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}

A: The GlobalScope lets you start coroutines which more-or-less have the same behavior as daemon threads since they are detached from any Coroutine-Job and basically run as long as the application. Their lifecycle is only limited by the application itself. This is something you want to avoid by using "structured concurrency" which basically means that your coroutines should be nested in a way that you can control them without manually keeping track of their references and joining them for example in order to await their computations. So in your real-life code you should avoid GlobalScope as much as possible, since there's most certainly a better solution.
As to your question, and as already mentioned, the GlobalScope runs on the Dispatchers.Default pool, which means that you will block some worker thread but not the one you spawned the coroutine from.
On the other hand, if you were to write this block:
fun main() {
    runBlocking {
        Thread.sleep(1000L)
        println("World!")
    }
    println("Hello,")
    Thread.sleep(2000L)
}

you'll see that the coroutine blocks the main thread and the output will show a different result. That is because runBlocking runs on the caller thread main rather than one of the worker pool threads.

A: GlobalScope.launch { } will not necessarily create a new thread, but it will use one from a shared pool because it uses the Default dispatcher. So, as far as your question is concerned, in your snippet, the block passed to launch runs in a different thread indeed.
In the documentation about dispatchers and threads, you will find the following:

The default dispatcher, that is used when coroutines are launched in GlobalScope, is represented by Dispatchers.Default and uses shared background pool of threads

And in the Dispatchers.Default doc, you can find:

By default, the maximal level of parallelism used by this dispatcher is equal to the number of CPU cores, but is at least two. Level of parallelism X guarantees that no more than X tasks can be executed in this dispatcher in parallel.

Note that you could change the dispatcher by providing one as a parameter of launch.

A: The GlobalScope.launch{..} function will not block. It returns an Job object, which you may use to wait for a result.
Behind the scenes, the GlobalScope uses the default dispatcher Dispatchers.Default. You may see it, for example, by printing a thread name inside a launch{..} function.
You will need to run more coroutines to see them blocking each other because of Thread.sleep calls.
https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html


text:
Q: Apache Spark Issue with Py4JJavaError while code execution No matter what I do I can't get past this error while running Apache spark.
I am running it through Jupyter Notebook which is pointing to Anaconda environment.
I am new to spark learning and I have checked so many blogs to fix this error but nothing helped.
any help is appreciated to fix it.
I am running java 8.
Code I am running :
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster("local").setAppName("My App")
sc = SparkContext(conf = conf)
lines=sc.textFile("C:/User/PG186028/Spark.txt")
lines.count()

error generated after  lines.count():
---------------------------------------------------------------------------
 ---------------------------------------------------------------------------
Py4JError                                 Traceback (most recent call last)
<ipython-input-6-c98a4dbe0cd9> in <module>()
----> 1 files.count()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyspark\rdd.py in count(self)
   1051         3
   1052         """
-> 1053         return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
   1054
   1055     def stats(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyspark\rdd.py in sum(self)
   1042         6.0
   1043         """
-> 1044         return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
   1045
   1046     def count(self):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyspark\rdd.py in fold(self, zeroValue, op)
    913         # zeroValue provided to each partition is unique from the one provided
    914         # to the final reduce call
--> 915         vals = self.mapPartitions(func).collect()
    916         return reduce(op, vals, zeroValue)
    917

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyspark\rdd.py in collect(self)
    812         """
    813         with SCCallSiteSync(self.context) as css:
--> 814             sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
    815         return list(_load_from_socket(sock_info, self._jrdd_deserializer))
    816

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pyspark\rdd.py in _jrdd(self)
   2472                                       self._jrdd_deserializer, profiler)
   2473         python_rdd = self.ctx._jvm.PythonRDD(self._prev_jrdd.rdd(), wrapped_func,
-> 2474                                              self.preservesPartitioning)
   2475         self._jrdd_val = python_rdd.asJavaRDD()
   2476

~\AppData\Local\Continuum\anaconda3\lib\site-packages\py4j\java_gateway.py in __call__(self, *args)
   1523         answer = self._gateway_client.send_command(command)
   1524         return_value = get_return_value(
-> 1525             answer, self._gateway_client, None, self._fqn)
   1526
   1527         for temp_arg in temp_args:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    330                 raise Py4JError(
    331                     "An error occurred while calling {0}{1}{2}. Trace:\n{3}\n".
--> 332                     format(target_id, ".", name, value))
    333         else:
    334             raise Py4JError(

Py4JError: An error occurred while calling None.org.apache.spark.api.python.PythonRDD. Trace:
py4j.Py4JException: Constructor org.apache.spark.api.python.PythonRDD([class org.apache.spark.rdd.MapPartitionsRDD, class org.apache.spark.api.python.PythonFunction, class java.lang.Boolean]) does not exist
    at py4j.reflection.ReflectionEngine.getConstructor(ReflectionEngine.java:179)
    at py4j.reflection.ReflectionEngine.getConstructor(ReflectionEngine.java:196)
    at py4j.Gateway.invoke(Gateway.java:237)
    at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
    at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)


text:
Q: First time Magenta generated midi doesn't play Trying to get first time Magenta installation to generate a playable midi.
After upgrading bazel on OSX to 'Build label: 0.2.3' Magenta
works with this 'example.mid' input midi placed in a subdirectory.
tmp3/example.mid

4d54 6864 0000 0006 0001 0002 00dc 4d54 726b 0000 0019 00ff 5804
  0402 1808 00ff 5103 03d0 9000 ff59 0200 0001 ff2f 004d 5472
  6b00 0000 4000 c000 0090 3c64 8151 3c00 0b3e 6481 513e 000b 4064
  8151 4000 0b41 6481 5141 000b 4364 8151 4300 0b45 6481 5145
  000b 4764 8151 4700 0b48 6481 5148 0001 ff2f 00

after running
bazel build magenta:convert_midi_dir_to_note_sequences

then
mkdir out3
touch out3/newexample.mid

./bazel-bin/magenta/convert_midi_dir_to_note_sequences \
--midi_dir=/Users/user/Downloads/magenta-master/tmp3 \
--output_file=/Users/user/Downloads/magenta-master/out3/newexample.mid \
--recursive

you get
out3/newexample.mid

2101 0000 0000 0000 072b 7cb0 0a36 2f69 642f 6d69 6469 2f74 6d70
  332f 3364 3864 3537 3835 6634 3838 6666 6438 3837 3566 3130
  6131 3238 3538 6336 6636 6332 3135 3230 3638 120b 6578 616d 706c
  652e 6d69 641a 0474 6d70 3320 dc01 2a04 1004 1804 3200 3a09
  1100 0000 0000 006e 4042 0d08 3c10 6421 6666 6666 6666 ce3f 4216
  083e 1064 1900 0000 0000 00d0 3f21 3333 3333 3333 df3f 4216
  0840 1064 1900 0000 0000 00e0 3f21 9999 9999 9999 e73f 4216
  0841 1064 1900 0000 0000 00e8 3f21 9999 9999 9999 ef3f 4216
  0843 1064 1900 0000 0000 00f0 3f21 cdcc cccc cccc f33f 4216
  0845 1064 1900 0000 0000 00f4 3f21 cccc cccc cccc f73f 4216
  0847 1064 1900 0000 0000 00f8 3f21 cccc cccc cccc fb3f 4216
  0848 1064 1900 0000 0000 00fc 3f21 cccc cccc cccc ff3f 49cc
  cccc cccc ccff 3f13 5fbf 34

but the music file doesn't play. Even if you add 'ff2f 00' (common suggestion) to the end.
How can you make this resulting file play in a player such as Quicktime 7? Any ideas?

A: We've recently added a model that you can train to generate new sequences. Have a look at https://github.com/tensorflow/magenta/blob/master/magenta/models/basic_rnn/README.md.
Thanks!


text:
Q: What is the upper limit on the number of dc2.large nodes I can elastically scale to in a Redshift cluster? This is the documentation that I'm referencing below:

*

*https://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-limits.html

*https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html
Document 1 states that the maximum number of DC2 nodes that you can allocate to a cluster is 128. However, it doesn't specify the maximum number of a specific flavour or DC2 type nodes. I'm specifically wondering about dc2.large and it's upper elastic resize limit.
Document 2 states that the dc2.large type node range is 1–32. It also states that the ra3.xlplus type have a node range of 2-16, and that "You can create a cluster with the ra3.xlplus node type that has up to 16 nodes. You can resize it with elastic resize to a maximum of 32 nodes." 32 is twice the stated node range of 16. There is no equivalent remark about dc2.large (nothing to the effect of "You can resize a 32 node dc2.large node up to 64" ).
I'm left with the question: what is the upper limit on the number of dc2.large nodes I can elastically scale in Redshift?
More specifically, can I elastically scale any dc2.large cluster containing anywhere from 17 to 32 nodes, up to a maximum of 64 nodes?


text:
Q: Linq method for creating a sequence of separate objects? I must be reinventing the wheel here - but I've searched and I can't find anything quite the same...
Here's my code for creating a sequence of zero or more objects that have a default constructor:
public static IEnumerable<T> CreateSequence<T>(int n) where T: new()
{
    for (int i = 0; i < n; ++i)
    {
        yield return new T();
    }
}

My question is quite simple: Is there a Linq equivalent of this I should be using?

A: Try this:
Enumerable.Range(1,count).Select(_ => new T());

Enumerable.Range will give you the current number from the specified range as parameter, but you can simply ignore that (named as _ in the example).

A: Yes there is: var items = Enumerable.Repeat(new YourClass(), 10);


text:
Q: Why is Worf in The Undiscovered Country? After watching The Undiscovered Country I noticed that the advocate for Kirk and Bones during their trial is none other than Michael Dorn, a.k.a. Worf.  During the trial I believe they even call the advocate Worf by name.
How can this be when Worf is alive and aboard the Enterprise D almost 70 years later? Is there any in-universe explanation for this, or any outside universe explanation for why Michael Dorn is in Undiscovered Country?

A: According to Memory Alpha;

Between the fourth and fifth seasons of Star Trek: The Next
  Generation, Dorn played Colonel Worf in Star Trek VI: The Undiscovered
  Country. Although the relationship was not stated on screen, the
  filmmakers' intention was that the Star Trek VI character was the
  grandfather of the Next Generation character. (Star Trek Encyclopedia)

In an interview with Michael Dorn (seen at 1h20m32s) during The Undiscovered Country segment of the 25th Anniversary Special he states this relationship.

A: Appearences to the contrary (after all it's even the same actor) this is a  different Worf than in TNG:

Although it was never confirmed on screen, publicity materials for
  Star Trek VI indicated that Colonel Worf was intended to be the
  grandfather of his Next Generation namesake, and the father of Mogh.


text:
Q: Dyanmic panel data model with interaction of lagged dependant variable in Stata I want to (consistently) estimate the following model:
$y_{it}=\beta_0 +\beta_1 y_{i,t-1} +\beta_2 y_{i,t-1}\times x_{it} +\beta_3 x_{i,t} +\beta_4 \Gamma_{it}+\varepsilon_{it}   $
Given I use a lagged dependent variable, I am considering to use the Arellano Bond estimator. In Stata I would run:
gen yXy = L.y*x
xtabond y yXx x Gamma, vce(robust)

Should I be concered about the interaction?


text:
Q: Componentizing complex functionality in an MVC web app This is question about MVC web-app architecture, and how it can be extended
to handle componentizing moderately complex units of functionality.
I have an MVC style web-app with a customer facing credit card charge page.
I've been asked to allow the admins to enter credit card payments as well,
for times when credit cards are taken over the phone.
The customer facing credit card charge section of the website is currently
it's own controller, with approximately 3 pages and a login.  That controller
is responsible for:

*

*Customer login credential authentication

*Credit card data collection

*Calling a library to do the actual charge.

*reporting the results to the user.

I would like to extract the card data collection pages into a component of
some kind so that I can easily reuse the code on the admin side of the app.
Right now my components are limited to single "view" pages with PHP style
embedded Perl code.
This is a simple, custom MVC framework written in Perl.  Right now, controllers
are called directly from the framework to service web requests.  My idea is to
allow controllers to be called from other controllers, so that I can componentize
more complex functionality.
For simplicity I think I prefer composition over inheritance, even though it will
require writing a bunch of pass-through methods (actions).  Being Perl, I could in
theory do multiple inheritance.
I'm wondering if anyone with experience in other MVC web frameworks can comment
on how this sort of thing is usually done.
Thank you.

A: Create a component (class?) which wraps all the cc specific functionality, and expose it through appropriate methods/functions.
Use composition to provide your controllers, both customer and admin facing, an instance of the cc component, and have both call the appropriate methods to achieve what needs to happen.
I have dealt with something similar many times, and I absolutely prefer keeping my "controllers" (or any other code that depends directly on third party libraries for that matter) as "stupid" as possible, and do like you said - pass through anything that calls for functionality that's specific to your app. This keeps my code easy to test, which is what drives most of my design these days.
I hope we're talking about the same things, MVC can be applied at so many different levels it sometimes gets confusing.


text:
Q: Consolidating rows in an associative array to merge specific values I am retrieving an  array of associative arrays from my sql
for ex -
Array( [0]=>{Array([user_id] => 6920 [user_fname] => Jay [user_lname] => Martin [user_skill] => Java}
[1]=> {Array([user_id] => 6920 [user_fname] => Jay [user_lname] => Martin [user_skill] => C++}
[2]=> {Array([user_id] => 6920 [user_fname] => Jay [user_lname] => Martin [user_skill] => php}

and this goes on for all the users , how can i consolidate these three rows to get a single row with all the skills.PHP
answer i want ->Array( [0]=>{Array([user_id] => 6920 [user_fname] => Jay [user_lname] => Martin [user_skill] => Java , C++ ,PHP}


text:
Q: Why doesn't this Hello World X11 code run on NetBSD? I am on a brand new 5.1 NetBSD box.
I copied the "Hello World" code from here rosettacode.org
The code compiles with this command:
cc -I /usr/X11R7/include -L /usr/X11R7/lib -lX11 helloworld.c

When I run a.out, I get the following error:
Shared object "libX11.so.6" not found

I confirmed that /usr/X11R7/lib/libX11.so.6 does exist.
ldd output:
./a.out:
    -lX11.6 => not found
    -c.12 => /usr/lib/libc.so.12

How do I properly link against X11 on NetBSD?

A: The official NetBSD answer is to use RPATH. Crazy.


text:
Q: float:right in the correct order it appears in HTML code I have a container div and two child divs both with the float: right property.
My code looks like:

               .container {width: 50%}

              .a, .b { float: right }

Semantically, I should see [  [A][B]] on my page, but it shows up as
[  [B][A]]
I get that I can just reorder my HTML and put B first if I want to see A first, but that's not really semantically correct. What's the proper way to do this?

A: You can use flexbox and justify-content: flex-end;

.container {
  background: #eee;
  width: 50%;
  display: flex;
  justify-content: flex-end;
}

a

b

Or set the child divs to display: inline-block; and use text-align on the container to align to the right.

.container {
  background: #eee;
  width: 50%;
  text-align: right;
}
.container > div {
  display: inline-block;
}

a

b

And another solution would be to introduce a new element to wrap the child elements, float the new element right, then float the children left.

.container {
  background: #eee;
  width: 50%;
  text-align: right;
  overflow: auto;
}
.inner {
  float: right;
}
.inner > div {
  float: left;
}

a

b

A: .container {
  width: 100%;
}
.container div {
  float:right;
  width: 50%;
}

A: Another solution is to just wrap the child elements in a tag, and float it right :), but this is subject to adding a wrapping element, and converting your child div tags into inline blocks.
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Test</title>

a

b

A: Floating your elements right will order them with the last div first. Try floating them both left.
.a, .b
{
float: left;
}


text:
Q: How to rescale image data before converting data types This is a follow up to my previous post here
I'm using the following lines of code to convert the data type(from uint16 to uint8) of z-stack images in MATLAB
%Multiple image tiff conversion%

File_Name = "Test_Image.tiff";
Image_Data = imfinfo(File_Name);
Number_Of_Images = length(Image_Data);

Tiff_Structure = struct('Image_File',[]);

for Image_Index = 1: Number_Of_Images

      Image = imread(File_Name,Image_Index);
      Uint8_Image = im2uint8(Image);

      %For more information and plotting individual images%
      Tiff_Structure(Image_Index).Image_File = Uint8_Image;

      %Saving the converted images to one tiff file%
      imwrite(Uint8_Image,'Converted_Image.tiff','WriteMode','append');

end

In the documentation available here it is mentioned that

im2uint8(I) converts the grayscale, RGB, or binary image I to uint8,
rescaling or offsetting the data as necessary

I would like to know if it is possible to rescale the data before converting the datatype to uint8 and how this rescaling can be done.
Test_Image.Tiff
Suggestions will be really helpful.
EDIT:
Plotting the histogram of the image data gives the following
img_data = imfinfo(f);
n_img = length(img_data);

imgs = cell(1, numel(img_data));
for i = 1:numel(img_data)
    imgs{i} = imread(f, i);
end
imgs = cat(3, imgs{:});
figure(1)
imhist(imgs(:), 256)

A: Assuming Image has values in the range 0-65535 (16bit)
to scale the values into an 8bit image:

*

*first divided the image by 65535 (2^16)  - this will normalize value range to 0-1

*now you need to rescale to 8bit range of values, multiplying the image by 255

so basically:
scaled_image = uint8(double(Image)./65535*255)

Note: To preserve the dynamic range of the image it might be better to choose a different value to normalize with, e.g some max value across all stack


text:
Q: Gradle task hierarchy I tried to write my own Gradle Tasks:
task(incVersion) << {
[...]
}

task cleanDocBuild(dependsOn: ['clean','cleanDoc','incVersion','asciidoctor','war']) << {

    cleanDoc.dependsOn clean
    incVersion.dependsOn cleanDoc
    asciidoctor.dependsOn incVersion
    war.dependsOn asciidoctor

    println 'Start Building...'
}

task(cleanDoc) << {
[...]
}

asciidoctor {
[...]
}

I want to call the tasks in a specific order:

*

*clean

*clenDoc

*incVersion

*asciidoctor

*war

How can I do this?

A: You have to set not only dependsOn property of the task (this property doesn't make any ordering, just provide task dependencies), but also mustRunAfter or shouldRunAfter, according to your needs, to make this tasks run in predefined order. You can read about it in official user guide. In your case this could be something similar to:
clenDoc.mustRunAfter clean
incVersion.mustRunAfter clenDoc
asciidoctor.mustRunAfter incVersion
war.mustRunAfter asciidoctor
cleanDocBuild.mustRunAfter war


text:
Q: SQL Injection: Which statement can prevent better SQL injection I am using PDO statement as below
select * from `admine_user` where `user_id` = ? and passw = ?
$resultfm1 = DB::instance()->prepare($query)->execute
(array($escapedid,$hashedpass))->fetchAll();

I am thinking to use
select * from `admine_user` where `user_id` = :user and passw = :pwd
$resultfm1 = DB::instance()->prepare($query)->execute
(array(":user"=>$escapedid,":pwd"=>$hashedpass))->fetchAll();

Out of above statements which is better to use which can prevent SQL injection effectively as now i can not use mysql_real_escape_string

A: MySQL only supports positional parameters (the ? placeholders), so PDO internally converts named parameters into positional parameters during the prepare step.
So in fact both styles ultimately do the same thing with respect to MySQL.
Also, "emulated prepares" doesn't actually do anything in the prepare step, it just saves the query string. When you execute, you supply values and they are interpolated into the query and then submitted to MySQL. If you don't trust this process, then disable emulated prepares.
This is not to say that PDO does anything unsafe, although early versions of PDO had some bugs.
Just make sure you're using a current version of PDO (basically anything in PHP 5.3 or newer), and then both styles are as safe as one can be.
Notwithstanding any regression bugs that may occur after I write this...


text:
Q: Perfino agent failed to start on linux machine I tried to start perfino agent on linux machine using various ways. I also followed recommended instruction from perfino  more times. It still failing. Please help me. Please see below error.
[root@localhost ~]# -javaagent:perfino.jar=server=192.168.9.30,name=TestLinux,group=MAIN
bash: -javaagent:perfino.jar=server=192.168.9.30,name=TestLinux,group=MAIN: command not found...

A: The "-javaagent..." string you are trying to execute directly is a VM parameter that you have to add to your java invocation.


text:
Q: How to add post parameters to $.ajax and $.ajaxSubmit I used the ajax method of jquery for my forms. but now I need to add a field to the function.
how can I have my forms fields and my new post parameter.
        var frm = $(n);
        $.ajax({
                type: frm.attr('method'),
                url: frm.attr('action'),
                //contentType:frm.attr('enctype'),
                data: frm.serialize(),
                success: function (data) {
                    $(dataform).html(data);
                    $(des).html('');
                    $("button[type='submit']").attr('disabled',null);
                }
        });

the data parameter should be like this:
data: frm.serialize() + {'foo':'bar'}

thanks in advance.

A: .serialize() returns a string of parameters like you'd see in a querystring, so just add on + "&foo=bar"

A: try something like this
data: frm.serialize()+'&foo=bar',


text:
Q: How passing string on filter keyword to Django Objects Model? How can i pass variables on a keyword  object filter on a view?
I have:
my_object = MyModel.objects.filter(my_keyword =my_filter_values)

I want to grab my_keyword from a variable coming from a string, like this:
my_string = 'my_keyword'
my_object = MyModel.objects.filter(my_string=my_filter_values)

But this doesn't work because Django doesn't know my_string from MyModel.
Edit: I've found this SO question - I'll test and report back.

A: You can do something like this:
my_filter = {}
my_filter[my_keyword] = my_filter_value

my_object = MyModel.objects.filter(**my_filter)

As an example, your variables might be:
my_keyword = 'price__gte'
my_filter_value = 10

Which would result in getting all objects with a price >= 10. And if you want to query on more than one field, you can just add another line below my_filter[my_keyword]:
my_filter[my_keyword] = my_filter_value
my_filter[my_other_keyword] = my_other_filter_value


text:
Q: How can I retain order in a list? I want to return the string representing the list of the new names of all the photos in the same order as the original string. However, my final_string is currently in a different order.
def fetch_date_time(photo):
    return photo.split(", ")[2]

def prefixed_number(n, max_n):
    len_n = len(str(n))
    len_max_n = len(str(max_n))
    prefix = "".join(["0" for i in range(len_max_n - len_n)]) + str(n)
    return prefix

def solution(S):
    list_of_pics = S.split("\n")
    city_dict = {}

    for pic in list_of_pics:
        city = pic.split(", ")[1]
        if city in city_dict:
            city_dict[city].append(pic)
        else:
            city_dict[city] = [pic]

    final_string = ""

    for city_group in city_dict:
        city_dict[city_group].sort(key=fetch_date_time)
        for ind, photo in enumerate(city_dict[city_group]):
            city = photo.split(",")[1]
            ext = photo.split(", ")[0].split(".")[-1]
            max_len = len(city_dict[city_group])
            number = prefixed_number(ind + 1, max_len)
            city_dict[city_group][ind] = city + number + "." + ext + "\n"
        final_string += "".join(city_dict[city_group])

    return final_string

string = """photo.jpg, Warsaw, 2013-09-05 14:08:15
john.png, London, 2015-06-20 15:13:22
myFriends.png, Warsaw, 2013-09-05 14:07:13
Eiffel.jpg, Paris, 2015-07-23 08:03:02
pisatower.jpg, Paris, 2015-07-22 23:59:59
BOB.jpg, London, 2015-08-05 00:02:03
notredame.png, Paris, 2015-09-01 12:00:00
me.jpg, Warsaw, 2013-09-06 15:40:22
a.png, Warsaw, 2016-02-13 13:33:50
b.jpg, Warsaw, 2016-01-02 15:12:22
c.jpg, Warsaw, 2016-01-02 14:34:30
d.jpg, Warsaw, 2016-01-02 15:15:01
e.png, Warsaw, 2016-01-02 09:49:09
f.png, Warsaw, 2016-01-02 10:55:32
g.jpg, Warsaw, 2016-02-29 22:13:11"""

print(solution(string))

My current output:
Warsaw01.png
 Warsaw02.jpg
 Warsaw03.jpg
 Warsaw04.png
 Warsaw05.png
 Warsaw06.jpg
 Warsaw07.jpg
 Warsaw08.jpg
 Warsaw09.png
 Warsaw10.jpg
 London1.png
 London2.jpg
 Paris1.jpg
 Paris2.jpg
 Paris3.png

Expected output:
Warsaw02.jpg
London1.png
Warsaw01.png
Paris2.jpg
Paris1.jpg
London2.jpg
Paris3.png
Warsaw03.jpg
Warsaw09.png
Warsaw07.jpg
Warsaw06.jpg
Warsaw08.jpg
Warsaw04.png
Warsaw05.png
Warsaw10.jpg

A: The below code may help.
string = """photo.jpg, Warsaw, 2013-09-05 14:08:15
john.png, London, 2015-06-20 15:13:22
myFriends.png, Warsaw, 2013-09-05 14:07:13
Eiffel.jpg, Paris, 2015-07-23 08:03:02
pisatower.jpg, Paris, 2015-07-22 23:59:59
BOB.jpg, London, 2015-08-05 00:02:03
notredame.png, Paris, 2015-09-01 12:00:00
me.jpg, Warsaw, 2013-09-06 15:40:22
a.png, Warsaw, 2016-02-13 13:33:50
b.jpg, Warsaw, 2016-01-02 15:12:22
c.jpg, Warsaw, 2016-01-02 14:34:30
d.jpg, Warsaw, 2016-01-02 15:15:01
e.png, Warsaw, 2016-01-02 09:49:09
f.png, Warsaw, 2016-01-02 10:55:32
g.jpg, Warsaw, 2016-02-29 22:13:11"""

class row:
  def __init__(self, image, city, date):
    self.image = image
    self.city = city
    self.date = date

def read_rows(text):
  rows = []
  for line in text.split('\n'):
    image, city, date = line.split(',')
    rows.append(row(image, city, date))
  return rows

def rename_city(rows):
  known_cities = {}
  for row in rows:
    if row.city in known_cities:
      known_cities[row.city] += 1
      row.city = "%s%02d"%(row.city, known_cities[row.city])
    else:
      known_cities[row.city] = 1
      row.city += "01"

def get_citynames(rows):
  cities = []
  for row in rows:
    cities.append(row.city)
  return cities

def solution(input):
  rows = read_rows(input)
  sorted_rows = sorted(rows, key=lambda x: x.date)
  rename_city(sorted_rows)
  return get_citynames(rows)

print("\n".join(solution(string)))

Output
 Warsaw02
 London01
 Warsaw01
 Paris02
 Paris01
 London02
 Paris03
 Warsaw03
 Warsaw09
 Warsaw07
 Warsaw06
 Warsaw08
 Warsaw04
 Warsaw05
 Warsaw10

A: To solve this problem you need:

*

*Group your data by city;

*Sort entries belong to same city by date;

*Generate new filenames and get back to original order.

First of all, we need to split each line of your string by ", ":
lines = [s.split(", ") for s in string.splitlines()]

*

*To group our lines by city we can use two different methods:
1.1. Make a dictionary where city will be a unique key and value will be list of all lines with this city:
grouped_photos = {}
for line in lines:
    city = line[1]
    if city in grouped_photos:
        grouped_photos[city].append(line)
    else:
        grouped_photos[city] = [line]

Here you can notice that there's no sense to generate lines if proceed with this method as it leads to one useless iteration, we can iterate over string.splitlines():
grouped_photos = {}
for line in string.splitlines():
    splitted = line.split(", ")
    city = splitted[1]
    if city in grouped_photos:
        grouped_photos[city].append(splitted)
    else:
        grouped_photos[city] = [splitted]

Also we can shorten code a bit using defaultdict:
from collections import defaultdict

...

grouped_photos = defaultdict(list)
for line in string.splitlines():
    splitted = line.split(", ")
    grouped_photos[splitted[1]].append(splitted)

1.2. Use groupby(). The main difference from previous method is that groupby() requires sorted data.
from itertools import groupby
from operator import itemgetter

...

lines.sort(key=itemgetter(1))
grouped_photos = {c: list(p) for c, p in groupby(lines, itemgetter(1))}

I've used dict comprehension only as temporary storage of groupby() return, we won't need it later.

*Now we need to sort every list with same city by date. The common way to compare dates stored in string (which is necessary for sorting) is to initialize datetime object using some format with datetime.strptime() or with datetime.fromisoformat() if string matches standard format.
from datetime import datetime

...

grouped_photos["Warsaw"].sort(key=lambda x: datetime.fromisoformat(x[2]))

But with format you have we can also exploit lexicographic_order which python uses to compare sequences (string is  sequence too). It means that we don't need to modify our date string just leave it as it is.
grouped_photos["Warsaw"].sort(key=itemgetter(2))

So, basically we need to sort every value in grouped_photos:
for value in grouped_photos.values():
    value.sort(key=itemgetter(2))

*To generate new filenames and put them in original order firstly we need to store original list index. For this we should modify initial data split to include also an index of line:
lines = [s.split(", ") + [i] for i, s in enumerate(string.splitlines())]

Size of our result list will be exactly the same as in source, so to not use sorting again we can initialize result list as list on None values with same length with lines, then iterate over grouped_photos and save generated filename to initial index.
To generate filename we need name of city, index in sorted list and original file extension. To extract file extension from filename we can use splitext() or simply call str.rsplit():
from os.path import splitext

ext = splitext("pisatower.jpg")[1]
# OR
ext = "." + "pisatower.jpg".rsplit(".", 1)[1]

Let's restore original order and set new filenames:
from os.path import splitext

...

result = [None] * len(lines)
for photos in grouped_photos.values():
    for i, (name, city, _, index) in enumerate(photos, 1):
        result[index] = f"{city}{i}{splitext(name)[1]}"

The only thing left is zero-padding of index. Length of list is a maximum index, so maximum width we can obtain using string length of length of each list. There are plenty of ways to pad number, I'll use extended format syntax in this example:
for photos in grouped_photos.values():
    padding = len(str(len(photos)))
    for i, (name, city, _, index) in enumerate(photos, 1):
        result[index] = f"{city}{i:0{padding}}{splitext(name)[1]}"

Now we need to combine all together. Using common sense and basic knowledge about loops we can combine code above with certain optimizations:
from operator import itemgetter
from itertools import groupby
from os.path import splitext

string = """photo.jpg, Warsaw, 2013-09-05 14:08:15
john.png, London, 2015-06-20 15:13:22
myFriends.png, Warsaw, 2013-09-05 14:07:13
Eiffel.jpg, Paris, 2015-07-23 08:03:02
pisatower.jpg, Paris, 2015-07-22 23:59:59
BOB.jpg, London, 2015-08-05 00:02:03
notredame.png, Paris, 2015-09-01 12:00:00
me.jpg, Warsaw, 2013-09-06 15:40:22
a.png, Warsaw, 2016-02-13 13:33:50
b.jpg, Warsaw, 2016-01-02 15:12:22
c.jpg, Warsaw, 2016-01-02 14:34:30
d.jpg, Warsaw, 2016-01-02 15:15:01
e.png, Warsaw, 2016-01-02 09:49:09
f.png, Warsaw, 2016-01-02 10:55:32
g.jpg, Warsaw, 2016-02-29 22:13:11"""

lines = [s.split(", ") + [i] for i, s in enumerate(string.splitlines())]
lines.sort(key=itemgetter(1, 2))
result = [None] * len(lines)
for city, [*photos] in groupby(lines, itemgetter(1)):
    padding = len(str(len(photos)))
    for i, (name, _, _, index) in enumerate(photos, 1):
        result[index] = f"{city}{i:0{padding}}{splitext(name)[1]}"

I've noticed that you haven't used any import in your code, maybe it's some weird requirement, so here is same code without imports and syntax sugar:
string = """photo.jpg, Warsaw, 2013-09-05 14:08:15
john.png, London, 2015-06-20 15:13:22
myFriends.png, Warsaw, 2013-09-05 14:07:13
Eiffel.jpg, Paris, 2015-07-23 08:03:02
pisatower.jpg, Paris, 2015-07-22 23:59:59
BOB.jpg, London, 2015-08-05 00:02:03
notredame.png, Paris, 2015-09-01 12:00:00
me.jpg, Warsaw, 2013-09-06 15:40:22
a.png, Warsaw, 2016-02-13 13:33:50
b.jpg, Warsaw, 2016-01-02 15:12:22
c.jpg, Warsaw, 2016-01-02 14:34:30
d.jpg, Warsaw, 2016-01-02 15:15:01
e.png, Warsaw, 2016-01-02 09:49:09
f.png, Warsaw, 2016-01-02 10:55:32
g.jpg, Warsaw, 2016-02-29 22:13:11"""

grouped_photos = {}
for i, line in enumerate(string.splitlines()):
    splitted = line.split(", ") + [i]
    city = splitted[1]
    if city in grouped_photos:
        grouped_photos[city].append(splitted)
    else:
        grouped_photos[city] = [splitted]

result = [None] * (i + 1)
for photos in grouped_photos.values():
    photos.sort(key=lambda x: x[2])
    padding = len(str(len(photos)))
    for i, (name, city, _, index) in enumerate(photos, 1):
        result[index] = city + str(i).zfill(padding) + "." + name.rsplit(".", 1)[1]

Add print(*result, sep="\n") to any of versions to get output in console.
Output:
Warsaw02.jpg
London1.png
Warsaw01.png
Paris2.jpg
Paris1.jpg
London2.jpg
Paris3.png
Warsaw03.jpg
Warsaw09.png
Warsaw07.jpg
Warsaw06.jpg
Warsaw08.jpg
Warsaw04.png
Warsaw05.png
Warsaw10.jpg


text:
Q: R Shiny: Table Created Using Latex Is Messy I am new to Shiny as well as Latex.
I am using the following script to crate a table output in Shiny.
---
library(xtable)

ui <- shinyUI(
        fluidPage(
                withMathJax(),
                titlePanel("Panel Title"),
                sidebarLayout(
                        sidebarPanel(
                                checkboxGroupInput("inputs", label = "Select Inputs:",
                                                   choices=c("Option A",
                                                             "Option B"),
                                                   selected="Option A")),
                        mainPanel((tabsetPanel(
                                tabPanel("Test Table",h2("Test Table Header"),uiOutput("tabletest"))))))))

server=function(input, output) {output$tabletest<-renderUI({
        table2=data.frame(A=c("{SubheaderA}","Item A1","Item A2","Item A3","{Subheader B}"," Item B1","Item B2","Item B3"),
                          B=c("","Value  A1","Value  A2","Value  A3","","Value  B1","Value  B2","Value  B3"))
        test=print(xtable(table2,type="latex",sanitize.text.function=identity))
        html=paste0("$$",test,"$$")
        list(tags$script(src = 'https://c328740.ssl.cf1.rackcdn.com/mathjax/2.0-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML', type = 'text/javascript'),
             HTML(html)
        )
})
}

shinyApp(ui = ui, server = server)

==
Would anyone be to help me with figuring out why I am not able to print tables.
Any help is greatly appreciated!


text:
Q: How to map a dynamic relation in JPA I have an Entity for holding Selection Domains, e.g. for Dropdown Boxes:
@Entity
public class Selection {
    @Id
    private long id;

    private String category;
    private long index;
    private String text;
}

The corresponding table has entries for several categories:
ID    Category   Index   Text
-----------------------------------
1     Status     1       New
2     Status     2       Active
3     Status     3       Obsolete
4     Type       1       Simple
5     Type       2       Complex
[...]

Now I have Entities which should map special categories of Selections:
@Entity
public class EntityWithStatus {
    @Id
    private long id;

    @JoinColumn(name="status_id", referencedColumnName="index", nullable=false)
    private Selection status;
}

Status "New" has index 1, but this index also applies to Type "Simple". I don't want to map to Selection's Primary Key. Is there a way to restrict this mapping to specific categories?
One way I found is to use Inheritance, using the category as discriminator. But that would mean I have to add Entities/Classes for every category. I'd like to prevent that...


text:
Q: OverscrollerIn android I have search a lot on android overscroller but did not get any appropriate matter
,so help me by providing good tutorial,
 I goes to Api Demo also but didnot get any thing that is undersatble

Thanx in advance

A: Check API demo for 2.3.4 Version 10
 android-sdk-windows ->samples->version 10