text:
Q: Clean way to return a one-element Numpy array Is there a clean way to write functions that return a one-element numpy array as the element itself?
Let's say I want to vectorize a simple square function and I want my return value to be the same dtype as my input. I could write something like this:
def foo(x):
    result = np.square(x)
    if len(result) == 1:
        return result[0]
    return result

or
def foo(x):
    if len(x) == 1:
        return x**2
    return np.square(x)

Is there an easier way to do this? So that I can use this function both for scalars and for arrays?
I know that I can check the dtype of my input directly and use IF statements to make it work, but is there a cleaner way?

A: I am not really sure whether or not I fully understood the question, but maybe something like this would help?
def square(x):
    if 'numpy' in str(type(x)):
        return np.square(x)
    else:
        if isinstance(x, list):
            return list(np.square(x))
        if isinstance(x, int):
            return int(np.square(x))
        if isinstance(x, float):
            return float(np.square(x))

I defined some test cases:
np_array_one = np.array([3.4])
np_array_mult = np.array([3.4, 2, 6])
int_ = 5
list_int = [2, 4, 2.9]
float_ = float(5.3)
list_float = [float(4.5), float(9.1), float(7.5)]

examples = [np_array_one, np_array_mult, int_, list_int, float_, list_float]

So we can see how the function behaves.
for case in examples:
    print 'Input type: {}.'.format(type(case))
    out = square(case)
    print out
    print 'Output type: {}'.format(type(out))
    print '-----------------'

And the output:
Input type: <type 'numpy.ndarray'>.
[ 11.56]
Output type: <type 'numpy.ndarray'>
-----------------
Input type: <type 'numpy.ndarray'>.
[ 11.56   4.    36.  ]
Output type: <type 'numpy.ndarray'>
-----------------
Input type: <type 'int'>.
25
Output type: <type 'int'>
-----------------
Input type: <type 'list'>.
[4.0, 16.0, 8.4100000000000001]
Output type: <type 'list'>
-----------------
Input type: <type 'float'>.
28.09
Output type: <type 'float'>
-----------------
Input type: <type 'list'>.
[20.25, 82.809999999999988, 56.25]
Output type: <type 'list'>
-----------------

From the test cases, the input and output is always same. However, the function is not really clean.
I used some of the code from this question at SO.

A: I think you need a very good reason to want that. (Could you explain why you need this?)
All the clients of this function will have to check if the result is an array or a single element or will have to convert it to an array.
Typically you also get very elegant code if you iterate over all elements of an array, even if it is just one element.
Unless it always has to be a single element (this is a conversion function), but then the return statement should throw an exception instead on empty/long arrays.
Apart from that, the code you have is perfectly understandable/readable. Any smart trick to 'improve' it would be a mental burden each time the future you or a colleague has to read it.
-- edit
I see your point. Probably you already ran into the problem that len(1) is not allowed (int/float do not have len()), so you could do a type check on the input argument. E.g.
if (type(x) == list) ...


text:
Q: How to set radiobuttonlist based on text I'm using jquery ui and I've got a radiobuttonlist that renders like so:

<input id="MainContent_rblModule_0" type="radio" name="ctl00$MainContent$rblModule" value="11" />Meeting
<input id="MainContent_rblModule_1" type="radio" name="ctl00$MainContent$rblModule" value="10" />Service Order
<input id="MainContent_rblModule_2" type="radio" name="ctl00$MainContent$rblModule" value="6" checked="checked" />Sub Project
<input id="MainContent_rblModule_3" type="radio" name="ctl00$MainContent$rblModule" value="6" />IT

<input id="MainContent_rblModule_4" type="radio" name="ctl00$MainContent$rblModule" value="6" />Engineering Services
<input id="MainContent_rblModule_5" type="radio" name="ctl00$MainContent$rblModule" value="6" />Building Maintenance
<input id="MainContent_rblModule_6" type="radio" name="ctl00$MainContent$rblModule" value="6" />Ask The CEO
<input id="MainContent_rblModule_7" type="radio" name="ctl00$MainContent$rblModule" value="6" />Safety

If I wanted to select the radio button list by value I could easily do:
var radio = $("[id*=MainContent_rblModule] input[value=" + projectId + "]");
radio.prop("checked", true).button("refresh");

But I need to select based on text so I tried:
var text = "IT";
var radio = $("[id*=MainContent_rblModule] label:contains('" + text + "')").find("input");
 radio.prop("checked", true).button("refresh");

This doesn't work...but I tried to figure out the best way to do this, maybe contains is not a good idea...

A: Try,
var text = "IT";
var radios = $("#MainContent_rblModule label:contains('" + text + "')");
radios.each(function(){
 $(this).prev('input').prop("checked", true).button("refresh");
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular iterate only display one output I try iterate array value.. When I try to console.log my array, it produce values that I want .. but when I display the data, only one of the value of data got display. Here is my function
getEarning() {
    for (let booking of this.bookings) {
      if (booking.status == 'paid') {
        this.earn = booking.price * 0.6;
        console.log(this.earn);
      }
    }
  }

here how I display the data

Earning: RM {{earn}}

here is my console log result

and here the result of my display data

A: The problem is that you are looping through this.bookings and setting a new value to this.earn and console logging it in that point in time. So you only display the latest value of this.earn in your html file. There are several ways to solve this. The simplest way would be to calculate the earnings directly in your html. Thus, you don't need getEarning() in your ts file.

  ...

Earning: {{booking * 0.6 | number: '1.2-2'}}


text:
Q: Can't use self.size for UIView subclass written in Objective-C but imported to swift project? Right now I have a StarView which is a subclass of a UIView. It works fine in another project, but when I imported it into a new swift project, I'm getting the error..."Property 'size' not found on objet of type 'StarView'.
- (instancetype)initWithGalaxySize:(CGSize)galaxySize
                     colorMode:(GalaxyColorMode)colorMode
              andShouldFlicker:(BOOL)shouldFlicker
{
self = [super initWithGalaxySize:galaxySize
                       colorMode:colorMode
                andShouldFlicker:shouldFlicker];
if (self)
{
    // Size
    self.size = CGSizeMake(10.0f, 10.0f);

    // Scale
    CGFloat randomScale = floatInRange(0.4f, 0.8f);
    self.transform = CGAffineTransformMakeScale(randomScale, randomScale);

    // Rotation
    self.transform = CGAffineTransformRotate(self.transform, degreesToRadians(floatInRange(0.0f, 360.0f)));
}

return self;
}

Any idea why it won't let me call self.size? I also get the same errors for self.width and self.height.

A: UIView uses self.frame.size or self.bounds.size depending on which coordinate space you want.


text:
Q: Using Vim commands in a Bash Script so im trying to create a bash script that runs on MAC command line to a remote server and uses some mv commands to move some files around but i also need it to open up a file and add a line to the top of the file and save it in the middle of the script heres what i have so far:

(this is adjusting permissions so i can edit the file)
chef-client -r xxxxxxredactedxxxxxxredacted
cd /xxx/postgresql/xx/main/
Sudo chmod -R 775 filenamehere
sudo chown -R postgres:postgres filenamehere

read -p 'Enter the IP: ' ip

echo "Enter the file name :"
read -r filename

  echo "Type this below: host all all "$ip"/24 trust : "
read -r line

cd /etc/postgresql/12/main/
printf '1i\n%s\n.\nwq\n' "$line" | ed "$filename".   <-- **this is the problem line**

^ this command gives me permission denied because of access, for some reason i can edit it with vim but not this command

its worth noting these commands arent ran through my pc so my ability to move files is somewhat limited, its ran through SSM ing into an IP of a test enviroment through my command line

Normally I manually VIM into the file and add a line to the top

A: Don't know if you're using echo to output the prompts because you didn't know about the -p read option or you wanted the new lines.
You could use command grouping to add a line at the top of your file.
read -p "Have you copied a file to the data shipper? (yes/no)"

if [ "$REPLY" == "yes" ]; then
    read -p "Enter a variable: " VARIABLE

    read -p "Enter a file name: " FILE

    cd /var/xxxredacted////
    cd /tmp/
    sudo mv "$FILE" /varxxxredactedxxxxxxxx/drop
    cd /var/redactedxxxxredactedxx/drop
    sudo unzip "$FILE"
fi

read -p "Enter the file name:\n" FILENAME
read -p "Enter the line to be added:\n" LINE

{ echo $LINE; cat "$FILENAME"; } > "${FILENAME}.new"
mv "$FILENAME"{.new,}

sed could be used too, if the line had to go to a specific line :
# If \n is omnited, $LINE will just be inserted on
# line 1 instead of appending a new line
sed -i "${LINENB}s/$LINE\n/" $FILENAME


text:
Q: How visual studio 2015 build android project I need an expert's explanation about how visual studio 2015 builds the android application. Before going to develop a complex and costly application with Visual Studio 2015, knowing the build process will help to avoid bugs that cannot be resolved.
Do they build the project as a java binary code or native code? If they use a java build, is that process the same as the gradle build? If they use native, what is the steps involved with the building process?
How Xamarin involves with the building process?

A: If you use Xamarin in Visual Studio you will get a native application after build so the performances of it are the same. You can also use Cordova in Visual Studio 2015 but then application you build are not native.
You can read more about Android Build process of Xamarin here.


text:
Q: Setting default value of zref abspage to avoid arithmetic overflow error while computing rotation of tikz picture logo (picture on every page) Combing answers from this question:
How to use \pageref{foo} as a number?
Positioning TikZ picture on page background to be on each page of twosided document
I was able to create picture of my logo ("artistic" planetary model of atom) that is rotating with nucleus and electrons rotating separately (nested pictures, if I understand it correctly), but when my document exceeded about 90 pages, It stopped compiling with "Arithmetic overflow" error.
In response of Ms. Fischer to first question (I am using that one, because I have in my book arabic and roman counters; sadly after switch those are restarted), there is argument to set default value of last page
\zref@extractdefault{LastPage}{abspage}{1}

I am failing at using that instead of
\getpagerefnumber{LastPage}

I think its because of "@" character being in that statement, and I dont know how to fix it with \makeatletter and \makeatother with correct syntax.
I am opened to any solutions, even those with different approaches (I read also about using package "xassoccnt," in this question:
Refer to the current page number, but not \thepage, but the real absolute
but I dont know how to set default value of both counters to make it work for my case. For compilation I am using luaLaTeX and learning lua too, so that might be also a way, but my limited knowledge is still not enough.
Next i present MWE, which is pretty extensive given my (kinda) complicated picture, but with MWEs from mentioned questions, I can make it work by simple changing default counter value, but in my specific case I dont know how to do that.
Mwe is compilable, for "incompilable" state please uncomment the \newpage \lipsum commands.
EDIT: MWE shows not "arithmetic overflow," but exceeding dimensions, which I hope is simillar. My orginal document shows "Arithmetic overflow" error.
EDIT2: Edited MWE to represent my issue, compiling MWE now brings error (at least on my side). Lowering ammount of pages (removing some "newpages" and "lipsum" makes MWE compilable again).
Thank you very much for any help in this, regards
Tomas
MWE:
\documentclass[12pt,twoside]{book}

\usepackage{lastpage}
\usepackage[lastpage]{zref}
\makeatletter
\zref@newprop*{numpage}{\the\value{page}}
\zref@addprop{main}{abspage}
\makeatother

\usepackage{refcount}
\setrefcountdefault{-1}

\usepackage{eso-pic}

\usepackage{lipsum}
\usepackage{tikz}
\usetikzlibrary{shapes,calc,positioning,shadows.blur,decorations.pathreplacing}

\newcommand{\nuclei}[1]{%
    \shade[ball color=white] (#1) circle (.4);
}

\newcommand{\nucleus}{%
    \nuclei{0.1,0.3}
    \nuclei{0,0}
    \nuclei{0.3,0.2}
    \nuclei{-0.2,0.1}
    \nuclei{-0.1,0.3}
    \nuclei{0.2,-0.15}
    \nuclei{-0.05,-0.12}
    \nuclei{0.17,0.21}
}

%\electron{xwidth,ywidth,rotation angle}
\newcommand{\electron}[3]{%
    \draw[rotate = #3](0,0) ellipse (#1 and #2)[color=blue];
    \shade[ball color=black] (0,#2)[rotate=#3] circle (.2);
}

\usepackage{changepage}
\strictpagecheck

\newcommand{\MyTikzLogo}{% For a logo drawn with TikZ
\begin{tikzpicture}[remember picture,overlay,scale=1]
\checkoddpage
\ifoddpage
  \begin{scope}[shift={([xshift=2cm,yshift=2cm]current page.south west)}, scale=0.25]
  \begin{scope}[rotate=360*\the\value{page}/\getpagerefnumber{LastPage}]
    \nucleus
  \end{scope}
    \electron{1.2}{1.4}{260+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{4}{2}{30+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{5}{1}{60+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{5.5}{1.5}{150+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{4.8}{2.25}{80+(360*\the\value{page}/\getpagerefnumber{LastPage})}
  \end{scope}
\else
  \begin{scope}[shift={([xshift=-2cm,yshift=2cm]current page.south east)}, scale=0.25,local bounding box=test]
  \begin{scope}[rotate=360*\the\value{page}/\getpagerefnumber{LastPage}]
    \nucleus
  \end{scope}
    \electron{1.2}{1.4}{260+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{4}{2}{30+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{5}{1}{60+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{5.5}{1.5}{150+(360*\the\value{page}/\getpagerefnumber{LastPage})}
    \electron{4.8}{2.25}{80+(360*\the\value{page}/\getpagerefnumber{LastPage})}
  \end{scope}
\fi
 \end{tikzpicture}
}

\AddToShipoutPictureBG{\MyTikzLogo}

\begin{document}
\section*{Lorem Ipsum}
\pagenumbering{roman}
\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\pagenumbering{arabic}

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\lipsum[1-60]

\newpage

\end{document}

A: Change everywhere (also in the rotate) the calculation order:
divide first and multiplicate later:
  360/\getpagerefnumber{LastPage}*\the\value{page}

This will avoid that the numbers gets too large - something that pgf can't handle very well as it uses internally dimensions.


text:
Q: Copy data from an excel and copy automaticly into one Web Form I have to register 100user manually into an external website. There is any way to copy the information, and when I paste into the web form, parse automatically into the form?

A: One way to do it is:

*

*Do one manual registration and then capture that HTTP Request. Use it as a template

*Export data from excel to csv. (just to make it easier to work on)

*Loop over each line of csv and create HTTP likely to be POST Request.

*Check for errors


text:
Q: perl6 grammar actions: unable to make anything if not using $/ I wrote a test program, and now it seems that if I don't use $/ in a
method signature because I have to use .match inside the method, I can no long make anything. What did I do wrong?
A further question is that if .match sets $/, and $/ is read-only, then I cannot have $/ in the signature of a method that contains a .match statement, and I cannot have more than one .match inside the method because each .match will try to set the read-only $/. This will be very awkward to program.
Here is the test program with only one .match statement inside and the results:
The test program:
grammar test {
    regex TOP   { <foo><bar> }
    regex foo   { :i \s* foo \s* }
    regex bar   { :i \s  bar \s* }
}

class actTest {
    method foo ($x) {              # program fails if I use $/ in signature
      print "1 "; say $x;          # how to combine the 2 and show $x as match?
      print "2 "; say $x.WHAT;
      my $newStr = $x.Str;
      print "3 "; say $newStr;
      my $newMatch
         = $newStr.match(/:i(f)(oo)/); # adverb cannot be outside?
      print "4 "; say $newMatch.WHAT;
      print "5 "; say $newMatch;
      print "6 "; say $/;
      my $oo = $newMatch[1].Str;
      print "10 "; say $oo;
      my $f = $newMatch[0].Str;
      print "11 "; say $f;
      my $result = $oo ~ $f;
      print "12 "; say $result;
      make $result;                # now I cannot make anything; huh???
    }
    method TOP ($/) {
      print "8 "; say $<bar>;
      print "9 "; say $<foo>.made; # failed, method 'foo' makes nothing
      make $<bar> ~ $<foo>.made;
    }
}

my $m = test.parse("Foo bar", actions => actTest.new);
print "7 "; say $m;

And the results:
1 「Foo 」
2 (Match)
3 Foo
4 (Match)
5 「Foo」
 0 => 「F」
 1 => 「oo」
6 「Foo」
 0 => 「F」
 1 => 「oo」
10 oo
 11 F
 12 ooF
1 「Foo」
2 (Match)
3 Foo
4 (Match)
5 「Foo」
 0 => 「F」
 1 => 「oo」
6 「Foo」
 0 => 「F」
 1 => 「oo」
10 oo
11 F
12 ooF
8 「 bar」
9 (Any)
Use of uninitialized value of type Any in string context.
Methods .^name, .perl, .gist, or .say can be used to stringify it to
something meaningful.
in method TOP at matchTest.pl line 28
7 「Foo bar」
 foo => 「Foo」
 bar => 「 bar」

A: 1) How to make without $/
make ... is just a shortcut for $/.make(...).
If you want to affect a different Match object than the one stored in $/, you have to use the method form directly, i.e. in your case $x.make($result).
2) When and why $/ is read-only
By default, $/ is bound to a normal item container (like a variable declared with my), i.e. not read-only. So there shouldn't be any problem with using the .match method multiple times in a routine.
It's only when you explicitly declare $/ as a parameter in a routine signature, that $/ will be bound directly to the Match object passed to that routine (not wrapped in an item container), and will thus be read-only inside the routine – because that's how normal signature binding works.
You could use the is copy trait to override the normal read-only parameter binding, and force $/ to be a mutable item container inside the routine:
method foo ($/ is copy) { ... }

This way, using .match inside the routine would work, and would store a new Match object in $/. But then you wouldn't have access to the original Match object passed to the routine anymore, and thus couldn't affect it with make. So for an action method that needs to use .match, using a custom parameter name like you did is the way to go.


text:
Q: How to generate 3D spherical sector I looked but haven't found an answer to this one: I'd like to create a region that represents a sector of a ball, bounded between radii $r_1$ and $r_2$, polar angles $\theta_1$ and $\theta_2$, and azimuthal angles $\varphi_1$ and $\varphi_2$. There seems to be no built-in functionality to achieve this directly. Do I have to assemble the region from parametric surfaces representing the spherical parts of the boundary, and trapezoids for the plane parts?

A: Definition of the region:
reg := (r1^2 <= x^2 + y^2 + z^2 <= r2^2 && (* conditions on radius *)
        θ1 <= ArcTan[z, Sqrt[x^2 + y^2]] <=  θ2 && (* conditions on polar angle *)
        φ1 <= ArcTan[x, y] <= φ2 (* conditions on azimuthal angle *)
        );

Definition of the parameters:
{r1, r2, θ1, θ2, φ1, φ2} = {2, 2.2, 30°, 180°, 15°, 85°};

Plots:
RegionPlot3D[ImplicitRegion[reg, {x, y, z}],
             PlotPoints -> 80, Boxed -> False, ViewAngle -> 20°]

RegionPlot3D[reg, {x, -2.5, 2.5}, {y, -2.5, 2.5}, {z, -2.5, 2.5}, Axes -> False,
             PlotPoints -> 80, Boxed -> False, ViewAngle -> 20°, Mesh -> None]

A: The NURBS representation of a spherical sector is particularly convenient, and has the advantage of not having to carry too many Polygon[] objects:
sphericalSegment[{r1_, r2_}, {θ1_, θ2_}, {φ1_, φ2_}] /; r1 < r2 :=
         Module[{cknots = {0, 0, 0, 1, 1, 1}, lknots = {0, 0, 1, 1},
                 θa = θ2 - θ1, φa = φ2 - φ1, a1, a2, cp, cθ, cφ, p1, p2, ws, wθ, wφ},
                cθ = Cos[θa/2]; cφ = Cos[φa/2];
                a1 = {Cos[θ1], Sin[θ1]}; a2 = {Cos[θ2], Sin[θ2]};
                p1 = {Sin[φ1] , Cos[φ1]}; p2 = {Sin[φ2], Cos[φ2]};
                cp = Map[Function[pt, Append[#1 pt, #2]],
                         {a1, Normalize[(a1 + a2)/2]/cθ, a2}] & @@@
                     {p1, Normalize[(p1 + p2)/2]/cφ, p2};
                ws = Outer[Times, {1, cφ, 1}, {1, cθ, 1}];
                wθ = Outer[Times, {1, 1}, {1, cθ, 1}];
                wφ = Outer[Times, {1, 1}, {1, cφ, 1}];
                {BSplineSurface[r1 Reverse[cp, 2], SplineDegree -> 2,
                                SplineKnots -> {cknots, cknots}, SplineWeights -> ws],
                 BSplineSurface[Outer[Times, {r1, r2}, cp[[1]], 1], SplineDegree -> {1, 2},
                                SplineKnots -> {lknots, cknots}, SplineWeights -> wθ],
                 BSplineSurface[Outer[Times, {r1, r2}, Reverse[cp[[All, 1]]], 1],
                                SplineDegree -> {1, 2}, SplineKnots -> {lknots, cknots},
                                SplineWeights -> wφ],
                 BSplineSurface[Outer[Times, {r1, r2}, cp[[All, -1]], 1],
                                SplineDegree -> {1, 2}, SplineKnots -> {lknots, cknots},
                                SplineWeights -> wφ],
                 BSplineSurface[Outer[Times, {r1, r2}, Reverse[cp[[-1]]], 1],
                                SplineDegree -> {1, 2}, SplineKnots -> {lknots, cknots},
                                SplineWeights -> wθ],
                 BSplineSurface[r2 cp, SplineDegree -> 2,
                                SplineKnots -> {cknots, cknots}, SplineWeights -> ws]}]

Some examples:
Graphics3D[{EdgeForm[], sphericalSegment[{9/10, 1}, {0, π/3}, {π/6, π/2}]}]

Graphics3D[{EdgeForm[], sphericalSegment[{9/10, 1}, {π/3, 3 π/4}, {π/2, π}]}]

A: sphericalSegment[{r1_, r2_}, {θ1_, θ2_}, {ϕ1_, ϕ2_}] :=
 Module[{plot, pts, surf, bdy},
  plot = ParametricPlot3D[{Cos[θ] Sin[ϕ], Sin[θ] Sin[ϕ], Cos[ϕ]},
    {θ, θ1, θ2}, {ϕ, ϕ1, ϕ2},
    Mesh -> None, BoundaryStyle -> Black];
  pts = First@Cases[plot, GraphicsComplex[p_, ___] :> p, Infinity];
  surf = First@Cases[plot, Polygon[p_] :> p, Infinity];
  bdy = First@Cases[plot, Line[p_] :> p, Infinity];
  GraphicsComplex[
   Join[r1*pts, r2*pts],
   {EdgeForm[],
    Polygon[surf], Polygon[Reverse /@ surf + Length@pts],
    Polygon[Join[#, Reverse@# + Length@pts],
       VertexNormals -> Cross[Subtract @@ pts[[#]], pts[[First@#]]]] & /@
     Partition[bdy, 2, 1, 1]},
   VertexNormals -> Join[-pts, pts]
   ]
  ]

Graphics3D[
 sphericalSegment[{0.95, 1.1}, {0, Pi/3}, {Pi/6, Pi/2}]
 ]


text:
Q: Python: Convert two columns of dataframe into one interposed list How can I convert two columns in a dataframe into an interposed list?
ex: I want to do something like
df
             Open  Close
Date
2016-12-23  1      2
2016-12-27  3      4
2016-12-28  5      6
2016-12-29  0      -1

someFunction(df)
>>> [1, 2, 3, 4, 5, 6, 0, -1]
Closest I've found is list(zip(df.Open, df.Close) but that returns a bunch of tuples in the list like this: [(1, 2), (3, 4), (5, 6), (0, -1)]

A: Try this:
df.values.flatten()
# array([ 1,  2,  3,  4,  5,  6,  0, -1])

A: IIUC
df.values.ravel().tolist()#df.to_numpy().ravel().tolist()

[1, 2, 3, 4, 5, 6, 0, -1]

A: How about:
df.stack().values
#array([ 1,  2,  3,  4,  5,  6,  0, -1])

A: You can obtain the values, and reshape it to a 1d array:
>>> df[['Open', 'Close']].values.reshape(-1)
array([ 1,  2,  3,  4,  5,  6,  0, -1])

or convert that to a list:
>>> list(df[['Open', 'Close']].values.reshape(-1))
[1, 2, 3, 4, 5, 6, 0, -1]

A: You could use a list comprehension in combination with df.values:
[y for x in df.values for y in x]
[1, 2, 3, 4, 5, 6, 0, -1]

x will be an array with the rows, and y will be the values in those rows


text:
Q: Pseudo Element with React Styled Components I've looked up several answers, and feel like I'm setting this up the exact same way, yet it's not working.
The index.css of my document sets up a gradient background, that works perfectly. Then I have my footer, and that is also working.  But the issue comes where I want to add an SVG as a background to the footer, and set the opacity on it.
If I do this, the background image appears, but the entire footer is affected by the opacity, which of course is a bad result.
const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;
    background-image: url('/logo.svg');
    opacity: 0.25;
}
`

But if I do this, which seems to be to be how it's supposed to work if I want just the background image semi-transparent while the rest of the footer stays opaque, then the background image does not show at all:
const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;

     &::before {
    content: "";
    background-image: url('/logo.svg');
    position: absolute;
    opacity: 0.25;
    }
}
`

How should I set this up so that the background image is semi-transparent, but the rest of the footer is not?
Here is my footer JSX if that helps:
<Foot id="footer-page">

HUMAN RESOURCES SOLUTIONS>

FOLLOW US ON SOCIAL MEDIA

                </Foot>

A: It looks like you need to use a single colon (:) where you use the &::before pseudo-selector.
Also, if that doesn't work you could try using the after pseudo-selector.
const Foot = styled.footer `
    position: relative;
    margin: 0px;
    padding-top: 2em;
    padding-left: 0em;
    padding-right: 0em;
    padding-bottom: 2em;
    color: white;

    &:before {
      content: "";
      background-image: url('/logo.svg');
      position: absolute;
      opacity: 0.25;
    }
}


text:
Q: What is the range on a fourier transform? In particular, I want to know the range of the coefficients on the type-IV discrete cosine transform. Assuming no normalization factor or window is applied, what interval can I expect the coefficients to reside on?
I realize this is a fairly simple question, but unfortunately, Google has yielded no answers.


text:
Q: Displaying Results In My View In A  From My Foreach In My Code Behind I am using a stored proc to get all the enteries of my 'Places' column and i want to display the results in a
 on my site but i'm struggling.
I've got the Foreach working and it returns all my enteries but when i try displaying my results, it only shows my last one.
I've never written a Foreach before to display my results.
Code Behind
namespace PaydayLunchGenerator
{
    public partial class _Default : Page
    {
        public string PlaceABC;

        protected void Page_Load(object sender, EventArgs e)
        {
            string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
            SqlConnection conn = new SqlConnection(connection);

            using (SqlCommand cmd = new SqlCommand("dbo.GetPlaces", conn))
            {
                try
                {
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        PlaceABC = reader.GetValue(1).ToString();
                    }
                    reader.Close();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}

Code i tried in my view
<% foreach (var ABC in PlaceABC)
{ %>

<%= PlaceABC %>

<%} %>

I'll be honest and i have no idea on how to write it so i took a guess at my view's foreach. All the data is provided from my code behind.

A: Make sure your PlaceABC is a List instead of a string, so change this:
public string PlaceABC to public List<string> PlaceABC = new List<string>();
then change
while (reader.Read())
      {
          PlaceABC = reader.GetValue(1).ToString();
      }

to this:
   while (reader.Read())
      {
          PlaceABC.Add(reader.GetValue(1).ToString());
      }

and in your view:
<% foreach (var ABC in PlaceABC)
{ %>

<%= PlaceABC %>

<%} %>

should be
<% foreach (var ABC in PlaceABC)
{ %>

<%= ABC %>

<%} %>


text:
Q: IllegalStateException Score Corruption after solver config change My local search part in solver config looks like:
<acceptor>
    <lateAcceptanceSize>400</lateAcceptanceSize>
    <entityTabuSize>9</entityTabuSize>
</acceptor>
<forager>
    <acceptedCountLimit>2000</acceptedCountLimit>
</forager>

and everything works fine but when I change it to(what can cause optimization gain I think):
<acceptor>
<lateAcceptanceSize>600</lateAcceptanceSize>
</acceptor>
<forager>
<acceptedCountLimit>4</acceptedCountLimit>
</forager>

After solver starts working I got exception
Score corruption: the solution's score (-20hard/-8medium/-4soft) is not the uncorruptedScore (-20hard/-8medium/-8soft)

What can cause this problem? (It is only information from FULL_ASSERT mode)
EDIT:
Something can be connected to rule:
// Boundary lessons have to be schedulead at the beginning/end in a day
rule "boundaryLesson"
    when
        $oddzial : Oddzial()
        $boundaryLesson : Lesson(scheduled == true, containsOddzial($oddzial), base.lessonLimits.isBoundaryLesson == true, $base : base)
        exists Lesson(scheduled == true, containsOddzial($oddzial), dayLessonNumber.day == $base.day, base.lessonNumberFrom < $base.lessonNumberFrom)
        and exists Lesson(scheduled == true, containsOddzial($oddzial), dayLessonNumber.day == $base.day, base.lessonNumberTo > $base.lessonNumberTo)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

because, sometimes I get following error also:
Score corruption: the workingScore (0hard/-2medium/0soft) is not the uncorruptedScore (-1hard/-2medium/0soft) after completedAction (8848-537:Tuesday-3 {com.pbz.plek.model.simple.DayLessonNr@5924af87 -> com.pbz.plek.model.simple.DayLessonNr@5924af87}):
  The corrupted scoreDirector has no ConstraintMatch(s) which are in excess.
  The corrupted scoreDirector has 1 ConstraintMatch(s) which are missing:
    com.praca.mgr.cp.algorytm.solver/boundaryLesson/level0/[8854-537:Tuesday-2, com.krakfin.pbz.plek.model.simple.Oddzial@c9d4]=-1
  Check your score constraints.

I know how incremental score calculation works but I cannot see what can be wrong with this rule

A: In both cases you'll have potential score corruption, but only in the second case it surfaces. For production reliability, you'll definitely want to fix it.
See docs on "incremental score calculation" to understand what score corruption is. Usual causes:

*

*Shadow variable corruption. Use OptaPlanner 6.3.0.Final or later and it will show up as "VariableListener corruption" instead of "Score corruption" and provide more info.

*A bad custom Move due to a bad undo move. Normally this will show up as "Undo Move corruption" instead of "Score corruption".

*A bad custom Move that acts different the second time it's done on the same solution state. This will be detected during processWorkingSolutionDuringStep().

If you use Drools calculation:

*

*A bad score rule that causes "Score corruption". As of OptaPlanner 6.1 this is unlikely, because it's much harder to write a bad score rule. Try commenting out score rules to figure out which one is to blame.

*A bug in Drools. Unlikely, but possible. Create a dedicated reproducer and submit a jira.

If you use incremental score calculation:

*

*A bad Java Incremental score calculator. Use <assertScoreDirectorFactor> with an easy score calculator too. Good luck in this case.

A: To sum up:

*

*I am using OptaPlanner 6.3.0.Final with FullAssert environment mode

*I removed custom move to exclude possibility of bugs in that section

*There are two plannig variables: Sala(Room) and DzienNrLekcji(Object consists day and lesson number)

*There aren't any shadow variables

*Problems with corrupted score exists at every score level so I left
only hard constraints rules section, which looks like that:
// ############################################################################
    // Hard constraints
    // ############################################################################
// two Lessons at the same time should be in another rooms.
rule "salaOccupancy"
    when
            $leftLesson : Lesson($id : base.numericId, scheduled == true, $sala : sala)
            not Lesson(scheduled == true, timeCollision($leftLesson), sala == $sala, base.numericId < $id)
            $rightLesson : Lesson(scheduled == true, timeCollision($leftLesson), sala == $sala, base.numericId > $id)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -10);
end

// each oddzial and nauczyciel can't have two lessons at the same time
rule "przydzialCollision"
    when
           $przydzialConflict : PrzydzialConflict($leftPrzydzial : leftPrzydzial, $rightPrzydzial : rightPrzydzial)
           $leftLesson : Lesson(scheduled == true, base.przydzial == $leftPrzydzial)
           $rightLesson : Lesson(scheduled == true, base.przydzial == $rightPrzydzial, timeCollision($leftLesson), this != $leftLesson)
        then
            scoreHolder.addHardConstraintMatch(kcontext, -2 * $przydzialConflict.getConflictCount());
end

// sala's capacity shouldn't be exceeded
rule "salaCapacity"
    when
        $sala : Sala($capacity : ograniczenia.maxLiczbaUczniow.max)
        $lesson : Lesson(scheduled == true, sala == $sala)
        $limit : LessonStudentLimit(lesson == $lesson, numberOfStudents > $capacity)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -2);
end

// cannot put lesson into not available time period in Sala or Przydzial
rule "availability"
    when
        Lesson( scheduled == true , dostepnaSala == false )
        or Lesson( scheduled == true , dostepnyPrzydzial == false)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -2);
end

// Oddzials cannot have gaps between classes during a day
rule "gaps"
    when
        $oddzial : Oddzial()
        $dzien : DzienTygodnia()
        $lessonList : ArrayList(LessonBlockCounter.calculateOddzialGaps($lessonList,TimetableSolution.maxLessonNr)>0) from collect (
            Lesson(scheduled == true, containsOddzial($oddzial), dzienNrLekcji.dzien == $dzien)
        )
    then
        scoreHolder.addHardConstraintMatch(kcontext, -5*LessonBlockCounter.calculateOddzialGaps($lessonList,TimetableSolution.maxLessonNr));
end

// If Przydzial has blocks distribution defined, only one lesson per day is allowed
rule "blocks"
    when
        $przydzial : Przydzial( ograniczenia.ograniczeniaBlokiLekcyjnePrzydzialu.czyTylkoJednaLekcjaNaDzien.isAktywne() == true )
        $dzien : DzienTygodnia()
        $lessonCount : Number( intValue > 1 ) from accumulate (
            $lesson : Lesson(scheduled == true, base.przydzial == $przydzial,dzienNrLekcji.dzien == $dzien),
            count($lesson)
        )
    then
        scoreHolder.addHardConstraintMatch(kcontext, -2);
end

// Boundary lessons have to be schedulead at the beginning/end in a day
rule "boundaryLesson"
    when
        $oddzial : Oddzial()
        $boundaryLesson : Lesson(scheduled == true, containsOddzial($oddzial), base.ograniczeniaLekcja.czyLekcjaGraniczna.aktywne == true, $base : base)
        exists Lesson(scheduled == true, containsOddzial($oddzial), dzienNrLekcji.dzien == $base.dzien, base.lekcjaNrOd < $base.lekcjaNrOd)
        and exists Lesson(scheduled == true, containsOddzial($oddzial), dzienNrLekcji.dzien == $base.dzien, base.lekcjaNrDo > $base.lekcjaNrDo)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -1);
end

// Linked lessons have to take place at the same time
rule "linkedLesson"
    when
        $linkedLesson : Lesson(scheduled == true, base.ograniczeniaLekcja.lekcjePolaczone.empty == false, $dzienNrLekcji : dzienNrLekcji)
        Lesson(scheduled == true, base.ograniczeniaLekcja.lekcjePolaczone contains $linkedLesson.base, dzienNrLekcji != $dzienNrLekcji)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -5);
end

// Linked lessons have to take place at the same time
rule "scheduledLinkedLesson"
    when
        $linkedLesson : Lesson(scheduled == false, base.ograniczeniaLekcja.lekcjePolaczone.empty == false)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -10*$linkedLesson.getBase().getCzasTrwania());
end

// Lessons have to be placed in the school time boundaries
rule "schoolTime"
    when
        $lesson : Lesson(scheduled == true, base.czasTrwania > 1 , base.lekcjaNrOd > TimetableSolution.maxLessonNr - base.czasTrwania)
    then
        scoreHolder.addHardConstraintMatch(kcontext, -5);
end

// Lessons have to be scheduled in one of the preferred sala
rule "assignedSalaPrzydzialu"
    when
        $lesson : Lesson( scheduled == true,
        sala not memberOf base.przydzial.ograniczenia.perferowaneSale.preferowaneSale.saleList )
    then
       scoreHolder.addHardConstraintMatch(kcontext, -1);
end

// ############################################################################
// Medium constraints
// ############################################################################

//lesson have to have sala and day assigned, not assigned lessons are acceptable in overconstrained problem
rule "scheduledLesson"
    when
        $lesson : Lesson( scheduled == false )
    then
        scoreHolder.addMediumConstraintMatch(kcontext, -$lesson.getBase().getCzasTrwania());
end

After running algorithm, I'am getting exception:
2015-11-04 10:39:21,493 [http-8080-3] INFO  org.optaplanner.core.impl.solver.DefaultSolver - Solving started: time spent (426), best score (uninitialized/-160hard/-165medium/0soft), environment mode (FULL_ASSERT), random (JDK with seed 0).
2015-11-04 10:39:23,969 [http-8080-3] INFO  org.optaplanner.core.impl.constructionheuristic.DefaultConstructionHeuristicPhase - Construction Heuristic phase (0) ended: step total (165), time spent (2903), best score (-160hard/-165medium/0soft).
2015-11-04 10:39:24,615 [http-8080-3] ERROR org.apache.struts2.dispatcher.Dispatcher - Exception occurred during processing request: Score corruption: the solution's score (-123hard/-161medium/0soft) is not the uncorruptedScore (-126hard/-160medium/0soft).
java.lang.IllegalStateException: Score corruption: the solution's score (-123hard/-161medium/0soft) is not the uncorruptedScore (-126hard/-160medium/0soft).
    at org.optaplanner.core.impl.score.director.AbstractScoreDirectorFactory.assertScoreFromScratch(AbstractScoreDirectorFactory.java:100)
    at org.optaplanner.core.impl.solver.scope.DefaultSolverScope.assertScoreFromScratch(DefaultSolverScope.java:127)
    at org.optaplanner.core.impl.solver.recaller.BestSolutionRecaller.processWorkingSolutionDuringStep(BestSolutionRecaller.java:107)
    ...

After studied problem I am pretty sure that it's connected with incremental score calculation and drl file. I thought that problem causes "gaps" rule because "calulateOddzialGaps" method checks day and lesson number of collected $lessonList, but after commented this rule problem still exists. Any other rule doesn't use lessons(planningEntity) at WHEN section inside java method. What can be wrong? I don't have any other ideas...


text:
Q: Respect sorting of original language in TYPO3 Frontend (like defLangBinding) I have some messed up values for tt_content.sorting in TYPO3 6.2 for translated records (sys_language_uid=1).
That means that styles.content.get displays the right order (as visible in the backend) in the original language, but not in the translated language (where in the backend everything looks fine, as it follows defLangBinding but in the frontend, the wrong values from the sorting fields are used, so the sorting is messed up.
We did modify some settings in the last few weeks
  // before
  // config.sys_language_mode = content_fallback:1,0
  // config.sys_language_overlay = hideNonTranslated

  // currently
  config.sys_language_mode = strict
  config.sys_language_overlay =0

but I am unsure if that is connected. The sorting in the DB is really wrong for some fields. It is correctable by moving individual CEs in Page or List module.
There are many related ancient bugs on forge.
My questions:

*

*Is there a script that fixes the sorting for the translated CEs for the entire site in accordance to the main language?

*Is there something like defLangBinding for the frontend - that would help as well, as the wrong sorting values would become meaningless. Or a modification for the styles.content.get query?

A: Why don't you just try to bring your content records in sync again? This could be done by pure SQL if there are no or only a few exclusive records in the second language. If not, you are going to mess it up even more.
This query will give you a table with the default language and the translated record side by side, including the sorting value:
select a.header, a.uid, a.sorting, b.sorting, b.uid, b.header from tt_content as a inner join tt_content as b on a.uid=b.l18n_parent where b.l18n_parent > 0 and a.sys_language_uid = 0 and not a.deleted and not b.deleted;

You could then adapt this query to an update query that sets the sorting value of table b to the one in table a.
To check if you have records without a parent in the default language, you can use this query:
select * from tt_content where sys_language_uid > 0 AND l18n_parent = 0 AND NOT deleted

As for your configuration, have a look at the manual for sys_language_overlay:

If set, records from certain tables selected by the CONTENT cObject
  using the "languageField" setting will select the default language (0)
  instead of any language set by sys_language_uid / sys_language_mode.
  In addition the system will look for a translation of the selected
  record and overlay configured fields.

So this seems to be connected to your problem: Before, TYPO3 was (maybe - you didn't post the setting for sys_language_overlay) configured to first fetch records in the default language, try to overlay them with a translation and then output it.
Now that sys_language_overlay is deactivated, the records are fetched in the translated version right away and their sorting is considered.


text:
Q: Firebase how to remove key pushing element I got database
When I add new user tree using push(), a key appears as a parent. And then I have to get user data, but this key interfere. How can I rename this element of tree or get username through the key or replace this part without key or use not the push() but something else that don't create key parent or maybe I can get necessary key using currentUser

A: I just recieved it, it was easier than I thought
app.database().ref('users/').child(newName).set(newUser)


text:
Q: Java shift operator don't works the same with a pre saved value than with the direct value This comes up after solve the problem:
https://www.hackerrank.com/challenges/flipping-bits/problem?h_l=interview&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=miscellaneous
My solution is:
static long flippingBits(long n) {
    long l=0;                       //Have to pre-declare 0, Why?
    return (~l>>>32)&~n;
}

But what I wanted to do is use the 0 direct into the return statement instead of declaring it before in "long l", like this:
static long flippingBits(long n) {
    return (~0>>>32)&~n;            //Using 0 directly don't works.
}

I also tried with parenthesis but is the same. After testing looks like it is not able to shift if I put the 0 directly.
Why is giving me a different value?

A: This should be a fairly easy fix.
return (~0>>>32)&~n;: the zero is interpreted as of type int.
To tell the program it's of type long, write the following:
return (~0L>>>32)&~n;

A: On a related note, shorts and bytes are treated similarly.
byte b =-16; // 1111000
b = (byte)(b>>>1);
System.out.println(b); //prints -8 and not 120

ANDing with 0xFF solves the problem
b = -16;
b = (byte)((b&0xFF)>>1);
System.out.println(b); // prints 120 as expected.

The reason is that b is converted to an int first and then shifted.
On a different note, if n is a long, why did you not just use ~n to flip bits since that is all that is needed?


text:
Q: CS0246 visual studio community edition 2015 missing reference? I have a "windows 10 pro" and a fresh install of "visual studio community edition 2015" installed.
I do a new project console application and call it ftptest
then copy and paste the code from here:
https://msdn.microsoft.com/en-us/library/ms229716%28v=vs.110%29.aspx
using System;
using System.IO;
using System.Net;

namespace ftpcheck
{
    public class Program
    {
        public void Main(string[] args)
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            Console.WriteLine(reader.ReadToEnd());

            Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

            reader.Close();
            response.Close();
        }
    }
}

And try to build it just to see what it does.
I get a lot of:

CS0246 The type or namespace name 'FtpWebRequest' could not be found
(are you missing a using directive or an assembly reference?)
CS0246    The type or namespace name 'NetworkCredential' could not be
found (are you missing a using directive or an assembly reference?)

How can i add that missing reference?

A: answered with a comment by hans passant:
My crystal ball says that you are using the wrong project template to get started. Use Visual C# > Windows > Classic Desktop > Console Application. And you somehow lost the static keyword on the Main() method. – Hans Passant Nov 26 '15 at 20:48

A: If you take a look on msdn, you will see the reference that you have to add:
https://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.110).aspx
Namespace:   System.Net
Assembly:  System (in System.dll)

A: include:  using System.Net; in your references section


text:
Q: Photocapture device Camera Hangs in Windows Phone 8 I am developing an application in Windows Phone 8. Basically in my application, i use PhotoCaptureDevice API for taking snaps and scanning Barcodes. When I go forth and come back to camera page continuously using hardware back button sometimes camera page hangs and unable to proceed further.
The code snippet used is :

//Passing Videobrush to PhotoCapturedevice

VideoBrush brush;

brush.SetSource(_device);

//PhotoCapture Device Intialization

internal PhotoCaptureDevice _device;

CameraSensorLocation cameraLocation;

    if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Back))
    {
          var supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back);
          _initRes = GetBestResolution(supportedResolutions);
           cameraLocation = CameraSensorLocation.Back;

     }
     else if (PhotoCaptureDevice.AvailableSensorLocations.Contains(CameraSensorLocation.Front))
     {
           var supportedResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Front);
           _initRes = GetBestResolution(supportedResolutions);
            cameraLocation = CameraSensorLocation.Front;

     }

Could you please help me on this

A: You must initialize the photocapture object before calling brush.SetSource(_device);


text:
Q: JUnit testing SQL queries I'm working on a project and we are required to create some test cases. I have a SQL database and parsing data there with queries like:
public Contractor create(String name, String address, String email, String phone, String city, int cvr) throws SQLException{
    Contractor contractor = new Contractor(name, address, email, phone, city, cvr);
    String sql = String.format("INSERT INTO person (name, address, email, phone, city, category) VALUES ('%s', '%s', '%s', '%s', '%s', 2)", name, address, email, phone, city);
    try{
        Connection conn = DBConnection.getInstance().getDBcon();
        conn.createStatement().executeUpdate(sql);

        String sql2 = "SELECT TOP 1 id FROM Person ORDER BY id DESC";
        ResultSet rs = conn.createStatement().executeQuery(sql2);

        if(rs.next()) {
            String sql3 = "INSERT INTO contractor (cvr, person_id) VALUES (2666,"+rs.getInt("id")+")";
            conn.createStatement().executeUpdate(sql3);
        }else{
            throw new SQLException();
        }

    } catch (SQLException e){
        e.printStackTrace();
    } finally {
        DBConnection.closeConnection();
    }
    return contractor;
}

How would the test with JUnits look like?

A: Well, the way Junit must be used is by testing each public method of your class, with as many different parametrizations as the number of experiments can success or fail.
Each testing method, then, must:

*

*Chose a proper set of parameter values.

*(Optionally) Initialize the tested component in a required initial state.

*Invoke the tested method.

*Check that the returned result is equal to the expected result.

*Clean up the tested component not to let any "dirt" from the executed test.

In your case, there is a difficult checking the results, because the connection is managed locally by your method. Even worse: The data is committed automatically into the connection, leaving dirty records in the database on each test.
To avoid this difficult, it would be enough with a little previous refactoring to ease the test development:

*

*Overload in your class the method create, with a package-access version which recieves also a Connection, and put there all the business logic.

*The public overload should only manage the connection and call the newly created overload.

Then, you can make your test safely:

*

*If your class is named MyClass, create a MyClassTest in the same package (typically in a different source path, like src\test\java in a Maven project).

*Create a method createSinglePerson() which invokes create with an arbitrary set of parameters and one connection (not auto-commit). After that, you must check that there is one record more than initially in the Person table, with a certain set of values, and one more record in the Contractor table with a certain set of values. To compare each value you must use Asserts.assertEquals(expected, real). At the end (in a finally clause), do a rollback to the connection and close it.

You can run your test as many times as needed, knowing that it won't alter the database state.
(Note: Parameter cvr is never used. Maybe you did it on purpose, I don't know).
Example
public class MyClassTest
{
    @Test
    public void createSinglePerson()
    {
        MyClass myClass=new MyClass();
        try(Connection connection=...)
        {
            try(Statement stCheck=connection.createStatement())
            {
                connection.setAutoCommit(false);

                // Initial cleanup:
                stCheck.executeUpdate("DELETE FROM person");
                stCheck.executeUpdate("DELETE FROM contractor");

                // Setting input parameters:
                String name="a";
                String address="b";
                String email="c@d.e";
                String phone="001";
                String city="f";
                int cvr=11;

                // Do the call:
                Contractor contractor=myClass.create(name, address, email, phone, city, cvr);

                // Javabean Checks: Check the javabean contains the expected values:
                assertEquals(name, contractor.getName());
                assertEquals(address, contractor.getAddress());
                ...

                // Database Checks:
                int personId;
                // Check the Person table contains one row with the expected values:
                try(ResultSet rs=stCheck.executeQuery("SELECT * FROM person"))
                {
                    assertTrue(rs.next());
                    personId=rs.getInt("id");
                    asssertEquals(name, rs.getString("name"));
                    asssertEquals(address, rs.getString("address"));
                    ...
                    assertFalse(rs.next());
                }

                // Check the Contractor table contains one row with the expected values:
                try(ResultSet rs=stCheck.executeQuery("SELECT * FROM contractor WHERE person_id="+personId))
                {
                    assertTrue(rs.next());
                    asssertEquals(2666, rs.getInt("cvr"));
                    ...
                    assertFalse(rs.next());
                }
            }
            finally
            {
                 // Undo the testing operations:
                 connection.rollback();
            }
        }
        catch (SQLException e)
        {
            fail(e.toString());
        }
    }
}


text:
Q: Correct tile movement for a 2048 game I decided to make a 2048 Command Line Edition but I'm having trouble getting the right tile movement...
My current structure is that the board is a 2D array (4x4) of ints. When an input is received, it will try to push every tile in that direction (ignoring tiles with value 0), if it notices a change it will start over (Because a tile on the bottom row will have to go all the way up, not just one step up). However, a side effect of this is the following problem:
[2][2][4] with the command -> should give [0][4][4] but since it starts over, the program will be able to merge 4 and 4 and get a [0][0][8] intead...
Another difficult problem is the [4][4][8][8] which should give [0][0][8][16] so I can't just stop after a merge.
The code below is my processCommand function. It takes a board and an input (which is "d", "u", "l", or "r". If the game notices gameover it will put "gameover" as input). It's not very pretty and I've tried to make a single for loop for moving tiles (Like if you write "l" a value horiz will be -1 and if you write "r" it will be 1 and then I move the tile horiz spots horizontal but I couldn't make that work).
Any ideas on how to do this (and critique on my programming) would be greatly appreciated!
func processCommand(board [][]int, input string) {

board_new := board

switch input {
    case "d":
        for i := 0; i < height - 1; i++ {
            for j := 0; j < width; j++ {

                if board[i][j] == 0 {
                    continue
                }

                if board[i + 1][j] == 0 || board[i + 1][j] == board[i][j] {
                    board_new[i + 1][j] = board[i + 1][j] + board[i][j]
                    board_new[i][j] = 0
                    i = 0
                    j = 0
                    change = true
                }
            }
        }

    case "u":
        for i := 1; i < height; i++ {
            for j := 0; j < width; j++ {

                if board[i][j] == 0 {
                    continue
                }

                if board[i - 1][j] == 0 || board[i - 1][j] == board[i][j] {
                    board_new[i - 1][j] = board[i - 1][j] + board[i][j]
                    board_new[i][j] = 0
                    i = 1
                    j = 0
                    change = true
                }
            }
        }

    case "l":
        for i := 0; i < height; i++ {
            for j := 1; j < width; j++ {

                if board[i][j] == 0 {
                    continue
                }

                if board[i][j - 1] == 0 || board[i][j - 1] == board[i][j] {
                    board_new[i][j - 1] = board[i][j - 1] + board[i][j]
                    board_new[i][j] = 0
                    i = 0
                    j = 1
                    change = true
                }
            }
        }

    case "r":
        for i := 0; i < height; i++ {
            for j := 0; j < width - 1; j++ {

                if board[i][j] == 0 {
                    continue
                }

                if board[i][j + 1] == 0 || board[i][j + 1] == board[i][j] {
                    board_new[i][j + 1] = board[i][j + 1] + board[i][j]
                    board_new[i][j] = 0
                    i = 0
                    j = 0
                    change = true
                }
            }
        }

    case "gameover":
        gameOver = true

    default:
        processCommand(board, input)
}

board = board_new

}

A: First your merging problem
Currently you're always scanning your tiles top-to-bottom and left-to-right, independently of the player's move. For 2048, however, it is preferable to scan in the opposite direction of the player's move, since tiles will only be merged in that direction. For example, let's take the following scenario:
0   0   2   0   |
0   0   2   2   | Player move
0   2   4   8   v
2   32  4   2

Let's assume the player's move direction is towards the bottom, so we start scanning from the bottom towards the top. In the third column, we'd need to first merge 4+4 and then 2+2, i.e. bottom-to-top. Going in that direction allows you to merge 4+4 and then mark the bottom-most field of the column as merged, thus not allowing further merges (indicated by the parentheses around the number):
0   0   0   0   |
0   0   2   2   | Player move
0   2   2   8   v
2   32  (8) 2

After merging the bottom-most cells (if possible), we proceed with the cells above and so on...
0   0   0   0   |
0   0   0   2   | Player move
0   2   (4) 8   v
2   32  (8) 2

[...]

0   0   (0) 0   |
0   0   (0) 2   | Player move
0   2   (4) 8   v
2   32  (8) 2

When no more merges are possible the move ends and all "merged" markers are removed and we wait for the next turn. This approach fixes your multiple-merge problem.
Another example for the scan direction (numbers now represent how a loop would run through the fields):
Player move
    ---->
4   3   2   1
8   7   6   5
12  11  10  9
16  15  14  13

About your code
Looking at the code, one notices that there is lots of code duplication regarding your loops. For each case you do a separate nested for-loop, which is not really optimal. Instead, you might be able to do something like this:
for i := 1; i < height; i++ {
    for j := 0; j < width; j++ {
        if board[i][j] == 0 {
            continue
        }

        switch input {
            case "d":
                updateBoardDown(board, i, j)
            case "u":
                updateBoardUp(board, i, j)

            [...]
        }
    }
}


text:
Q: convert JSON to excel file using javascript and to apply filters on each column before exporting the file I was going through the possibilities of converting the json into an excel.
I came across this post in stack overflow which was very helpful
how to export json data to excel file using javascript?
Now, I want to improvise on this, along with the coversion to .csv file i wnat it to have filters to the columns.
Is there any way to do this??


text:
Q: Yii, joining 2 dropdown lists into 1 So basically I have 2 different drop down lists, for example, A has 10 options and B has 10 options.
How can I have them both in 1 single drop down? For example, the top 10 options from A and the bottom 10 from B?
The below is the drop down A:
    <?php echo $form->labelEx($model,'clientPackagedService_id'); ?>
    <?php $client = Client::model()->findByPk(1);?>
    <?php echo $form->dropDownList($model, 'clientPackagedService_id', CHtml::listData($client->clientPackagedservices(array('condition'=>'client_id='.$client->id.' AND booking_id IS NULL')),'id','packagedServiceInfo'),
        array('disabled'=>'disabled', 'prompt'=>'Select Packaged Service...')
    ); ?>
    <?php echo $form->error($model,'clientPackagedService_id'); ?>

The below is the drop down B:
    <?php echo $form->labelEx($model,'service_id'); ?>
    <?php echo $form->dropDownList($model, 'service_id',  GxHtml::listDataEx(Service::model()->findAllAttributes(null, true)),
        //array( 'prompt'=>'Select Service...')
        array( //
                    //'disabled'=>$disabledValue, //
                    'enabled'=>true,
                    'prompt' => 'Select service...',
                    'ajax' => array( 'type'=>'POST', //request type
                        'url'=>CController::createUrl('updateMasseuseAndStationListSID'), //url to call.
                        'data'=>array('service_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
                        'dataType'=>'json',
                        'success'=>'js:function(data) {
                            //alert(data.masseuse);
                            var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
                            $(mass).html(data.masseuse);
                            $(mass).trigger("chosen:updated");
                            $(mass+"_chzn").css("width","300px");
                            $(mass+"_chzn > .chzn-drop").css("width","298px");

                            var station="#'.CHtml::activeId($model, 'station_id').'";
                            $(station).html(data.station);
                            $(station).trigger("chosen:updated");
                            $(station+"_chzn").css("width","300px");
                            $(station+"_chzn > .chzn-drop").css("width","298px");

                            //alert(data.timeEnd);
                            var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
                            $(timeEnd).val(data.timeEnd);

                        }',
                    )
    )); ?>
    <?php echo $form->error($model,'service_id'); ?>

How can I join them both and then remain the same operation of Ajax?
Please advise. Thanks in advance.

A: Combine result of clientPackagedservices() with Service::model()->findAllAttributes() inside your controller and then pass it to the view file


text:
Q: Some problems while I am building tensorflow I cannot build tensorflow on my system. My configuration:
system:ubuntu16.04
cuda:gtx1070
cudnn:6.0
cuda:8.0
tensorflow version:1.3.1
python:3.5.3(install in the workspace of pyenv)
bazel version:0.5.2
gcc version:5.4.0

When I run:
./configure
bazel build --config-opt --config-cuda //tensorflow/tools/pip_package:build_pip_package --verbose_failures

then it crashes with missing crosstool_wrapper_driver_is_not_gcc file in the cuda repository:

The content of generated .tf_configure_bazelrc is:
build --action_env PYTHON_BIN_PATH="/root/.pyenv/shims/python"
build --action_env PYTHON_LIB_PATH="/root/.pyenv/versions/3.5.3/lib/python3.5/site-packages"
build --define PYTHON_BIN_PATH="/root/.pyenv/shims/python"
build --define PYTHON_LIB_PATH="/root/.pyenv/versions/3.5.3/lib/python3.5/site-packages"
build --force_python=py3
build --host_force_python=py3
build --python3_path="/root/.pyenv/shims/python"
test --force_python=py3
test --host_force_python=py3
test --define PYTHON_BIN_PATH="/root/.pyenv/shims/python"
test --define PYTHON_LIB_PATH="/root/.pyenv/versions/3.5.3/lib/python3.5/site-packages"
run --define PYTHON_BIN_PATH="/root/.pyenv/shims/python"
run --define PYTHON_LIB_PATH="/root/.pyenv/versions/3.5.3/lib/python3.5/site-packages"
build --define with_jemalloc=true
build:opt --cxxopt=-march=native --copt=-march=native
build --action_env TF_NEED_CUDA="1"
build --action_env TF_NEED_OPENCL="0"
build --action_env TF_CUDA_CLANG="0"
build --action_env CUDA_TOOLKIT_PATH="/usr/local/cuda"
build --action_env TF_CUDA_VERSION="8.0"
build --action_env GCC_HOST_COMPILER_PATH="/usr/bin/gcc"
build --action_env TF_CUDNN_VERSION="6"
build --action_env CUDNN_INSTALL_PATH="/usr/local/cuda-8.0"
build --action_env TF_CUDNN_VERSION="6"
build --action_env TF_CUDA_COMPUTE_CAPABILITIES="6.1"
build --config=cuda
test --config=cuda

A: It's complaining that it cannot find crosstool_wrapper_driver_is_not_gcc
 file, which is a wrapper for C++ complier. I'd try updating bazel to version 0.6.0. Can you rerun with --sandbox_debug, and ideally manually inspect the generated sandbox directory if it contains crosstool_wrapper_driver_is_not_gcc, if permissions are set correctly, and if you can manually  execute the command that bazel is trying to execute.


text:
Q: Django DRF login only superuser I want to implement login with Django drf.
I want only superuser (is_staff permission in my user model) to be able to log in.
Until now I used rest_framework_simplejwt for generating a token for every user that trying to log in.
How can I implement that only superuser will be able to log in?
Views.py: calling the serializer
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer

Serializer.py:
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
    user = CustomUser.objects.get(email=user.email)
    print(colored(user, "yellow"))
    token = super().get_token(user)
    # Add custom claims
    token['username'] = user.clinic_name
    token['email'] = user.email
    # ...
    return token

In serializer.py when I'm trying to retrieve user  user = CustomUser.objects.get(email=user.email) I get only the email filed back.
I'm using email to retrieve user because email is a unique field.
urls.py:
urlpatterns = [
path('token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('register/', views.ClinicRegistration, name='auth_register'),
path('users/', views.ClinicListView.as_view(), name='users_list'),
path('users/<pk>/', views.ClinicDetailView.as_view(), name='get_user'),
path('users/<pk>/update/', views.ClinicUpdate, name='update_user'),
path('users/<pk>/delete/', views.ClinicDeleteView.as_view(), name='delete_user'),
path('', views.getRoutes),
path('test/', views.testEndPoint, name='test')

]
In the frontend I'm using react I make an Axios.post request with the: username, password, and email fields.
This is my CustomUserModel:
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = None
email = models.EmailField(_('email address'), unique=True)
clinic_name = models.CharField(max_length=150, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
date_joined = models.DateTimeField(default=timezone.now)
fb_projectId = models.CharField(max_length=150, blank=True)
fb_databaseURL = models.CharField(max_length=150, blank=True)
fb_storageBucket = models.CharField(max_length=150, blank=True)
fb_locationId = models.CharField(max_length=150, blank=True)
accounts = models.BooleanField(default=True)
dashboard = models.BooleanField(default=True)
measurements = models.BooleanField(default=False)
medications = models.BooleanField(default=False)
questionnaire = models.BooleanField(default=False)
chat = models.BooleanField(default=False)

objects = CustomUserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['clinic_name']

def __str__(self):
    return self.email

The react API call:
const loginUser = async (username, password) => {
return appAxios
  .post(`token/`, {
    username,
    password,
    email: username,
  })
  .then((res) => {
    setAuthTokens(res.data);
    setUser(jwt_decode(res.data.access));
    setApiErrors("");
    localStorage.setItem("authTokens", JSON.stringify(res.data));
    history.push("/");
  })
  .catch((err) => {
    setApiErrors(err.response.data.detail);
    history.push("/login");
  });

};

A: Why you don't use default documentation?
https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#adding-required-permissions-to-views
in your case:
class MyOnlyForAdminView(drf.generics.APIView):
    ... # any view staff before
    permission_classes = [drf.permissions.IsAdminUser]
    ... # any view staff after


text:
Q: Manual for cross-compiling a C++ application from Linux to Windows? Is there a manual for cross-compiling a C++ application from Linux to Windows?
Just that. I would like some information (links, reference, examples...) to guide me to do that.
I don't even know if it's possible.
My objective is to compile a program in Linux and get a .exe file that I can run under Windows.

A: It depends on what you mean (I couldn't really say).

*

*If you mean that you want to use an existing Linux application on Windows, then you could try compiling it using Cygwin on Windows. This however does not give you a Windows executable free from all dependencies towards Cygwin (your executable still depends on the cygwin.dll file) - and it still may need some porting before it will work. See http://www.cygwin.com.

*If you mean that you want to be able to perform the actual compilation of a Windows application on Linux and produce a .exe file that is executable on Windows - thus using your Linux box for development and/or compilation then you should look into MinGW for Linux which is a tool for crosscompiling for Windows on Linux. See http://www.mingw.org/wiki/LinuxCrossMinGW.
Best regards!

A: The basics are not too difficult:
sudo apt-get install mingw32
cat > main.c <<EOF
int main()
{
  printf("Hello, World!");
}
EOF
i586-mingw32msvc-cc main.c -o hello.exe

Replace apt-get with yum, or whatever your Linux distro uses. That will generate a hello.exe for Windows.
Once you get your head around that, you could use autotools, and set CC=i586-mingw32msvc-cc
CC=i586-mingw32msvc-cc ./configure && make

Or use CMake and a toolchain file to manage the build. More difficult still is adding native cross libraries. Usually they are stored in /usr/cross/i586-mingw32msvc/{include,lib} and you would need to add those paths in separately in the configure step of the build process.

A: I suggest you give the following, GUB (Grand Unified Builder) a try as it cross-compiles several packages with their dependencies and assembles them into a single installation package for currently 11 architectures. You can download a prebuilt iso for installation in a VM from here and follow the source here.  It can currently be used to cross-compile GNU LilyPond/ GNU Denemo / Inkscape and OpenOffice.org.
The target architectures are:

*

*darwin-ppc -  tar.bz2 file for Darwin 7 (MacOS 10.3)/PowerPC

*darwin-x86 -  tar.bz2 file for Darwin 8 (MacOS 10.4)/x86

*mingw -  mingw executable for Windows32

*linux-x86 -  shar archive for Linux/x86

*linux-64 -  shar archive for Linux/x86_64

*linux-ppc -  shar archive for Linux/PowerPC

*freebsd-x86 - shar archive for FreeBSD 4/x86

*freebsd-64 - shar archive for FreeBSD 6/x86_64

*cygwin - .tar.bz2 packages for Cygwin/Windows32

*arm - shar archive for Linux/ARM (largely untested)

*debian - shar archive for Debian (largely untested)


text:
Q: How to get website filename without extension and ?id=someid using php I would like to get a website filename after domain without the extension and any query string.
I try to resolve with basename, but if the user put ? after .php the output is display incorrect.
https://example.com/customers/NameIWant.php
returns: NameIWan
https://example.com/customers/NameIWant.php?someting
returns: NameIWan.php?someting

$url= basename($_SERVER['REQUEST_URI'], '.php' . $_SERVER['QUERY_STRING'])

This $url I will use it to query MySQL.
And I don't need query in URL or any code only the name of the current file.

A: You can use parse_url() and basename() to get the filename only:
<?php

$url = 'https://example.com/customers/NameIWant.php?someting';

// /customers/NameIWant.php
$path = parse_url($url, PHP_URL_PATH);

// NameIWant
$filename = basename($path, '.php');

(Replace $url = 'https://example.com/customers/NameIWant.php?someting'; with $url = $_SERVER['REQUEST_URI'];)
https://www.php.net/manual/en/function.parse-url.php
https://www.php.net/manual/en/function.basename.php


text:
Q: "Illegal instance declaration" when declaring instance of IsString I'm writing an application that uses UTF-16 strings, and to make use of the overloaded strings extension I tried to make an IsString instance for it:
import Data.Word ( Word16 )
import Data.String ( IsString(fromString) )

type String16 = [Word16]

instance IsString [Word16] where
    fromString = encodeUTF16

encodeUTF16 :: String -> String16

The problem is, when I try to compile the module, GHC 7.0.3 complains:
Data/String16.hs:35:10:
    Illegal instance declaration for `IsString [Word16]'
      (All instance types must be of the form (T a1 ... an)
       where a1 ... an are *distinct type variables*,
       and each type variable appears at most once in the instance head.
       Use -XFlexibleInstances if you want to disable this.)
    In the instance declaration for `IsString [Word16]'

If I comment out the instance declaration, it compiles successfully.
Why is this rejected? The instance for [Char] looks pretty much like the same thing, yet it compiles fine. Is there something I've missed?

A: After having a look through the GHC manuals and around the Haskell wiki (especially the List instance page), I've got a better idea of how this works. Here's a summary of what I've learned:
Problem
The Haskell Report defines an instance declaration like this:

The type (T u1 … uk) must take the form of a type constructor T applied to simple type variables u1, … uk; furthermore, T must not be a type synonym, and the ui must all be distinct.

The parts highlighted in bold are the restrictions that tripped me up. In English, they are:

*

*Anything after the type constructor must be a type variable.

*You can't use a type alias (using the type keyword) to get around rule 1.

So how does this relate to my problem?
[Word16] is just another way of writing [] Word16. In other words, [] is the constructor and Word16 is its argument.
So if we try to write:
instance IsString [Word16]

which is the same as
instance IsString ([] Word16) where ...

it won't work, because it violates rule 1, as the compiler kindly points out.
Trying to hide it in a type synonym with
type String16 = [Word16]
instance IsString String16 where ...

won't work either, because it violates part 2.
So as it stands, it is impossible to get [Word16] (or a list of anything, for that matter) to implement IsString in standard Haskell.
Enter... (drumroll please)
Solution #1: newtype
The solution @ehird suggested is to wrap it in a newtype:
newtype String16 = String16 { unString16 :: [Word16] }
instance IsString String16 where ...

It gets around the restrictions because String16 is no longer an alias, it's a new type (excuse the pun)! The only downside to this is we then have to wrap and unwrap it manually, which is annoying.
Solution #2: Flexible instances
At the expense of portability, we can drop the restriction altogether with flexible instances:
{-# LANGUAGE FlexibleInstances #-}

instance IsString [Word16] where ...

This was the solution @[Daniel Wagner] suggested.
Solution #3: Equality constraints
Finally, there's an even less portable solution using equality constraints:
{-# LANGUAGE TypeFamilies #-}

instance (a ~ Word16) => IsString [a] where ...

This works better with type inference, but is more likely to overlap. See Chris Done's article on the topic.
(By the way, I ended up making a foldl' wrapper around Data.Text.Internal and writing the hash on top of that.)

A:
Why is this rejected?

Because:
  (All instance types must be of the form (T a1 ... an)
   where a1 ... an are *distinct type variables*,
   and each type variable appears at most once in the instance head.

Is there something I've missed?

Yes:
   Use -XFlexibleInstances if you want to disable this.)


text:
Q: ShellExecute utilizando o CMD para abrir o mysql Senhores, gostaria de lhes perguntar se tem como utilizar o comando cmd para rodar o mysql.exe nele, deixem-me utilizar uma linha de código:
ShellExecute(Handle,'open',PChar('cmd.exe'),PWideChar('/k cd\mysql\bin & mysql.exe --host 192.168.0.50 --user root --database=sinval --password= Repair Table item'), nil, SW_SHOW);

Quero que na ultima passagem de parâmetro do ShellExecute(), ele execute um comando sql, sendo mais claro, gostaria que ficasse tipo assim:
ShellExecute(Handle,'open',PChar('cmd.exe'),PWideChar('/k **Comando cmd & comando para entrar no mysql | comando sql**'), nil, SW_SHOW);

Então, o que acham? Há uma forma melhor de fazer isto? Se não entenderem, por favor falem, tentarei ver uma melhor explicação.

A: Você precisa passar a opção -e ou --execute seguida do comando que quer executar. Por exemplo:
mysql.exe --host 192.168.0.50 --user root --database=sinval --password=bla --execute "SELECT * FROM tbl"


text:
Q: iPhone OpenGL ES 2.0 render to texture multiplies color values rather than adding them I am attempting to render to a texture on the iPhone using openGL ES 2.0.
To test, I am rendering a polygon (just a simple circle).  The circle is supposed to render fully red (rgba color is (1, 0, 0, 1)) but for some reason, it's resulting color will be the multiplication of it's color with whatever I initialize the render texture as.
For example :
Texture init color :     (1,   1,   1,   1)
Circle color :           (1,   0,   0,   1)
Resulting circle color : (1,   0,   0,   1) //This is as expected

Texture init color :     (0.5, 0.5, 0.5, 1)
Circle color :           (1,   0,   0,   1)
Resulting circle color : (0.5, 0,   0,   1) //This is unexpected.

The background color shouldn't be factored in at all.
If I render the circle with darker red (0.5, 0, 0, 1), the fact that it's multiplying the color rather than adding it is more evident.
Texture init color :     (1,   1,   1,   1)
Circle color :           (0.5, 0,   0,   1)
Resulting circle color : (0.5, 0,   0,   1) //This is as expected

Texture init color :     (0.5,  0.5, 0.5, 1)
Circle color :           (0.5,  0,   0,   1)
Resulting circle color : (0.25, 0,   0,   1) //This is unexpected.

My intuition is saying this is a problem with the blend mode but the problem persists even if I set the glBlendFunc to (GL_ONE, GL_ZERO).
This could also be due to the fact that the rendering uses premultiplied values but again, I am using very simple values here and full alpha which should ignore this problem but I might be wrong.
Question : Why are the colors multiplying with the background color?

My RenderTexture setup :
glBindTexture(GL_TEXTURE_2D, 0);

glGenFramebuffers(1, &m_frameBuffer);
glGenTextures(1, &m_textureId);

glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer);
glBindTexture(GL_TEXTURE_2D, m_textureId);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, MathUtil::NextPowerOf2(m_width), MathUtil::NextPowerOf2(m_height), 0, GL_RGBA, GL_UNSIGNED_BYTE, m_data);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_textureId, 0);

glViewport(0, 0, m_width, m_height);

When I render an object, I call the following :
glEnable(GL_BLEND);
glBlendFuncSeparate(GL_ONE, GL_ZERO, GL_ONE, GL_ZERO);

glDrawElements(GL_TRIANGLES, (GLsizei)(m_offset / 4) * 6, GL_UNSIGNED_SHORT, (void*)0);

Finally, I read the values from the render texture with glReadPixels (glGetTexImage isn't available for iPhone's openGL ES 2.0 I believe) to confirm these values.
glReadPixels(0, 0, MathUtil::NextPowerOf2(m_width), MathUtil::NextPowerOf2(m_height), GL_RGBA, GL_UNSIGNED_BYTE, m_data);

A: After a lot of testing, it was found that the problem occurred because of openGL settings that weren't properly reset between setting the render target from the screen to the texture (and vice versa).
My solution was to refresh all gl bindings and calls (like the shader program) after the target was setup.
Unfortunately, I don't know exactly which call or combination of calls was causing this odd behaviour.


text:
Q: Optimalize MySQL query I have one query, that is comparatively slow. I tried to rewrite it many times, but I cant find better solution. So I want to ask you, if it is written in wrong way from the beginning or it is ok.
    SELECT sql_calc_found_rows
    present_id, present_id, present_url, present_name, present_text_short, foto_name, price_id, price_price, price_amount, price_dis
    FROM a_present
    LEFT JOIN
       (SELECT price_id, price_present_id, price_supplier_id, price_dis, price_amount,
        (CASE WHEN price_dis <> 0 THEN price_dis ELSE price_amount END) as price_price
       FROM a_price
       WHERE
       price_visibility = 1 AND price_deleted <> 1
       GROUP BY price_id ) pri
    ON pri.price_present_id = present_id
    LEFT JOIN _present_fotos ON foto_id = present_title_foto
    LEFT JOIN _cate_pres ON cp_present = present_id
    WHERE present_visibility = 1 AND present_deleted <> 1 AND price_price > 0 AND present_out <> 1 AND cp_category IN (30,31,232,32)
    GROUP BY present_id
    ORDER BY price_price
    LIMIT 8

Description: price_dis is price after discount, price_amount is price before discount.. Each product (present) has more prices than one.. Is there faster solution to select final price?
If you will find table structure bad, I will be in trouble:)
Thank you very much!
EDIT:
explain select

A: OK, so I see a couple of things that could be improved.
First of all, you are JOINing with a table derived from a subquery - with subqueries MySQL does not use indexes (hence the slowdown). Instead of joining with a subquery, try JOINing with a table a_price itself, and put that CASE statement in the original (parent) SELECT. It should allow MySQL to use indexes when JOINing, and it is really important, when your subquery returns many rows.
It should look somewhat like this (including MIN() and GROUP BY, as you need minimum price):
SELECT (...), price_amount, price_dis, MIN((CASE WHEN pri.price_dis <> 0 THEN pri.price_dis ELSE pri.price_amount END)) as price_price
    FROM a_present
    LEFT JOIN a_price pri
    ON pri.price_present_id = present_id AND price_visibility = 1 AND price_deleted <> 1
(...)
GROUP BY present_id

Second of all - as EXPLAIN SELECT suggests - MySQL does not use index on table _cate_pres. You should make it use index to JOIN and to select categories you need (since you put some of them in the IN (..) statement).
Try adding an index on _cate_pres.cp_category, and/or maybe a composite index on this table (using two columns - cp_category and cp_present).
Generally, the result you want to achieve (not always it's possible, but in your case I'm pretty sure it is), is to make the following disappear from EXPLAIN SELECT:

*

*[key] NULL - this means no key is used in this particular set

*[Extra] Using temporary - this means a temporary table is created to retrieve results, and it is usually bad for performance

*[Extra] Using filesort - this means no index is used for sorting, so sorting process is slow.

Read more about indexes in the Mysql docs, and please give much attention to EXPLAIN output.


text:
Q: Combine Windows CMD BAT files I'm trying to build a .bat file that will run an executable Java SpringBoot web app jar file (keeping the cmd window open so that I can verify it started cleanly and close it/kill the process when I'm done), then wait 10 seconds to give the app time to start, then finally open it's URL in my web browser.
I've been able to get my intended functionality by breaking it down into two .bat files. The code I have below does what I want (except the echo message is repeated, but that's not a big deal).
I'd like to know how I can achieve the same functionality within a single .bat file.
I have launch.bat:
start wait.bat
java -jar C:\dev_tools\myapp.jar

which calls wait.bat:
echo Waiting for app to start before launching browser...
timeout 10
start http://localhost:8013/myapp/ && exit

A: Given the combined script is called launch.bat, put if not "%~1" == "" goto :JUMP on top, then the contents of launch.bat but with the first line changed to start launch.bat #, then place goto :EOF, then :JUMP, then the contents of wait.bat:
if not "%~1" == "" goto :JUMP
start launch.bat #
java -jar C:\dev_tools\myapp.jar
goto :EOF

:JUMP
echo Waiting for app to start before launching browser...
timeout 10
start http://localhost:8013/myapp/ && exit

When you now start launch.bat, it first checks if there is an argument, which should not be the case initially; so the first start command line is reached where the script executes itself, but with an argument (#) this time; the initially executed instance continues executing the rest until goto :EOF is reached, which terminates execution.
The recursively called instance will immediately continue execution at label :JUMP, where the code of the original wait.bat script is placed.

A: I think, this should work:
@echo off
start "MyApp" java.exe -jar C:\dev_tools\myapp.jar
echo Waiting for app to start before launching browser...
%SystemRoot%\System32\timeout.exe 10
start http://localhost:8013/myapp/

java.exe is started as separate process running parallel to cmd.exe instance processing this batch file.
So immediately after starting java.exe the information line is output by cmd.exe in initially opened console window.
Then timeout is executed to wait 10 seconds before finally the application is started with the HTTP URL.
Finally cmd.exe finishes processing the batch file as reading end of batch file which results in terminating the cmd.exe if started with option /C as done on double clicking on a batch file.
The Java application started as separate process keeps running independent on termination of cmd.exe processing the batch file.
I hope this is what you want.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*echo /?

*start /?

*timeout /?


text:
Q: Call a sagemaker inference endpoint using the java sdk v2 I am trying to call a sagemaker inference endpoint from Java. I can do it without an issue from Python, running this after installing the sagemaker package:
predictor = TensorFlowPredictor('my-endpoint')
data = {'foo': 'bar'}
result = predictor.predict(data)

How can I do this using the latest official library? I'm assuming it is software.amazon.awssdk:sagemaker:2.17.167
There are similar questions on this site, but they seem to use an older version of the client. I also found a github repository with examples, but it does not show how to call an inference endpoint.

A: Answering my own question. I was using the wrong library. For inference there is a separate "runtime" dependency: software.amazon.awssdk:sagemakerruntime:2.17.167
Something like this then works, this is Kotlin code:
val runtime = SageMakerRuntimeClient.builder()
    .region(Region.EU_CENTRAL_1)
    .build()

val requestString = """
    {"foo": "bar"}
"""

val request = InvokeEndpointRequest.builder()
    .endpointName("my-endpoint")
    .contentType("application/json")
    .body(SdkBytes.fromString(requestString, Charset.defaultCharset()))
    .build()

val response = runtime.invokeEndpoint(request)

println(response.body().asString(Charset.defaultCharset()))


text:
Q: darle formato a un string Buenas tardes tengo el sig código
static String neto = "";
static String tara = "";
static String bruto = "";

    Enviar_datos enviar = new Enviar_datos(conf);
    String bascula = conf.getBascula();
    if (control == 0) {

        conf.CargarConfiguracion();
        bascula = conf.getBascula();

        tara = leido_final;
        System.out.println("tara:" + tara);
        lf1 = Double.parseDouble(leido_final);

    }
    if (control == 1) {

        neto = leido_final;
        System.out.println("neto:" + neto);
        lf2 = Double.parseDouble(leido_final);

    }

    if (control == 2) {
        double brutoi = lf1 + lf2;
        bruto = String.valueOf(brutoi);

        enviar.setPeso_neto(bascula + tara + neto +bruto);
        enviar.converir_datos();
        control = 0;
    }

}

mi programa registra las variables con una bascula con el sig formato 0.000
mi pregunta es como puedo rellenar con ceros a la izquierda para darle el siguiente formato 0000000000.000

A: Como tal en un dato tipo Doubleno conozco una manera posible de hacerlo. El método que funciona, es pasarlo a un tipo stringy agregarlos manualmente. Te comparto una función que usé alguna vez para esto:
private static String agregarCeros(String string, int largo)
            {
                String ceros = "";

                int cantidad = largo - string.length();

                if (cantidad >= 1)
                {
                    for(int i=0;i<cantidad;i++)
                    {
                        ceros += "0";
                    }

                    return (ceros + string);
                }
                else
                    return string;
            }

Lo que hace este método, es que le envías 2 variables, una variable stringque es el string, y una variable largoque es el largo que debería tener tu string, con los 0 agregados a la izquierda.
Si necesitas más información, lo consulté de Esta pregunta en un sitio externo

A: clase java.text.DecimalFormat, sirve para formatear números.
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
static String formatoDeseado = "0000000000.000";
static DecimalFormat formateador = new DecimalFormat(formatoDeseado);

Para obtener el número formateado:
double valor = 123.455;
String valorFormateado = formateador.format(valor);

System.out.println("valor formateado="+valorFormateado);

Saludos.


text:
Q: Unity setting Button's onClick in script I am using Unity 2020.3 and making basically a question-answer game.
Assume that I have this  two functions:
public void TrueAnswer()
{
    Debug.Log("True !");
}

public void FalseAnswer()
{
    Debug.Log("False !");
}

In every question, true answer's button is changing(For example, in xth question the answer is in first button but in x+1th question the answer is in third button). So, I should change answer buttons onClick event in every question. Depend on my research, there is some ways like:
using UnityEngine.UI;

m_YourFirstButton.onClick.AddListener(TaskOnClick);
m_YourSecondButton.onClick.AddListener(delegate {TaskWithParameters("Hello"); });
m_YourThirdButton.onClick.AddListener(() => ButtonClicked(42));
m_YourThirdButton.onClick.AddListener(TaskOnClick);

(This is from Unity Documentation, version 2019.1)
using UnityEngine.UIElements;

button.GetComponent<Button>().clicked += ButtonClicked;

(This is what I understand from Unity Documentation version 2020.3 and what VS 2019 IntelliSense recommend me to use "clicked" event. 2020.3 also has onClicked event but it is obsolote)
First, I used the first way to set buttons onClick events and it did not work.
Then, I read the documentations and tried the second solution, which is also did not work but I get an error:
ArgumentException: GetComponent requires that the requested component 'Button' derives from MonoBehaviour or Component or is an interface.

I understand what the error is, but I am very confused. After Unity 2019.1, I can't find the UnityEngine.UI library in Unity Documentations but if I use in script I can use it without any error. So depend on the documentation I must use UnityEngine.UIElements library but if I use, how can I make buttons derive from MonoBehaviour or others?

A: I don't think you need to change the buttons click event at all.
Rather those can be a "static" click event that return what button index was clicked.
[0] Button 1 -> ButtonClicked(0)
[1] Button 2 -> ButtonClicked(1)
[2] Button 3 -> ButtonClicked(2)

You can then have the answers in an array
[0] Answer 1
[1] Answer 2
[2] Answer 3

and use the clicked buttons index to determine which answer was picked.
When you go to ask a new question, all you have to do is create (or replace values of) the answers array with the relevant answers (in any order you wish).


text:
Q: allow "unsafe" websites to get GeoLocation on smartphone In a form on a website that im building for a school work, i need to check the geolocation of the computer/smartphone when a button its clicked, im using the IIS, so on my computer i just type localhost/form.html to use it, and it works. But on my smartphone, i type the IP of my computer/form.html (when in the same network) i click the button but nothing happens because the google chrome doesnt allow unsafe websites to get the geolocation.
(the code that im using, doesnt really matter because the problem isnt there..)
<script>
    var x = document.getElementById("x");
    button.addEventListener("click", getLocation);
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>

Anyone knows how can i solve this? Thanks in advance.


text:
Q: Direct Product of Groups and Group Actions
Let $A$, $B$ be subgroups of $G$ and $AB=\{ab:a\in A, b\in B\}\subseteq G$.
  Show that the direct product $A\times B$ acts on the set $AB$ by $(a,b)x=axb^{-1}$ is a group action.
  Show that there is only one orbit.

Let $a_1,a_2\in A$, $b_1,b_2$ and $x\in AB$ and show the axioms of a group action hold as follows
$$
(a_1,b_1)(a_2,b_2)x=(a_1,b_1)a_2xb_2^{-1}=a_1a_2xb_2^{-1}b_1^{-1}=(a_1a_2)x(b_2^{-1}b_1^{-1})=(a_1a_2,b_1b_2)x=[(a_1,b_1)\times (a_2,b_2)]x
$$  Showing the identity axiom for group actions is trivial.
The above seems correct but I'm stuck on how to show there is only one orbit.  I've been thinking about how to show the stabilizer is limited to the identity but am not getting anywhere.

A: To show that there is only one orbit, it suffices to show that the orbit of the identity element is the entire set $AB$. Any element of $AB$ is of the form $ab$ with $a\in A$ and $b\in B$, so we need to find $(a',b')\in A\times B$ such that
$$(a',b')e=ab,$$
where $e$ denotes the identity element of $G$. Taking $(a',b')=(a,b^{-1})$ does the trick.


text:
Q: keyboard - resizing viewgroup, overlaying viewgroups and custom editor view im writing a keyboard and there are a number of things i want to do:
1) i want to be able to dyamically resize the the keyboard view. I
have a custom view for my keyboard, created by my
InputMethodService.onCreateInputView
i've tried calling invalidate, requestLayout, forceLayout, on the
keyboard view, on its parent and on the view root but nothing seems to
call the onMeasure code again in my layout to allow it to resize.
2) i would also like to have a view group that goes over the edit
window and possibly over the rest of the screen. for example if the
user preses a button i want to draw above thier finger (which could be
over the editor window) what the are pressing or some additional
information.
3) i would like to be able to disable the editor window and do this my
self, so for example i can change how this functions


text:
Q: MobileFirst 7.1 Community Edition I would like to know if there is any community or free edition of MobileFirst which can be used for small scale projects ?

A: There is not. There is the development edition for development time, and the enterprise/consumer edition for going to production (contains the required tools and artifacts).


text:
Q: Owl-carousel Autoplay not working I searched a lot about this and found almost the same answer everytime. I have referred Owl Carousel Won't Autoplay  and Owl Carousel Will Not Autoplay and this too http://owlcarousel.owlgraphic.com/demos/autoplay.html
I am using below code for setting autoplay time but it's not working:

I am using owl carousel in below format:

                                 Quick View

  NEW 15% OFF

Product 1

abcd

                            XL / XXL / S

 $25

    Add to cart

Can anyone please tell me what is that I am missing?

A: Not sure if this solves your problem, but you can just set autoplay: 500.
autoPlayTimeout doesn't appear to be a valid attribute - http://owlgraphic.com/owlcarousel/#customizing
Also, autoplayHoverPause should be stopOnHover

A: .owlCarousel({
  autoplay:true,
  autoplayTimeout:2000,
  ...
  ...