text:
Q: Writting a Hessian for an arbitrary number of variables or for a arbitrary vectorial function The following code calculate the Hessian --- with simplification --- for a transcendental function.
fu[x_, y_, z_] :=  x^α y^β z^γ
hes = D[#1[#2, #3, #4], {{#2, #3, #4}}, {{#2, #3, #4}}] &
hescd = hes[fu, x, y,
    z] /. {x_^(α_ - 2) y_^β_ z_^γ_ -> U/x^2,
    x_^(α_ - 1) y_^(β_ - 1) z_^γ_ -> U/(x y)};
hescd // MatrixForm

I would like
1) to generalize it for a vector of arbitrary dimension
2) It obviously works  for any algebraic function but not for all the transcendental functions for which there is a simplification. How to rewrite it to include directly in hes the simplification?

A: Maybe you want the following:
hess[fn_, varList__] := Simplify[D[fn @@ {varList}, {{varList}, 2}]]

The first argument is the function, and the remaining arguments are referred to by varList__. Its length is arbitrary, and the function is applied to it by @@.
I added Simplify to address your point 2). It could be replaced by FullSimplify or some other, more customized commands that depend on the specific application.
Edit
I initially only went by the title of the question. The more specific replacement in the question can be built into my original answer by adding the following rule:
hess[fn_, varList__] := U ( D[fn @@ #, {#, 2}] /. Thread[# -> 1])/
                            KroneckerProduct[#, #] &[#] &@{varList}

This maintains the calling syntax given in the question, and works for arbitrary dimensions:
fu[w_, x_, y_, z_] := w^a x^b y^c z^d

hess[fu, w, x, y, z] // MatrixForm

The output is the same as in @MichaelE2's answer.

A: The Hessian is pretty straightforward, as pointed out by Jens.  Using patterns instead of basic algebra makes the "simplification" trickier than necessary.
ClearAll[a, b, c, d, w, x, y, z, f];

f[x_List, p_List] := Inner[Power, x, p, Times];

vars = {w, x, y, z};
powers = {a, b, c, d};

D[f[vars, powers], {vars, 2}] * U/f[vars, powers] // MatrixForm

A: This seems to work for the Cobb-Douglass function with arbitrary number of variables:
ClearAll[fu2, hess2]
fu2[x : {__}, p : {__}] := Times @@ (x^p)

hess2[fn_, x : {__}, p : {__}] := ReleaseHold[D[fn[x, p], {x, 2}] /.
  Power[w_, Plus[k_Integer, a_]] :>  HoldForm[Power[w, k]] Power[w, a] /. fn[x, p] :> U]

hess2[fu2, {v, w, x, y, z}, {a, b, c, d, e}] // MatrixForm

In version 10 and later versions you can use Inactive and Activate combination instead of HoldForm and  ReleaseHold, that is,
hess2[fn_, x : {__}, p : {__}] := Activate[D[fn[x, p], {x, 2}] /.
  Power[w_, Plus[k_Integer, a_]] :>  Inactive[Power[w, k]] Power[w, a] /. fn[x, p] :> U]


text:
Q: Changing string to UTC to dateTime object I have time = '2020-06-24T13:30:00-04:00'. How can I change it to a dateTime object in UTC time. I would prefer not to use pd.Timestamp(time).tz_convert("UTC").to_pydatetime() because it returns a weird output that would look like this datetime.datetime(2020, 6, 24, 17, 30, tzinfo=<UTC>). As a result, when I check for equality with datetime.datetime(2020, 6, 24, 17, 30), it return False.
Edit:
import datetime
import pytz

time = '2020-06-24T13:30:00-04:00

dt = datetime.datetime(2020, 6, 24, 17, 30)
print("dt: ",dt)

so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z').astimezone(pytz.utc)
print("so:",so)

print(dt == so)

outputs
dt: 2020-06-24 17:30:00
so: 2020-06-24 17:30:00+00:00
False

How can I get it to properly evaluate to True?

A: #1 Since your string is ISO 8601 compatible, use fromisoformat() on Python 3.7+:
from datetime import datetime, timezone

s = '2020-06-24T13:30:00-04:00'

dtobj = datetime.fromisoformat(s)
# dtobj
# datetime.datetime(2020, 6, 24, 13, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

Note that this will give you a timezone-aware datetime object; the tzinfo property is a UTC offset. You can easily convert that to UTC using astimezone():
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)

#2 You can achieve the same with strptime (also Python3.7+ according to this):
dtobj = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)

#3 If you want to turn the result into a naive datetime object, i.e. remove the tzinfo property, replace with None:
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)

#4 For older Python versions, you should be able to use dateutil's parser:
from dateutil import parser
dtobj = parser.parse(s)
dtobj_utc = dtobj.astimezone(timezone.utc)
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)

A: Alright so my previous answer was sort of wack because I did not understand your issue entirely so I am rewriting it. You problem is that you are constructing a datetime object from a string and it is timezone aware(UTC). However, whenever you make a datetime object in python, dt = datetime.datetime(2020, 6, 24, 17, 30), it is creating it but with no timezone information (which you can check using .tzinfo on it). All you would need to do is make dt timezone aware when you first create it. See below my code snippit.

import datetime

time = '2020-06-24T13:30:00-04:00'

dt = datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)

print("dt: ",dt.tzinfo)

so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z')

print("so:",so.tzinfo)

print(dt == so)

redpajama_set_name: RedPajamaStackExchange


text:
Q: CMS (Central Manamenent Server) help/guidance? We have just recently come across the Central Management Server feature in SQL2008.
We currently have a number of environments and think that this feature could really help us in running multiple instances queries.
But before making the move to implement this to our production environment, would anyone with experience please help us with the following points?

*

*Are there any best practices you recommend?

*Are there any drawbacks/cons to consider if we decide to use the feature?

*Any negative in creating a group consisting of both 2005 and 2008 servers?

*And in regards to transactions, is this per instance or a whole group?
any reply would be very much appreciated.

A: There is no real best practice, but if you want to use a job server as well you should choose your CMS as a server which is a standard edition, if not you can even use a SQL express edition as your CMS.
If you are managing a multi server/instance environment, there are no real cons/drawbacks, this will enhance the way you can monitor & query your environment.Also if you have multiple dba's in your environment you can work together on the same CMS, and see the newly installed instances from your Collegue.
You can build your groups the way you like and want, I have environments where I have 2005 & 2008 & 2012 & 2014 together because they are production. The only thing that is a drawback with that is that some dmv's are different in 2005 then in 2008/2012/2014. So some multiserver-queries will fail if you don't make them 2005 compatible.
This is a transaction per instance, the result is returned as one result, but it will be a transaction for every instance.
I hope this answered all your questions.

A: Are there any best practices you recommend?
To my knowledge there are no best practices around CMSs.
Are there any drawbacks/cons to consider if we decide to use the feature?
If your CMS gets fairly large (100+ entries) it can take a few seconds (30-40) to load.  Also multi server queries have their drawbacks.  Multi server queries work great for updates or for displaying data, however you aren't going to be able to store your results into any type of table/temp table.  You'd have to dump the results into a CSV and re-load if you want to do something like that.  Also if you try to connect to more than 4-5 servers in a single connection it can take some time to finish.  There is also a limit but I don't remember what it is.  ~50 is the practical limit I think.
Any negative in creating a group consisting of both 2005 and 2008 servers?
No, I've done this and it works great as long as your queries work for both 2005 and 2008.
And in regards to transactions, is this per instance or a whole group?
As I alluded to above it's going to be per instance.  No data travels between them.
Additional info
All that said I love CMSs.  They are a wonderful way to keep a shared list of instances that the entire team can reference.  Also if you are interested I have a script that will load a CMS from a table.  One of the benefits to this is that you can add the same instance multiple times in different groupings.  So one group is broken down by version (2005, 2008 etc) and another by SDLC stack (dev, test, prod) or any other format you can think of.


text:
Q: How to find corner points , counts the shapes with hole and which given type python opencv I hope all are doing well.
I have the input image as shown below
I want to:

*

*count the corner points in the image of a given color

*count the shapes with hole in the image.

*count the number of the shapes in the image of a given type (like
triangles, circles, rectangles, etc.)

I have tried the following code for counting the corner points but it also counts the inner point of the shape.
How can I process from this point?
My code
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('/content/shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray,5,3,0.04)
ret, dst = cv2.threshold(dst,0.1*dst.max(),255,0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(gray,np.float32(centroids),(5,5),(-1,-1),criteria)
for i in range(1, len(corners)):
    print(corners[i])
img[dst>0.1*dst.max()]=[255,0,255]
plt.imshow(img)

Input

Output


text:
Q: Deploying Jekyll on Heroku Fails Using Jekyll 2.5.3 on Heroku with Github deployment. Jekyll builds fine locally on OS X, but fails on Heroku. Any ideas on how to fix this would be appreciated.
config.ru
require 'rack/jekyll'
require 'yaml'
run Rack::Jekyll.new

Gemfile
source 'https://rubygems.org'

gem 'bundler'
gem 'jekyll', '~> 2.5'
gem 'jekyll-redirect-from', '~> 0.8'
gem 'html-proofer'
gem 'rack-jekyll'
gem 'compass'

app.json
{
  "name":"ninelabs.com",
  "scripts":{},
  "env":{
    "LANG":{
      "required":true
    },
    "RACK_ENV":{
      "required":true
    }
  },
  "addons":[]
}

Here's the log showing errors:
Note the line No such file or directory - /apple-icon-72x72.png (Errno::ENOENT)
> 2015-10-04T16:41:32.741506+00:00 heroku[web.1]: Starting process with command `bundle exec rackup config.ru -p 13959`
> 2015-10-04T16:41:37.929983+00:00 app[web.1]: /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/utils.rb:102:in `initialize': No such file or directory - /apple-icon-72x72.png (Errno::ENOENT)
> 2015-10-04T16:41:37.930023+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/utils.rb:102:in `open'
> 2015-10-04T16:41:37.930058+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/utils.rb:102:in `has_yaml_header?'
> 2015-10-04T16:41:37.930076+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/site.rb:177:in `block in read_directories'
> 2015-10-04T16:41:37.930093+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/site.rb:172:in `each'
> 2015-10-04T16:41:37.930109+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/site.rb:172:in `read_directories'
> 2015-10-04T16:41:37.930126+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/site.rb:151:in `read'
> 2015-10-04T16:41:37.930149+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/jekyll-2.5.3/lib/jekyll/site.rb:49:in `process'
> 2015-10-04T16:41:37.930174+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-jekyll-0.3.5/lib/rack/jekyll.rb:29:in `initialize'
> 2015-10-04T16:41:37.930192+00:00 app[web.1]:  from /app/config.ru:3:in `new'
> 2015-10-04T16:41:37.930209+00:00 app[web.1]:  from /app/config.ru:3:in `block in <main>'
> 2015-10-04T16:41:37.930225+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'
> 2015-10-04T16:41:37.930241+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'
> 2015-10-04T16:41:37.930263+00:00 app[web.1]:  from /app/config.ru:in `new'
> 2015-10-04T16:41:37.930288+00:00 app[web.1]:  from /app/config.ru:in `<main>'
> 2015-10-04T16:41:37.930305+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'
> 2015-10-04T16:41:37.930321+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'
> 2015-10-04T16:41:37.930337+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'
> 2015-10-04T16:41:37.930354+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'
> 2015-10-04T16:41:37.930371+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'
> 2015-10-04T16:41:37.930400+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'
> 2015-10-04T16:41:37.930417+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:272:in `start'
> 2015-10-04T16:41:37.930434+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/lib/rack/server.rb:147:in `start'
> 2015-10-04T16:41:37.930451+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/gems/rack-1.6.4/bin/rackup:4:in `<top (required)>'
> 2015-10-04T16:41:37.930468+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/bin/rackup:23:in `load'
> 2015-10-04T16:41:37.930489+00:00 app[web.1]:  from /app/vendor/bundle/ruby/2.0.0/bin/rackup:23:in `<main>'
> 2015-10-04T16:41:37.956751+00:00 app[web.1]: Configuration file: /app/_config.yml
> 2015-10-04T16:41:39.069543+00:00 heroku[web.1]: State changed from starting to crashed
> 2015-10-04T16:41:39.062775+00:00 heroku[web.1]: Process exited with status 1


text:
Q: How do I solve this analytically $3^x=9x$ One of my friends ask me how to solve this equation analytically $3^x=9x$. Looking at it I guess 3 is the answer and I also plot a graph of line $9x$ and the curve $3^x$, they intersect at 3.
But, what I want is to give an analytical solution of the equation. I started
$3^x=9x$
$3^{x-2}=x$
$(x-2)\ln3=\ln x$
How can I continue?

A: This equation has no analytical solution, you can find roots only numerically. But one root is obvious. And we can prove that there is no root which is more than 3 by taking the derivative  of $y=((x-2)\ln(3))-(\ln(x))$ that gives $y'=\ln(3)-\frac{1}{x}>0$ when $x>3$. There is another solution approximately $0.127869$. Because of monotonicity and continuity of $y$ on $[0,\frac{1}{\ln3}]$ there is only one root there, analogically on $(\frac{1}{\ln3},\infty)$. That is only two roots.

A: It's easy to prove that $3^x \geq 9x$ for all real $x \leq 0$ and $x\geq 3$ with equality at $x=3$. Furthermore, in the interval $(0,3)$ there is exactly one $\alpha$  such that $3^\alpha = 9\alpha$.  Put all this together and it's not hard to show that $3^x > 9x$ for $x \in (-\infty,\alpha) \cup (3,\infty)$ and $3^x < 9x$ for $x \in (\alpha,3)$.
There is no way of algebraically manipulating the equation $3^x = 9x$ around to get this(*) - you have to use calculus (or something to that effect).
(*): Unless you don't mind using facts about the Lambert W function, and that amounts to the same as using calculus; essentially.

A: $$3^x=9x \Rightarrow 1 =\frac {9x}{3^x} \Rightarrow 1= 9x \cdot e ^{-x\ln 3}\Rightarrow \frac{1}{9}=x \cdot e ^{-x\ln 3} \Rightarrow$$
$$\Rightarrow \frac{-\ln 3}{9}=(-x \ln 3)\cdot e^{-x\ln 3}\Rightarrow W\left(\frac{-\ln 3}{9}\right)=-x \ln 3\Rightarrow$$
$$x= \frac{-W\left(\frac{-\ln 3}{9}\right)}{\ln 3}$$
where W is Lambert W function .

A: To find "the other root" it often helps to express the original problem as deviation from that root which is already known. So if we "see" one root is $\small x=3$ I'd proceed
$$\small 3^x = 9x \to 3^{3+d} = 9(3+d) $$
where $\small d=0$ refers to the already known solution. Then the equation often can be much simplified to exhibit a possible interval for another solution more visibly.
$\qquad \small \begin{eqnarray}
3^{3+d} &=& 9(3+d) \\
27 \cdot 3^d &=& 27+9d \\
3^d &=& 1+d/3 \\
\end{eqnarray} $
and search for solutions in $\small d \ne 0 $ If we want to avoid calculus here, but know the expression for the exponential series, we might introduce the symbol $\small \lambda = \ln(3) $ and write
$\qquad \small \begin{eqnarray}
1+ \lambda d + (\lambda d)^2/2! + \ldots &=& 1 + d/3 \\
 \lambda d + (\lambda d)^2/2! + \ldots &=&  d/3 \\
 \lambda  + \lambda^2 d/2! + \lambda^3 d^2/3! + \ldots &=&  1/3 \\
 d( \lambda^2 /2! + \lambda^3 d/3! + \ldots ) &=&  1/3 - \lambda  & \lt & 0\\
\end{eqnarray} $
so d must be negative.
Then we can write using -c=d and c positive:
$\qquad \small \begin{eqnarray}
3^{-c} &=& 1-c/3 \\
1/3^c + c/3 &=& 1 \\
\end{eqnarray} $
and have an initial guess ($\small 2 \lt c \lt 3 $) for the interval for the second possible c ($\small c \ne 0 $) resp the second root $\small d = -c \ne 0 \to 0 \lt x \lt 1 $ and might apply Newton's iteration for approximation of the actual root. Also we see immediately that there is no further real (non-complex) root.

A: I think the only way of manipulating this jargon is by splitting the equation .
$3^x=9x$
$y=3^x$     and    $  y=9x$
when plotted, you find that the two equations intersect at $x=3$
therefore,$x=3$

A: I am going to give three methods of solving this problem and they are:
$1$. Differentiation -                                                                               It can be broken down into a simpler form by finding  the derivative of both sides.
$\frac{d(3^x)}{dx} = \frac{d(9x)}{dx}$
$x(3^x - 1) = 9$
$x = 9$
$3^{x - 1}=9$
$3^{x - 1} = 3^2$
Equating the exponents,
$x - 1 = 2$
$x = 3$
Thus $x = 3 \ or \ 9$.
But since $9$ does not satisfy the equation.
$x = 3$.
$2$. Graphical approach -
This can be done by plotting a graph of $y=9x$ and $y=3^x$ and the $x$ component of the intersection is going to be $3$.
Thus $x=3$.
3. Value analyzing - This done by replacing the variable with figures starting from zero to see which one satisfies the equation and you will find out the equation is true when $x$ is $3$.
Thus $x=3$.


text:
Q: I have installed iOS6 simulator in xcode5, but I can't run app on iOS6 simulator There is no option on the left corner of  Xcode to select to run on iOS6 or iOS7 simulator. While there should be.  The storyboard builds for iOS6.1 and later. How could I run my app on iOS6 simulator?

A: There is an option on the top left corner to select which simulator you want:

You also have to select the right Architecture to be able to change the Deployment Targeet:

To further prove that you have to remove the 64 bits:

Hope this helps!

A: You might need to install additional iOS simulator.
To install additional tools and software go to:
xcode preference -> downloads.

A: you must change your deployment target to 6.1. if you cannot select that you might need to install additional packets from the settings of xcode.

A: @LuisCien's answer is correct, though your VALID_ARCHS may need to be edited as well. The key point there being that ARCHS and VALID_ARCHS cannot contain arm64. As @LuisCien and others have pointed out, the IPHONEOS_DEPLOYMENT_TARGET must be 6.1 or earlier.


text:
Q: Windows 10 java.net.BindException: Address already in use: bind on all ports I am trying to fire an instance of Zookeeper from my windows command line. No matter what port I try I get the error
java.net.BindException: Address already in use: bind
        at sun.nio.ch.Net.bind0(Native Method)
        at sun.nio.ch.Net.bind(Net.java:433)
        at sun.nio.ch.Net.bind(Net.java:425)
        at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
        at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:67)
        at org.apache.zookeeper.server.NIOServerCnxnFactory.configure(NIOServerCnxnFactory.java:90)
        at org.apache.zookeeper.server.ZooKeeperServerMain.runFromConfig(ZooKeeperServerMain.java:120)
        at org.apache.zookeeper.server.ZooKeeperServerMain.initializeAndRun(ZooKeeperServerMain.java:89)
        at org.apache.zookeeper.server.ZooKeeperServerMain.main(ZooKeeperServerMain.java:55)
        at org.apache.zookeeper.server.quorum.QuorumPeerMain.initializeAndRun(QuorumPeerMain.java:119)
        at org.apache.zookeeper.server.quorum.QuorumPeerMain.main(QuorumPeerMain.java:81)

I have tried all types of crazy ports which are open, e.g 2188, 2180 etc.
None of these ports show up on netstat commands. Is this a JDK issue specific to Windows 10?
thanks

A: Disable your antivirus and make sure you are not listening on those ports already.


text:
Q: puppet can't get the right service status from centos5.3 when i disable puppet service ,centos5.3 system always have change: " Notice: /Stage[main]/Puppet/Service[puppet]/ensure: ensure changed 'running' to 'stopped'
Notice: Finished catalog run in 1.15 seconds"
just say the code :
[root@xen-21206-vm02 ~]# puppet resource service puppet -d

Debug: Puppet::Type::Service::ProviderDaemontools: file /usr/bin/svc does not exist
Debug: Puppet::Type::Service::ProviderOpenrc: file /sbin/rc-service does not exist
Debug: Puppet::Type::Service::ProviderLaunchd: file /bin/launchctl does not exist
Debug: Puppet::Type::Service::ProviderGentoo: file /sbin/rc-update does not exist
Debug: Puppet::Type::Service::ProviderDebian: file /usr/sbin/update-rc.d does not exist
Debug: Puppet::Type::Service::ProviderRunit: file /usr/bin/sv does not exist
Debug: Puppet::Type::Service::ProviderSystemd: file systemctl does not exist
Debug: Puppet::Type::Service::ProviderDaemontools: file /usr/bin/svc does not exist
Debug: Puppet::Type::Service::ProviderOpenrc: file /sbin/rc-service does not exist
Debug: Puppet::Type::Service::ProviderLaunchd: file /bin/launchctl does not exist
Debug: Puppet::Type::Service::ProviderGentoo: file /sbin/rc-update does not exist
Debug: Puppet::Type::Service::ProviderDebian: file /usr/sbin/update-rc.d does not exist
Debug: Puppet::Type::Service::ProviderRunit: file /usr/bin/sv does not exist
Debug: Puppet::Type::Service::ProviderSystemd: file systemctl does not exist
Debug: Executing '/sbin/service puppet status'
Debug: Executing '/sbin/chkconfig puppet'

service { 'puppet':
  ensure => 'running',
  enable => 'false',
}

[root@xen-21206-vm02 ~]# /sbin/service puppet status
puppet is stopped
[root@xen-21206-vm02 ~]# echo $?
3

this agent get the wrong service status.should
service { 'puppet':
  ensure => 'stopped',
  enable => 'false',
}

who can help me?
thks


text:
Q: Is it appropriate to flag feature requests to get attention from CMs? I have seen some feature requests that have no involvement by a CM on the post (no comments, no answers, no edits). It may be possible that they have not seen that feature request. In such case, would it be appropriate to flag as "in need of moderator attention" saying "This feature request needs your attention".

A: No. Flags are kind of like yelling FIRE.
From experience, CMs/Devs/PMs and probably other employees do keep an eye on meta - both main and per site, and while they might not always answer, are probably aware.
Flags are for things that need (semi) immediate attention, which FRs never are.


text:
Q: Adding new attribute to Object after it's created using method (Ruby) I am trying to add an attribute to an object after it's been created using a method from within the object Class. I'd like to put this code in the def set_sell_by and def get_sell_by methods, if this is possible. So, in the end I'd like to do apple.set_sell_by(10) and then get that value later by doing apple.get_sell_by to check if the item has 5 days or less left to sell it.

class Grocery_Inventory
 attr_accessor :product, :store_buy, :quantity, :serial_number, :customer_buy
 def initialize(product, store_buy, quantity, serial_number, customer_buy)
  @product = product
  @store_buy = store_buy
  @quantity = quantity + 5
  @serial_number = serial_number
  @customer_buy = customer_buy
 end

 def get_product_name
  p product
  self
 end

 def get_cost_customer
  p "$#{customer_buy}"
  self
 end

 def get_product_quantity
  p "You have #{quantity} #{product}"
  self
 end

 def set_sell_by
  #some code...
  self
 end

 def get_sell_by
  if sell_by < 5
   p "You need to sell this item within five days."
   self
  else
   p "Item doesn't currently need to be sold."
   self
  end
 end
end

apples = Grocery_Inventory.new("apples", 1.00, 5, 123, 0.25)
apples.get_product_name
apples.get_cost_customer
apples.get_product_quantity

A: Ruby is very lax in this regard. Simply access a variable with @and if it doesn't exist it will be created.
def set_sell_by
    @sell_by = value
    self
end


text:
Q: why does a variable in javascript seem to hold the value "undefined" even when it was defined if I run the following javascript code, the browser alerts "undefinedabc".
var x;
x += "abc";
alert(x);

To me it looked like I did define the variable x, so why does it seem to be undefined?

A: var x = "";
x += "abc";
alert(x);

Try this. You are trying to add 'abc' and undefined which will result to undefinedabc.

A: undefined is the default value of any variable with no value assigned. So, var x; means that a = undefined. When you add "abc" to it, you're actually doing undefined + "abc". Finally, undefined is stringifiend to "undefined" and then concatenated to "abc" and turns to "undefinedabc".
In order to concat initialize the var x, you should assign an empty string to it (remember that JavaScript dinamically-typed):
var x = '';
x += "abc";
alert(x);    // "abc"

This MDN article describes this behaviour.

A: First examine the behaviour of a Variable Statement, Specifically:
"Variables are initialised to undefined when created."

Then examine the behaviour of the addition operator (compound assignment applies the behaviour of the operator corresponding to what precedes =).
Specifically, point 7:
"If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)"

So, since "abc" is a string, x is to be translated to a String, according to ToString.  x, as we know from above, is undefined.
Finally, examine the behaviour of the abstract operation ToString, specifically, that an undefined argument results in the string "undefined".


text:
Q: How to change terminal title without changing the prompt string? I have customized my command prompt to display current directory with some color and full path. Now I want to set title of my window to only directory name (not full path).
Can you please advise how to achieve  that in korn shell. Thanks.

A: The way I found to achieve this is by creating an alias to the cd.
I put the following code inside the .profile file which did the trick
xcd() { cd $*; echo -ne "\033]0;$(basename $PWD)\007"; }
alias cd='xcd'

Thanks a lot to Kusalananda for the solution which I was actually looking for:
cd() { command cd "$@"; echo -ne "\033]0;${PWD##*/}\007"; }

A: According to this site : How to change the title of an xterm: examples for different shells

ksh provides little in the way of functions and expansions, so we have
  to insert the escape string in the prompt to have it updated
  dynamically. This example produces a title of username@hostname:
  directory and a prompt of ksh$ .
case $TERM in
    xterm*)
        HOST=`hostname`
        PS1='^[]0;${USER}@${HOST}: ${PWD}^Gksh$ '
        ;;
    *)
        PS1='ksh$ '
        ;;
esac

However, $PWD produces the full directory path. We can remove the
  prefix of $HOME/ from the directory using the ${...##...} construct.
  We can also use ${...%%...} to truncate the hostname:
HOST=`hostname`
HOST=${HOST%%.*}
PS1='^[]0;${USER}@${HOST}: ${PWD##${HOME}/}^Gksh$ '

Note that the ^[ and ^G in the prompt string are single characters for
  ESC and BEL (can be entered in emacs using C-q ESC and C-q C-g).


text:
Q: Project Euler Number 338 I'm stuck on Project Euler problem 338. Here is what I've done so far...
Let's denote a rectangle with width and height x and y respectively (x,y). To form new rectangles you can consider cutting a kind of stairway down the diagonal (as is shown in in the problem description) with d steps. But to form a new rectangle the following must hold: d|x and either (d-1)|y or (d+1)|y. The new rectangle then becomes either (x/d*(d-1), y/(d-1)*d) or (x/d*(d+1), y/(d+1)*d). Obviously the new rectangles area is the same as the old rectangle's.
That was enough to confirm that G(10)=55 and G(1000)=971745 by looping through all relevant d and adding all new rectangles to a set being careful to count (x,y) and (y,x) only once.
The main issue with this method is that it's possible to make a new rectangle in two different ways. For example, (9,8) can transform into both (6,12) and (12,6) with d=3 and either d-1 or d+1 dividing y. Or another example of (4,4) transforms into both (2,8) and (8,2) with d=2 and d=1 respectively.
I was then lucky enough to read this blog post. It removes the need to check for duplicates by searching for one of the sides instead.
def F(w, h):
    if w&1 and h&1: return 0
    if w<h: w,h = h,w

    r = 0
    x = 1
    while x**2 <= w*h:
        if (w*h)%x!=0 or x==h:
            x += 1
            continue

        if w%(w-x)==0 or x%(x-h)==0:
            r += 1

        x += 1

    return r

def G(N):
    s = 0
    for w in range(1, N+1):
        for h in range(1, w+1):
            s += F(w,h)

    return s

G(1012) would require far too long to solve regardless of how fast F is though. I think it's necessary to either use some kind of sieving algorithm where we loop through all x < 1012 counting how many (w,h) satisfy h <= w <= 1012, x|(w*h), x != h and (w-x)|w or (x-h)|x.
I think an O(n2/3) algorithm must be possible... but I'm stuck here!

Edit: I don't have access to the forum since I am unable to solve it. That's why I'm asking for help. I have completed most other questions and want to tackle this question now!
Edit 2: I think considering the areas by prime factors is a dead end. That's because there are 1024 different areas. Rectangles with prime areas have 0 solutions, rectangles with semiprime areas have 1 solution if one of the primes is 2 otherwise they have 0 solutions. But counting all the semiprime solutions alone would take too long since we'd need to count all the primes p such that 2*p < 1024 which is not feasible.
Edit 3: I've stripped down the code:
def G(N):
    s = 0
    for x in range(1, N):
        for h in range(1, N+1):
            if x==h: continue
            for w in range(max(h, x**2//h), N+1):
                if (w*h)%x==0 and x%(w-x)==0 and x%(x-h)==0:
                    s -= 1

    for x in range(1, N):
        for h in range(1, N+1):
            if x==h: continue
            for w in range(max(h, x**2//h), N+1):
                if (w*h)%x==0 and w%(w-x)==0:
                    s += 1

    for x in range(1, N):
        for h in range(1, N+1):
            if x==h: continue
            for w in range(max(h, x**2//h), N+1):
                if (w*h)%x==0 and h%(x-h)==0:
                    s += 1

    return s

I don't think breaking the brute-force code down will work though. Remember it's enough that we just count the solutions (x, w, h) to each of these three subproblems. The last such summation would have the constraints 0 < x < N, 0 < h < N+1, x!=h, max(h, x2/h) < w < N+1, x|wh and x-h|h.
I think we should start with the assumption that some prime p divides x, w, h or even x-h and then see what we can deduce about the other variables. If that works well, maybe consider pk for arbitrary k.

A: I don't have a solution yet, but something interesting for Python. I realized that Python can be used as a convenient tool for notation of algorithms! Basically I wrote down a program similar to yours and started transforming the program logically which leave the results unchanged. I came up with
def order(x,y):
    if x>=y:
        return (x,y)
    else:
        return (y,x)

N=1000
num=set()
for n in range(1, N+1):
    for a in range(1,N//n+1):
        for b in range(1,N//(n+1)+1):
            if a==b: continue
            num.add((order(a*n,b*(n+1)), order(b*n,a*(n+1))))

print(N, len(num))

Obviously brute force or even a simple loop over 10^12 is not feasible, but maybe with this algorithm one can find a closed form expression at some point. If it wasn't for the set character of num, it would be doable. Maybe one can find duplicate point this way.
This could be a dead end, but still it's pretty cool that Python can be used for notation and work with algorithms :)
Any progress on your side?


text:
Q: C# And MongoDB Create DB from Code Hi Im Trying to create a DataBase in MongoDB from C# code This is the code Im Useing
    public partial class SqlToMongo : Form
{
    public SqlToMongo()
    {
        InitializeComponent();
        connectToMongo();
    }
    public void connectToMongo(){
        var con = "mongodb://127.0.0.1";
        MongoClient client = new MongoClient(con);
        var db = client.GetDatabase("BetsOdds");
      bool d =  db.RunCommandAsync((Command<BsonDocument>)"{ping:1}")
    .Wait(2000);
        var Betsodds = db.GetCollection<BetOdds>("Betodds");
    }
}

The ping return true when MongoService is running and false when the service is off, the code works.
I'm using RoboMongo as a GUI for MongoDB and after the code runs i still don't see the Database on the GUI. i need some help what i'm doing wrong
Thanks

A: The database will not show up in the list until you have added some data.  I have not used RoboMongo, but if you create a database in code, and then using the Mongo console to list the databases, you will not see anything.  Add some data and try again, the database will show up in the list of the 'show dbs' command.


text:
Q: How to get a cgitb traceback inside a try/except block? Usually it is advised to initialize cgitb at the beginning of a script with the function cgitb.enable().
But how can I do to use cgitb to format a special exception I catched in a try/except block, without registering cgitb as a global exception handler?
I suppose it would look like this:
import cgitb
try:
    1/0
except Exception as exc:
    print(cgitb.something(exc))

A: import cgitb
import sys
try:
    1/0
except Exception:
    print(cgitb.text(sys.exc_info()))


text:
Q: Show: $E(|X|)\leqslant\liminf_{n\to\infty} E(|X_n|)$

Let $X,X_n$ be random variables with $X_n\to X$ is distribution.
    Show
    $$
E(|X|)\leqslant\liminf_{n\to\infty} E(|X_n|).
$$

I call the probability space on which $X$ and $X_n$ are defined $(X,A,P)$. Then $X_n\to X$ in distribution means
$$
\lim_n \int f\, dP_{X_n}=\int f\, dP_X
$$
for all bounded and continious functions $f\colon\mathbb{R}\to\mathbb{R}$, right?
Do not know how continue...

A: If the absolute value function were bounded, this would be easy.  It's not, but we can approximate it by bounded continuous functions.
Let $\phi_k(x) = |x| \wedge k$.  Notice that $\phi_k$ is bounded and continuous, that $\phi_k(x) \le |x|$, and as $k \to \infty$, $\phi_k(x) \uparrow |x|$ pointwise.  Fix $k$ for the moment.  Now for each $n$ we have $$E \phi_k(X_n) \le E |X_n|.$$
Passing to the limit as $n \to \infty$ we have
$$\liminf_{n \to \infty} E \phi_k(X_n) \le \liminf_{n \to \infty} E |X_n|.$$
But since $\phi_k$ is bounded and continuous, the convergence in distribution gives us $E\phi_k(X_n) \to E \phi_k(X)$, so $\liminf_{n \to \infty} E \phi_k(X_n) = E \phi_k(X)$.  Thus we have
$$E \phi_k(X) \le \liminf_{n \to \infty} E |X_n|.$$
Finally let $k \to \infty$ and use the monotone convergence theorem (or Fatou's lemma) on the left side:
$$E |X| \le \liminf_{n \to \infty} E|X_n|.$$

A: Assume that the assertion is wrong. Than there exists a subsequence $X_{n_j}$ such that $lim_{j\rightarrow \infty}E[|X_{n_j}|]<E[|X|]|]$.
Since $X_n \rightarrow X$ in distribution , there exists a subsubsequence such that $X_{n_{j_k}}\rightarrow X$ almost surely. Now Fatou implies that
$lim_{j\rightarrow \infty}E[|X_{n_j}|]=liminf_{k \rightarrow \infty }E[|X_{n_{j_k}}|]\ge E[liminf_{k \rightarrow \infty }|X_{n_{j_k}}|]=E[|X|]$,
a contradiction.
Edit: This is rubbish.


text:
Q: MongoClient not working when properties read from config file I have an issue while connecting to mongoDb from python3.
I have a configuration file where the host,username and password is provided and the data needs to be read from a configuration file. I am reading the configuration using ConfigObj. The problem is the following.
If I create the MongoClient using a static string then the client is working fine when I am calling cursor.next() but when the MongoClient is being created from the config file then I am getting the following error.
pymongo.errors.OperationFailure: Authentication failed.
Working Code.
client=MongoClient("mongodb://dummyuser:password@1.1.1.1:27071/default_db?authSource=auth_database",
maxPoolSize=10))

If I create a client in this format and later on from a function call global client and extact the documents using cursor.next() then it works fine. However if we use the following code.
client = MongoClient(host=configuration['host'],
                   port=27071,
                   username=configuration['user'],
                   password=configuration['password'],
                   authSource=configuration['auth_database']))

After creating a client like this if we are calling cursor.next() then I am getting the following error.
  File "basepath/lib/python3.7/site-packages/pymongo/helpers.py", line 159, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.

I am not able to understand what is changing. Please help me.
The config file is of the format.
[mongodb]

 [[connection]]
  host = 1.1.1.1
  port = 27071
  user = dummy_user
  password = password
  authentication_database = auth_data

and the dict read is ,
{'host': '1.1.1.1', 'user': 'dummy_user', 'password': 'password',  'authentication_database': 'auth_data', 'port': 27071}


text:
Q: Prove that a bounded sequence contains all of it's accumulation points Homework question:
Let {$x_n$} be a bounded sequence. Prove that the set of all subsequential limits of {$x_n$} is closed.
Any help would be appreciated.
(I edited this so that anyone who looks at this in the future will not get confused by my incorrect interpretation of the question. It now matches the second part of the solution, instead of both the second and the first).

A: The statement that if $(x_n)$ is bounded then $(x_n)$ contains all its accumulation points is false.
Take for example $x_n=1/n$. This is bounded, but zero is an accumulation point which is not part of the sequence.

If you ask to prove that the set of limit points is closed, this is true. If $y_n$ is a sequence of limit points which converges to $y$, then there exist terms $x_n$ in the sequence such that $|x_n-y_n|<1/n$. As a consequence
$$ |x_n-y|\leq |x_n-y_n|+|y_n-y| \to 0$$ so $x_n$ converges to $y$ which makes $y$ a limit point.


text:
Q: C++ Nested Primitive Type Templates I've been working on a pixel format and canvas system using templates with primitive type arguments, that is:
enum class PIXEL_FORMAT : char {
    PALETTE,
    RGB,
    RGBA
};

template<unsigned int bit_depth, PIXEL_FORMAT fmt> struct Pixel {};

//specializations for 8-bit, 16-bit, etc. RGB/RGBA formats

These all work perfectly fine, but when I attempted to create a Layer struct:
template< template<unsigned int depth, PIXEL_FORMAT fmt> class PixelType > struct Layer {
using pixel = PixelType<depth, fmt>;
pixel** pixels;

The errors I got were:
F:\Personal Projects (Java or Other)\C_C++\Independent\GUI Apps\FreeArt\Canvas.h|7|error: 'depth' was not declared in this scope
F:\Personal Projects (Java or Other)\C_C++\Independent\GUI Apps\FreeArt\Canvas.h|7|error: 'fmt' was not declared in this scope
F:\Personal Projects (Java or Other)\C_C++\Independent\GUI Apps\FreeArt\Canvas.h|7|error: template argument 1 is invalid
F:\Personal Projects (Java or Other)\C_C++\Independent\GUI Apps\FreeArt\Canvas.h|7|error: template argument 2 is invalid

So obviously I'm not understanding the way nested templates using primitive types as parameters work. I've looked for similar issues, but can't seem to find anything on using primitive types instead of regular template arguments (typename T, etc).
I'm hoping this can be used for other types with templates using primitive type arguments, for example a possible
template<template<unsigned int bit_depth, double samp_per_sec> class Sound> struct SoundEffect {};

A: If you want to use a single pixel type in a layer, then you need this:
template < typename PixelType > struct Layer {
   ...
};

using RGBA8Layer = Layer < Pixel<8, RGBA> >;

If you need to access bit_depth and format from within Layer, define static const members in either Pixel or in a separate "traits" template.
The construct you are trying to use is called "template template parameter". They are needed when you have potentially many templates with the same signature:
template <unsigned int bit_depth, PIXEL_FORMAT fmt> struct Pixel {};
template <unsigned int bit_depth, PIXEL_FORMAT fmt> struct FancyPixel {};
template <unsigned int bit_depth, PIXEL_FORMAT fmt> struct FastPixel {};
template <unsigned int bit_depth, PIXEL_FORMAT fmt> struct PackedPixel {};

and you wanted to use any of them with Layer, and you wanted to select depth and format from inside the layer, then you would use this:
template< template<unsigned int, PIXEL_FORMAT> class PixelType >
struct Layer {
    using MyNormalPixel = PixelType<8, RGB>;
    using MyHighDefinitionPixel = PixelType<16, RGBA>;
};

using FancyLayer = Layer<FancyPixel>;
using PackedLayer = Layer<PackedPixel>;

Notice how parameter names in PixelType are omitted — they cannot be used in the code at all. The only thing they are useful for is documentation. The situation is analogous to that of function arguments:
// signature off the top of my head
double integrate (double func(double),
                  double from, double to, double epsilon, double step);

Indeed, templates are in essence functions in the types domain and "template template parameters" are analogous to "function function parameters" like func above.


text:
Q: Instances in locale declaration for Isabelle I've declared a certain locale which fixes multiple things and am trying to declare a new locale for morphisms of the first. Here's the first locale:
locale presheaf = topology + Ring +
fixes
opcatopensets ::" ('a) PosetalCategory" and
objectsmap :: "'a set ⇒ ('a, 'm) Ring_scheme" and
restrictionsmap:: "('a set ×'a set) ⇒ ('a  ⇒ 'a)"
assumes
"opcatopensets  ≡ ⦇ Obj = {x. x ∈ T} , Mor = {(x,y)| x y. (x,y) ∈ revpo} ,
 Dom = psheafdom , Cod  = psheafcod , Id  = psheafid  , Comp = psheafcomp ⦈" and
"∀y w. w ≠ y ⟶ (psheafcomp (x,y) (w,z) = undefined)" and
"∀x. x ∉ T ⟶ (objectsmap x = undefined)" and
"∀x y.(restrictionsmap (x,y)) ∈ rHom (objectsmap x) (objectsmap y)" and
"∀ x y . (restrictionsmap (x,x) y = y) " and
"∀ x y z .  ( (restrictionsmap (y,z))∘(restrictionsmap (x,y)) = restrictionsmap(x,z) )"

At the end of this declaration, I get the following output:
locale presheaf =
  fixes T :: "'a set set"
    and R :: "('b, 'c) Ring_scheme"
    and opcatopensets :: "'a PosetalCategory"
    and objectsmap :: "'a set ⇒ ('a, 'm) Ring_scheme"
    and restrictionsmap :: "'a set × 'a set ⇒ 'a ⇒ 'a"
  assumes "presheaf T R opcatopensets objectsmap restrictionsmap"

So I thought I could extract from the last line what I needed in order to define a new locale involving two instances of the locale "presheaf". This is what I tried:
locale sheafmorphism =
F: presheaf T  R opcatopensets F restrictionsmap + G: presheaf T R opcatopensets
G restrictionsmap
for F and G  +
fixes morphism :: "'a set ⇒ ('a ⇒ 'a)"
assumes  (things)

In short, I want to fix two presheaves F and G and then fix this parameter "morphism" and assume things involving "morphism" and the "restrictionsmap" and "objectsmap" of F and G. This attempt of mine led to:

Illegal free variables in expression: "T", "R", "opcatopensets",
  "restrictionsmap"

I suppose I don't understand how to do this when the locale you want to instantiate fixes more than one thing. What is causing this error and how could I do what I'd like?

A: You can easily combine several instances of a locale into a new one, but you typically must rename the parameters of the locales and declare them accordingly with for. In your code, you only renamed the parameter objectsmap to F and G respectively, and added the prefixes F and G to refer to the two instances. However, the other parameters T, R, opcatopensets, and restrictionsmap have not been renamed and are missing in the for clause of the locale declaration. That is the reason for the error message. So you should add them to the for clause and it should work. However, both instances of the locale will use the same T, R, opcatopensets and restrictionsmap. If this is not what you intended, then you should rename them, too.
For example, the following declaration
locale sheafmorphism =
  F: presheaf T1 R1 opcatopensets1 F restrictionsmap1 +
  G: presheaf T2 R2 opcatopensets2 G restrictionsmap2
  for T1 R1 opcatopensets1 F restrictionsmap1
      T2 R2 opcatopensets2 G restrictionsmap2 +
  fixes morphism :: "'a set ⇒ ('a ⇒ 'a)"
  assumes ...

renames all arguments of the two instances. In contrast, the following only renames the morphism to F and G.
locale sheafmorphism =
  F: presheaf T R opcatopensets F restrictionsmap +
  G: presheaf T R opcatopensets G restrictionsmap
  for T R opcatopensets F G restrictionsmap +
  fixes morphism :: "'a set ⇒ ('a ⇒ 'a)"
  assumes ...


text:
Q: listview databind alphabetical order I need to order my Category titles -
( <%#Eval("CategoryDescription").ToString().ToUpper()%>   )
Alphabetically.  How do I do this? Thanks!
Here is the code behind in C#:
    protected void lstvwFileCategory_OnItemDataBound(Object sender,
    ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem temp = (ListViewDataItem)e.Item;
            Files.HAHADocument_Category catdata =
            (Files.HAHADocument_Category)temp.DataItem;

            ListView files = new ListView();
            files = (ListView)e.Item.FindControl("lstvwFiles");

            files.DataSource = catdata.Documents;
            files.DataBind();
        }
     }

Here is the code itself:
     <asp:ListView runat="server" ID="lstvwFileCategory"
     OnItemDataBound="lstvwFileCategory_OnItemDataBound">
          <LayoutTemplate>
              <asp:Literal runat="server" ID="itemPlaceholder" />
          </LayoutTemplate>
          <ItemTemplate>

<%#Eval("CategoryDescription").ToString().ToUpper()%>

                    <asp:ListView runat="server" ID="lstvwFiles"
                    OnItemDataBound="lstdvwFiles_OnItemDataBound">
                         <LayoutTemplate>
                             <asp:Literal runat="server" ID="itemPlaceholder" />
                         </LayoutTemplate>

          </ItemTemplate>
     </asp:ListView>

and
 if (PageID > 0)
    {
        HAHA_BLL.FileRepository.Files fls = new HAHA_BLL.FileRepository.Files();
        lstvwFileCategory.DataSource =
        fls.GetHAHADocument_Categories((int)PageID);
        lstvwFileCategory.DataBind();
    }

A: Add using System.Linq; at the top of the code behind file, then change the data source assignment to this:
lstvwFileCategory.DataSource = fls.GetHAHADocument_Categories((int)PageID)
                                    .OrderBy(c => c.CategoryDescription);


text:
Q: "Four plus two equals six" (or "is equal to six" or "is six") You write

4 + 2 = 6

and say "four plus two equals (or is equal to or is) six."
In the question "Is equal to" or "equals", I read the following comment:

Equals is equal being a verb, in the present tense. Is equal to is equal being a predicate adjective, with its auxiliary verb in the present tense. English is full of pairs like this, useful if one needs an extra syllable. [...] – John Lawler Jun 16 at 16:18

I am thoroughly confused about the bit "Is equal to is equal being a predicate adjective, with its auxiliary verb in the present tense". Is the verb in the present tense the word is? and is to the predicate with the adjective being equal?
Also, does the word is represent a verb in the present tense in the phrase, "four plus two is six"?
Finally, could you please provide another example that is useful if one needs an extra syllable.
Yes, I understand that they all mean the same thing. What I'm looking for is a grammatical syntax analysis with more examples, since, as John Lawler says, "English is full of pairs like this, useful if one needs an extra syllable."
(As an aside, I once read that this symbol "=" is called an "equals sign" in British English and is called an "equal sign" in American English. A related post can be found here.)

A: If one wants a complete grammatical analysis, one should be prepared for the view that be equal to is a transitive multi-word verb, a single lexeme.
("A lexeme is a unit of lexical meaning, which exists regardless of any inflectional endings it may have or the number of words it may contain. Thus, fibrillate, rain cats and dogs, and come in are all lexemes, as are elephant, jog, cholesterol, happiness, put up with, face the music, and hundreds of thousands of other meaningful items in English. The headwords in a dictionary are all lexemes."
(David Crystal, The Cambridge Encyclopedia of the English Language, 2nd ed. Cambridge University Press, 2003) )
The fact that is equal to etc can readily be substituted by equals etc strongly supports the multi-word single-lexeme analysis. It then becomes arguable whether it is helpful to try to analyse within the fixed expression (along the lines: is equal more closely bound to the 'verb' or the 'preposition'? if the 'adjective'-'preposition' binding is tight, is to better analysed as a particle?).
Of course, the verb-form is not invariant: So, the left-hand side must be equal to the right-hand side.
Also, be equal to meaning measure up to (the demands of) is not synonymous with equal:
Do you think he is equal to the task?
*Do you think he equals the task?

A: The word "equal" has three parts of speech: noun, verb, and adjective.

*

*

four plus two equals six

In your first example sentence, "equal" is being used as a verb in the third person singular form: equals.

*

four plus two is equal to six

In your second example, "equal" is being used as an adjective, and so it needs to employ a linking verb (in this case, "be" or "is") before it. The "to" after it is a preposition.

*

four plus two is six

Finally, here "is" is again a linking verb in an S + LV + C pattern (Subject + Linking Verb + Complement).

A: I'm not entirely sure what the question or questions are, but in the sentence X is equal to Y, is is a lexical, not an auxiliary, verb. Equal is an adjective acting as the subject predicative. To Y is a prepositional phrase acting as the complement to equal.

A: The entire phrase "is equal to" is a predicate, not any part of it. A predicate describes a relationship between two things; in this case, that the first thing ("4 + 2") is related to the second thing ("6") by the first being equal to the second. A predicate describes a static truth, while a verb describes (loosely speaking) an action in progress.
Math makes this distinction especially confusing because math uses practical language to describe abstractions. An example that makes the difference clearer is:
(1) George tends the garden.
(2) George is the tender of the garden.
(1) describes something George does, while (2) describes something George is.

A: (bold means a verb, italic means a noun, parentheses mean a prepositional phrase, strikethrough means an adjective).

"Four (plus two) is equal (to six)" N-LV-A
"Four (plus two) is six." N-LV-N
"Four (plus two) equals six". N-LV-N

In the first sentence, "is" is a linking verb or copula. Here "equal" is an adjective, and the predicate of the sentence. The word "six" is the object of the prepositional phrase "to six", which functions as an adverb, modifying the word "equal".
In the second sentence, "is" is still a linking verb, but instead of an adjective, "six" is now the predicate of the sentence, which circumvents the necessity for a prepositional phrase.
Finally, the third sentence does not use "is" at all, but instead uses "equals" as its linking verb. It is more or less identical to the second sentence, but replaces "is" with a more colorful, more descriptive linking verb.

As a somewhat loose follower of the E-Prime philosophy--which in its strictest form mandates the omission of the verb "to be" and all of its conjugations--I would be most inclined to use sentence 3. A quote from the Wikipedia article on the use of "equals" rather than "is":

Replacing statements including "to be" with those using becomes, remains and equals divides perception of, and expressions about, time more operationally into actual cognitive categories that humans know how to act upon.
To claim that one thing equals another is a claim only about the present with no reference to the future or the past—it can be disproved by direct testing.

A:
Finally, could you please provide another example that is useful if one needs an extra syllable?

Well, it's actually two syllables –– len("is equal to")–len("equals") = 4–2 = 2.
An example:

Two bees or not two bees, that is the question;
          To risk a sting to get their sweet confection;
  But do not add a dozen to the scene;
          As twelve plus two is equal to fourteen.

Nonsense?  You bet it's nonsense.  But most modern poetry is –– am I right?


text:
Q: docker-entrypoint.sh: executable file not found in $PATH I was able to build a successful image out of the Dockerfile below but I failed to run the image and I get the error below even though I have copied the entrypoint.sh to the right location. Any pointers to fix this would be great.
Error: docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "docker-entrypoint.sh": executable file not found in $PATH: unknown.

ENV NODE_VERSION 12.22.6

COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]

CMD [ "node" ]

the docker-entrypoint.sh looks like below:
#!/bin/sh
set -e

if [ "${1#-}" != "${1}" ] || [ -z "$(command -v "${1}")" ]; then
  set -- node "$@"
fi

exec "$@"

A: I've seen this before.  Not sure how to fix it.
BUT, luckily, there is a 2nd format you can write that command in, for example:
ENTRYPOINT docker-entrypoint.sh node $TEST_VAR1 $TEST_VAR2


text:
Q: When I click my visited days, calendar opens on January 2014 As in topic, when I click in my profile on "visited" it shows up with a calendar but opened on January 2014, not like every other time on current month.
I'm using chrome atm.

In my opinion this issue is correctable, you can provide jQ calendar with current date taken from server, not from the local computer. And it's not unreproducable - you can reproduce it while changing computer's local date.

A: Given that the entire site is based upon UTC (in this case visited days are not based on local time days but on UTC days) it makes sense for the calendar to open such that the current stack exchange day is displayed, not the local day.
At present at month ends/starts it could occur that the calendar opens on a month before/after the true stack exchange month meaning your visit today is not displayed even if the user's local time is correctly set.
As such I support this being based on server time not local time

A: Getting the date from the server would give incorrect results because of time zones. The server could give you 2013-11-30 while in your location it's already 2013-12-01.
Depending on the client's date is correct.


text:
Q: Cannot open file after export as excel using PHPExcel
When i download and open file excel using phpexcel

A: Just to write ob_clean() before phpExcel save function
For Example
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'excel5');
ob_clean();
$objWriter->save("abcd.xls");


text:
Q: Is it against the rules to hand out gift codes for our game on the App Store? After publishing an app on iTunes you get 50 promo codes to hand out to users. This usually runs out pretty quickly. We thought we may be able to circumvent this by gifting the app to certain users using a US iTunes gift card. Does anyone know if this is against the App Store policy in any way? I read through the terms and conditions and didn't see anything about it.
Thanks

A: Apple will get their 30% cut, so there should be no problem with that idea.

A: I think you're confusing gift cards and promo codes.
Gift cards are paid in advance using real money, so Apple gets 30% of the gift card value up front.
Apps bought using gift cards can receive customer reviews.
Promo codes are totally free, nobody earns anything.
Apps received using promo codes can not receive customer reviews.

A: You can't give away iTunes Gift Cards to promote your App. I wanted to do this on Twitter and Facebook to interact with the users, so I decided to contact Apple to make it all clear. Here is the reply:
Thanks for reaching out.

Unfortunately, iTunes Gift Cards, iTunes Codes or Apple product cannot be given out in conjunction with app promotions. That said, you'll need to find an alternate incentive/gift for the program.

Best regards,
Promo Review

You can contact Apple on on this email: promoreview@apple.com


text:
Q: Is it possible to do Battle Frontier through local DS wifi? I've played the Battle Frontier both alone and online play, but I've never played it locally.
Mostly, I'm interested in playing with my girlfriend, who has Diamond, while I have SoulSilver. Are we able to do the battle tower with each other? Also, there's like an arcade battle room in the Battle Frontier in SoulSilver with a game board - does that exist in Diamond?
Where do we go to run through Battle Tower? Is there anything we can't do together because it's not in Diamond?
(Sorry if the question is worded poorly, I haven't played DPPt and am not sure what features it does or doesn't have compared to HGSS)

A: You can play Battle Frontier matches (including Battle Tower) with others through local wifi (mostly double battles), but Diamond and Pearl can only join in on Battle Tower matches, because the complete battle frontier wasn't included until Platinum.


text:
Q: How to use Git when editing existing projects? Here's the situation. I have a commercial application developed in PHP. I'll have to add features to it, but none of the original files will be touched. I need to work ONLY on my new files. How do I manage this situation in Git?
In my gitignore I specified * to ignore everything and a negation ! for my new files, but it's really boring. I don't want to add a new line to gitignore everytime I create a new file.
Any solution?
PS: this script don't support plugins so is not a solution to just "git init" my plugin folder. Anyway It's developed using MVC so I'll be adding controllers and views.

A: You might consider a local pre-commit hook.
That hook can:

*

*list of the files about to be committed

*check the last committer: git log -1 --format=%cn -- afile: if this is not you, exit -1: the hook will block the commit.

If you haven't touched (committed) any other files yet, that hook will ensure you would be working only on your new files.


text:
Q: Sharing some XML between layouts I want to make something that is a vertical LinearLayout on the phone version of an app, a horizontal one for tablets.
The view in question is located inside a large XML file that specifies the entire view.
The naive way to do this is to just copy and paste the file from res/layout to res/layout-sw600dp. I did this and it works. However this means I know have to maintain two files if I want to make other UX changes. This is inefficient.
What is the easiest way to abstract away the LinearLayout in question?
I have looked at Custom Components but it goes farther than I would like to go. I do not want to have to make code changes for this, it should be self-contained in XML changes.

A: You can reuse layouts using < include > and < merge> tags.
Doing that, you can have different containers in sw600dp and layout folders including the same common layout.
Official doc here


text:
Q: How to save the text in textfield in swift? I have a tableview consisting of 2 cells and each cell has a textfield. I'd like to hold the text in textfield in an another variable and append it into an array but it just save the second cell's textfield's text into the variable and doesn't append the array.
Here is cellForRowAt code :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == queryTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: queryCellReuseIdentifier,
                                                   for: indexPath) as! queryCell

            cell.selectionStyle = UITableViewCell.SelectionStyle.gray

            queryTextField = UITextField(frame: CGRect(x: 20, y: 0, width: 300, height: 20))
            queryTextField.delegate = self
            queryTextField.placeholder = "Soruyu buraya giriniz"
            queryTextField.font = UIFont.systemFont(ofSize: 15)
            cell.addSubview(queryTextField)

            return cell

        }

Here is my related function :

  func textFieldDidEndEditing(_ textField: UITextField) {
        var temp = queryTextField.text!
        queryArray.append(temp)

        print(temp)

    }

A: if your project is non-storyboard approach, then I would say, it would be more easier and flexible to take control of each type and data and action since sometimes things not quite flexible with storyboard only.. . as you create, even a single UIElement, UI conforms to those properties, methods and actions which you define, means fully customized code  - custom defined code base..
now to your question, according to what you did, probably, your textfield text is overwritten to blank, losing the previously entered value every time the cell is  dequeued, cell is generated fresh again for use every time " dequeue cell " method is executed, if you want to persist your previous value, I would say,  " remind the dequeued cell that it had some value before being re- dequeued again " means:

*

*declare your global array or dict.

*dequeue your cell and setup your cell properties
3 after cell is dequeued, do something like this, and your cells previous value is saved even after the cell is dequeued.

example, common approach:
struct DefaultInfo {
     var string: String?
     var type: SomeData? //optional
}

 let array: [DefaultInfo] = []

 var array = self.array[indexPath.row]

 // after cell is dequeued:
 switch array.type {
        case .someCase:

          let string = cell.textField.text
          array.string = string
          cell.textField.text = array.string
          //print(array.string!)
          // now you should be able to see your input after cell is
          //renewed.. . try it.. .

       default: break
  }

A: It seems like you have an independant variable queryTextField which is overriden when you create the second cell.
Also, in textFieldDidEndEditing try accessing textField instead of queryTextField, like this:
func textFieldDidEndEditing(_ textField: UITextField) {
     var temp = textField.text!
     queryArray.append(temp)

     print(temp)
}

Responding to this:

I need every cell has its textfield and I need to be able to save
  their texts into an array. After that I am going to send them to web
  service. To sum up, they will be my parameters.

*

*You don't need to have global queryTextField just for that. You can remove this variable, if that's its only goal.

*Do you need to send web request on some trigger? Like button tap. I assume, yes.

*Since theoretically not all your cells are visible at the same time (e.g. when thay do not fit the screen), it's bad idea to try and track texts in text fields. Instead, you need some kind of model to store all texts (paired with indeces, maybe). The simplest would be dictionary where key is cell identifier (e.g. indexPath) and value is the text.

*In textFieldDidEndEditing you can report the changes to the view controller. For this you need to assign the cell as the delegate for its text field. And view controller - as the delegate for the cell. In  textFieldDidEndEditing cell would be calling view controller delegate method to report the text change, passing (for example) self and text as parameters. View controller would then be able to find its index path and store the text in the model (dictionary).

*On trigger (button click?) view controller will be able to build parameters from the model (dictionary).

Consider this pseudocode as a direction:
cellForRow {
  ...
  cell = ...
  let textField = ...
  textField.delegate = cell
  cell.addSubview(textField)
  cell.delegate = self
}

In cell:
textFieldDidEndEditing(textField: UITextField) {
  delegate?.report(text: textField.text ?? "", in: self)
}

In view controller:
report(text: String, in cell: UITableViewCell) {
  let indexPath = tableView.indexPath(of: cell)
  model[indexPath] = text
}


text:
Q: Python3 - Как запустить строннее приложение в отдельном терминале и ждать его завершения? Нужно запустить отдельное приложение в отдельном терминальном окне и ждать его закрытия. Делаю так:
result = subprocess.run(["xfce4-terminal", "-e", "./etherdump.sh"], capture_output=True)

пофигу, все стартует в отдельном окне, но и выполненеи скрипта идет дальше. Как мне заставить скрипт ждать закрытия терминала в таком случае?


text:
Q: Where to call setState to update graph I'm struggling to get a graph widget to rebuild when the underlying data is changed. I have tried setState in a few different spots and can't figure it out.
Any ideas?
Data is stored in class:
class SensorReading {
  SensorReading({
    required this.timestamp,
    required this.value,
});

  DateTime timestamp;
  double value;

}

class Sensor {
  Sensor({
  });

  List<SensorReading> readings = [];
}

I'm listening to some data coming in from bluetooth and adding readings.
  await c.setNotifyValue(true);
  c.value.listen((value) {
    setState(() {
        sensor.readings.add(SensorReading(timestamp: DateTime.now(), value: value));
    }
  }

The main widget contains a graph widget. The graph widget will only update when I force a redraw by rotating the screen or similar.
 @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Sensor readings'),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: SfCartesianChart(
                  primaryXAxis: CategoryAxis(),
                  // Chart title
                  title: ChartTitle(text: 'Live stream'),
                  // Enable legend
                  legend: Legend(isVisible: true),
                  // Enable tooltip
                  tooltipBehavior: TooltipBehavior(enable: false),
                  series: <ChartSeries<SensorReading, DateTime>>[
                    LineSeries<SensorReading, DateTime>(
                        dataSource: widget.sensor.readings,
                        xValueMapper: (SensorReading reading, _) => reading.timestamp,
                        yValueMapper: (SensorReading reading, _) => reading.value,
                        name: 'Temp',
                        // Enable data label
                        dataLabelSettings: DataLabelSettings(isVisible: false))
                  ]),
            ),
        ]
    )
}


text:
Q: Getting a TypeError using the useRef hook..."null is not an object" Hello react developers.
So I'm putting together an app for a client. Client wants a page that plays a video (no sound, plays inline) when the video is in view in the viewport, and it pauses when the video is out of viewport. So I made a custom hook to do this. Here's my code (ignoring the imports, which are just useRef and useEffect):
const usePlayVideo = options => {
const wrapperRef = useRef(null);
const videoRef = useRef(null);
const handleVid = entries => {
    const [entry] = entries;
    if (entry.isIntersecting) videoRef.current.play();
    else videoRef.current.pause();
    };
useEffect(() => {
    const wrapper = wrapperRef.current;
    const observer = new IntersectionObserver(handleVid, options);
    if (wrapper) observer.observe(wrapper);
    return () => {
        if (wrapper) observer.unobserve(wrapper);
    };
    }, [wrapperRef, options]);
    return [wrapperRef, videoRef];
};
export { usePlayVideo };

Then, in the component, i import the hook and use it like so:
function ClientAsk() {
    const [wrapperRef, videoRef] = usePlayVideo({
        root: null,
        rootMargin: "0px",
        threshold: 0.3,
    })

    return (
        {/* bunch of other divs and stuff */}
        <div className="grid_s_start_3 grid_s_span_20" ref={wrapperRef}>
            <video ref={videoRef} id="video" playsInline muted preload="auto" loop style={{ width: "100%" }}>
                <source src={ClientVid} type="video/mp4" />
            </video>
        </div>
        {/* rest of other divs and stuff */}
        );
}

export default ClientAsk;

And that's that.
In browser on my dev environment, this works GREAT! Works as intended! I'm thrilled.
But I try it out on my iPhone, using iOS Safari, and it also works...UNTIL I return to the previous page while the video is playing.
So, there's a "< Back" link at the top of the page. When the video is not playing (i.e., I didn't scroll down far enough, or I scrolled past the video and it paused), the app goes back to the previous page, no problem!
BUT if I stop scrolling at the video, and it's playing, and I press the back button (or the Safari browser's back button), I am greeted with a dev error:
TypeError: null is not an object (evaluating 'videoRef.current.pause')
handleVid
src/hooks/usePlayVideo.js:8
5 | const videoRef = useRef(null);
6 | const handleVid = entries => {
7 | const [entry] = entries;
> 8 | if (entry.isIntersecting) videoRef.current.play();
| ^ 9 | else videoRef.current.pause();
10 | };

Now, I THINK I know WHY this is happening...however, I simply cannot figure out how to fix this or make the error stop happening. I was wondering if anyone has any tips for this? Am I using the wrong hooks in my custom hook? Should I not use "null" as my default for useRef? Is this only an iOS issue?
Any help would be appreciated.
Thank you!

A: So the issue was that this line of code returned a value of null that caused an error when returning to the previous page:
const handleVid = entries => {
    const [entry] = entries;
    if (entry.isIntersecting) videoRef.current.play();
    else videoRef.current.pause();
};

Per @Zac above, the reason for that is because the videoRef constant is always a true value as written, and its current value can be false (null in this case).
So, I rewrote it per his advice, as follows, wrapping the handleVid function in an if (videoRef.current) condition:
if (videoRef.current) {
   if (entry.isIntersecting) videoRef.current.play();
 else videoRef.current.pause();
 };

This addresses the TypeError on Safari, and no longer shows up when returning to the previous page.
Thank you very much for your help!


text:
Q: vertex coloring of a graph $G$ such that colors appear twice
*

*Let $G=(V,E)$ be a graph whose vertices can be colored with $m$-colors, such that each color appears at least twice.

*Let $\lambda(G)$ denote the minimum number of colors needed for a vertex-coloring of $G$

Use 1. to prove that such a coloring can be achieved with $\lambda(G)$ colors

Let $\alpha$ denote a coloring with property 1. and $\beta$ a coloring with $\lambda(G)$ colors. $\beta$ has a color class with only one vertex if $\beta$ doesn't have property 1.
I don't know how that helps to prove that such a coloring can be achieved with $\lambda(G)$ colors
Edit: A coloring of the graph $G$ is a proper coloring. $u,v$ have different colors if $(u,v)\in E$
Would appreciate any help

A: Call the given coloring with at least two vertices of each color a friendly coloring.
Now start with the coloring that uses the minimal number of colors. If every color is used twice we are done. If not, pick a vertex with a lonely color, look up the vertices that share its color in the friendly coloring and repaint them with the lonely color. Repeat as long as there are lonely vertices.
It is clear that this always gives an admissible coloring and that it does not increase the number of colors. But the procedure must stop because a repainted vertex will not be repainted again. So we end up with a friendly minimal coloring.


text:
Q: Pig Java UDF: Generating a bag from a tuple I am hoping someone can help me create a java UDF that will take this input spread across three text files:
Montreal, 5 3 10 9 8
Toronto, 7 2 2 3 4 4
Edmonton, 3 3 1 1 7
Montreal, 2 2 9

and return the following output bags:
{(Montreal,5),(Montreal,3),(Montreal,10),(Montreal,9),(Montreal,8),(Montreal,2),(Montreal,2),(Montreal,9)}
{(Toronto,7),(Toronto,2),(Toronto,2),(Toronto,3),(Toronto,4),(Toronto,4)}

I am fairly new to java and any help you can provide is greatly appreciated. Thank you.

A: If you're using pig 0.14 or after that supports STRSPLITTOBAG, then
A = load 'test.input' using PigStorage(',') as (place:chararray, numbers:chararray);
B = FOREACH A GENERATE place, FLATTEN(STRSPLITTOBAG(numbers)) as number;
C = FOREACH B GENERATE place, (chararray) number;
D = GROUP C by place;
E = FOREACH D generate C; -- dropping group field
dump E;

Output
({(Toronto,2),(Toronto,2),(Toronto,7),(Toronto,4),(Toronto,4),(Toronto,3)})
({(Edmonton,7),(Edmonton,1),(Edmonton,1),(Edmonton,3),(Edmonton,3)})
({(Montreal,9),(Montreal,2),(Montreal,2),(Montreal,8),(Montreal,9),(Montreal,10),(Montreal,3),(Montreal,5)})


text:
Q: Grouping results of SELECT but keep some values unique I have a SQL table like this
year    tour     wins    cuts   money
1990     EUR       2         4    54,500
1990     USA       1         2    22,000
1991     EUR       4         2    154,000
1991     USA       2         1    245,000
and so on

I wish to GROUP the results by YEAR, summing up the wins and cuts
HOWEVER, I wish to keep the money column alone, and return both values, from each YEAR row, like moneyEUR and moneyUSA (based on the TOUR column)
I am currently doing a SELECT like this
SELECT year, SUM(wins), SUM(cuts), money FROM players GROUP BY year

This GROUPS fine by year, but just returns the first money value.
Is there a way I can also return each money value as separate values?
and still SUM up the other values per year?

A: If you have always exactly 2 records for each year then you can do
SELECT year,
       SUM(wins),
       SUM(cuts),
       sum(case when tour = 'EUR' then money end) as moneyEUR,
       sum(case when tour = 'USA' then money end) as moneyUSA
FROM players
GROUP BY year

A: select t1.tour, t1.money, t1.year, t2.wins_sum, t2.cuts_sum
from players t1
join (
    select year
    sum(wins) wins_sum,
    sum(cuts) cuts_sum
    from players
    group by year
) t2 on t1.year = t2.year


text:
Q: Alternative to jQuery livequery plugin? I need to check when an element is alive, I'm doing:
$('#obj').livequery(function() { ... });

How can I do it with live method or another way?

A: This is an old question, but for the record, here my 5 cents:

An alternative to livequery is to use a Publish/Subscribe approach with for example this implementation
jQuery Tiny Pub/Sub: A really, really, REALLY tiny pub/sub implementation for jQuery.
I use it, for example, in this way:
// inform of DOM change (mostly through AJAX)
$.publish("/table/loaded");

// re-execute plugin
$.subscribe("/table/loaded", function(e, data) {
    $("#my_id input[name='date']").datepicker();
});

+info : Understanding the Publish/Subscribe Pattern for Greater JavaScript Scalability

A: If it is your code that is adding the element to the DOM, then run your code on it when you create it:
$('body').append('
some new object
');

var obj = $('#obj');

obj.runSomeCode();

...or you can even do it before it is appended:
var obj = $('
some new object
');

obj.runSomeCode();

obj.appendTo('body');

A: As an alternative to the livequery plug-in you might look at the $.whenLive jQuery plugin:
$.whenLive allows you to track the DOM tree insertion of one or more elements.
http://bitcubby.com/tracking-the-insertion-of-javascript-components-into-the-dom/
Here is an example from that page:
var widget = $("
I am a nobody. Nobody is perfect. Therefore, I am perfect.
");
$(widget).onLive(function() {
    // Awesomesauce.
    var height = $(this).height();
    var width = $(this).width();
});
$("body").append(widget);

A: It's an old question but I'm astonished there is no answer as it's simple. You have to use on() and attach the event to a parent or body. Ex :
$('#obj').livequery('click', function() { ... });
$('#obj').livequery(function() { ... });

become
$('body').on('click', '#obj', function() { ... });
$('body').on('DOMNodeInserted','#obj', function() { ... });

note that DOMNodeInserted is IE9+


text:
Q: Increase Elasticsearch maximum dimensions for sparse vectors Using sparse vectors in elastic search has two dimensional limits. On the one hand, vectors should not have more than 1024 elements.
This can be solved, as seen in this question.
The second limit is not the number of elements in one sparse vector, but the dimension of the elements. For example, if we have 20 dimensions, we could have this two vectors:
v1 = {"1": 0.01, "7": 0.2, "0": 0.4}
v2 = {"19": 0.02, "11": 0.7}

with only 3 and 2 elements each. Note that keys range from 0 to 19, as strings.
These dictionary keys (sparse vectors are given as dictionaries to json) are integers encoded as strings, and cannot go beyond the funny number 65535.
I am guessing this might have something to do with the default limit for file descriptors, which is 65535 as well, which I think is too suspicious to be unrelated.
Are these problems actually related? And is it possible to bypass the limitation for sparse vectors? In my case the dimension of the sparse vectors is given from a vocabulary, so reducing it will harm results (I am not so worried about query performance, though.)

A: They actually increased the number of dimensions from 500 to 1024 in the past in order to satisfy requirements for larger models. The only way to increase the limit higher is by editing this configuration and installing from source.
Not sure about the dictionary key issue.
However, in my experience the dense vector search in Elasticsearch is very slow, so I created an out-of-the-box platform for improving search relevance with SOTA models called NBoost.
Hope this helps!


text:
Q: How to open trim audio panel in IMG.LY I woud like to open audio trim editor in VideoEditor IMG.LY from my action. How can I do this?
Native implementation works but before that I must to open separate display and select audio from audio list. I would like set my audio file and open with file trim audio feature immediatly.

A: To skip the audio selection dialog in VideoEditor IMG.LY and set the audio track, you can use the following code:
    settingsList.configure<AudioOverlaySettings> {
        it.audioOverlay = AudioTrackAsset(...)
}

However, if the user removes the audio track, the audio selection dialog will reappear. To prevent this, you can remove the delete button from the UiConfigAudio.quickOptionList.


text:
Q: How can I see the tether coming to the address? what I want to do is a bot that sends a signal to myself when there is a token coming to my wallet address. But in the fiction I want to do, I want to pull the latest transactions of the address with trongrid and send a notification to myself if the money has come from there, but I have no idea how to do it. How do I access the inside of raw_data_hex and find out what's going on there?
import requests
import binascii
from struct import Struct

walletAddress = "walletAddress"

url = f"https://api.trongrid.io/v1/accounts/{walletAddress}/transactions?only_confirmed=true&only_to=true&limit=25"

headers = {"accept": "application/json"}

response = requests.get(url=url, headers=headers)

for transaction in response.json()["data"]:
    raw_data = binascii.unhexlify(transaction.get("raw_data_hex"))
    print(raw_data[:255].decode("iso-8859-1"))
```


text:
Q: C# capture pressed gamepad keys (Direct Input) How to capture pressed gamepad keys (Direct Input) in C#?
I have searched but most of the sources seem outdated, will there be a simple API that allows me to capture these events?
I am making an app that captures all the keystrokes on a gamepad but I have no idea how to start.

A: You can use XNA or MonoGame. They have simple API to detect pressed keys.
For example
https://learn.microsoft.com/en-us/previous-versions/windows/xna/bb197001(v=xnagamestudio.42)


text:
Q: How to rotate the existing content of HTML5 canvas? Is there a way to rotate the existing content of HTML5 canvas by Javascript? I know it's possible to rotate an image that will be drawn on to canvas, but I want to rotate the content that has been drawn on to canvas, for example, a 200x200 corner of a 400x400 canvas, or any specific region of an existing canvas.
Same question to scale the existing canvas content...
I know getImageData/putImageData provide a potential to transform the pixel array, but it's just too slow and inefficient.

A: If you first want to draw on a canvas and then rotate it for use on e.g. corners, you can to that when you "clone" the canvas or by using CSS.
Examples
Get the first canvas element:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

draw on it:
ctx.fillStyle = 'blue';
ctx.fillRect(0,0, 25, 5);
ctx.fill();
ctx.fillStyle = 'red';
ctx.fillRect(25, 0, 25, 5);
ctx.fill();

clone it to another canvas (that is rotated by CSS):
var ctx2 = document.getElementById("canvas2").getContext("2d");
ctx2.drawImage(canvas, 0,0);

or rotate the canvas while you "clone" it:
var ctx3 = document.getElementById("canvas3").getContext("2d");
ctx3.rotate(Math.PI/2);
ctx3.translate(0,-50);
ctx3.drawImage(canvas, 0,0);

here is the CSS for rotating it:
#canvas2 {
    -webkit-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -ms-transform:rotate(90deg);
}

Here is the full example:
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0, 25, 5);
    ctx.fill();
    ctx.fillStyle = 'red';
    ctx.fillRect(25, 0, 25, 5);
    ctx.fill();

    var ctx2 = document.getElementById("canvas2").getContext("2d");
    ctx2.drawImage(canvas, 0,0);

    var ctx3 = document.getElementById("canvas3").getContext("2d");
    ctx3.rotate(Math.PI/2);
    ctx3.translate(0,-50);
    ctx3.drawImage(canvas, 0,0);

}
</script>
<style>
#canvas2 {
    -webkit-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -ms-transform:rotate(90deg);
}
</style>
</head>
<body>
<canvas id="canvas" width="50" height="50"></canvas>
<canvas id="canvas2" width="50" height="50"></canvas>
<canvas id="canvas3" width="50" height="50"></canvas>
</body>
</html>

A: It's pretty easy to do with a temp canvas.
Live Demo
Live Demo Animated (just for the heck of it)
The above example draws 2 boxes, then rotates and scales from 0,0 to 200,200
var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = canvas.height = 400;

// fill the canvas black, and draw 2 boxes
ctx.fillStyle = "#000";
ctx.fillRect(0,0,400,400);
ctx.fillStyle = "rgb(255,0,0)";

ctx.fillRect(10,10,190,190);
ctx.fillStyle = "rgb(255,255,0)";
ctx.fillRect(250,250,90,90);

// Create a temp canvas to store our data (because we need to clear the other box after rotation.
var tempCanvas = document.createElement("canvas"),
    tempCtx = tempCanvas.getContext("2d");

tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
// put our data onto the temp canvas
tempCtx.drawImage(canvas,0,0,canvas.width,canvas.height);

// Append for debugging purposes, just to show what the canvas did look like before the transforms.
document.body.appendChild(tempCanvas);

// Now clear the portion to rotate.
ctx.fillStyle = "#000";
ctx.fillRect(0,0,200,200);
ctx.save();
// Translate (190/2 is half of the box we drew)
ctx.translate(190/2, 0);
// Scale
ctx.scale(0.5,0.5);
// Rotate it
ctx.rotate(45*Math.PI/180);
// Finally draw the image data from the temp canvas.
ctx.drawImage(tempCanvas,0,0,200,200,10,10,190,190);
ctx.restore();


text:
Q: Problems with AMD drivers I have the exact same problem as this user, but it only freezes under too heavy load, e.g. when I try to run the installer. I have a HP Pavilion 15-aw027no. After trying multiple USB's with no luck, I went on to DVD-RW's. This worked perfectly (almost), no freezing or crashing, but now whenever I try to install, I get this:
[Errno 5] input/output error

Tried a different DVD, same output. I've tried 4 different DVD's, all with no luck. I've tried to run Memtest86+ to test my RAM for errors, but it returned negative. I tried to run sudo fsck -cc /dev/sda6 to test the part of my SSD which I'll be installing Ubuntu onto for bad blocks. It returned almost 300 errors. I then tried to install in the same session, hoping it would avoid the bad blocks, but this didn't seem to be the problem. Errno 5. I tried HP diagnostics (F2 during boot) extensive system test, no errors, even though fsck returned so many errors. I tried again after all this, but I keep getting the same errno 5.
Also, I checked the MD5SUMS, SHA1SUMS and SHA256SUMS of the ISO I was using, and they all matched the ones on the website.
UPDATE:
Installation with bootable USB worked after adding nomodeset to the grub entry, but now nomodeset is present in the installed version of Ubuntu (the one on my internal drive). Whenever I try to remove nomodeset from the grub entry, Ubuntu becomes very unstable and freezes. The net time I reboot the system, I get this screen
I then booted from my bootable USB, executed sudo fsck -cc /dev/sda6 and got this output. The problem now is, I'm back to where I started. nomodeset is enabled again, and when I try to remove it again, same thing happens.
UPDATE 2:
Well, I didn't quite solve the problem, but I found the cause. I've been trying to install the fglrx-drivers, but I eventually found out that they aren't supported after ubuntu 14.04, so I went on and installed that. This time it didn't run in basic video mode, but it kept being unstable, and crashed all the time, so I tried to install fglrx, but no luck. I couldn't log in, I was stuck in a login-loop, where it would keep logging me out (this happened with the drivers downloaded form AMD's website too), so I pressed ctrl + alt + f1 and logged in through the shell. By looking in some log files, and searching the web, I found out that my GPU (which is a Radeon R7 M340) isn't supported by fglrx, so I went on and uninstalled it, and after that, I was able to log in again. The open source drivers work OK, but if I try to play a youtube video, it will lag AF. I think I'll just avoid AMD cards from now on.


text:
Q: How to correctly do a droppable on sortables? Take the example code snippet below:
If you click and drag Item 1 over Item 2 (or one of the other items) it will turn gray as to indicate it is droppable.
Drag it further so sortable kicks in and Item 2 moves up to Item 1's previous location - if you notice now the droppable location for Item 2 is still located at Item 2's original location and not moved with Item 2 to its now current location where Item 1 was previously located.
It somehow seems like, at least in its default states, a droppable on a sortable is not possible. So how do I correctly do a droppable on sortables?

$("#sortable").sortable({ cursor: "move" });
$("#sortable > li").droppable({ hoverClass: "hover" });
.pointer { cursor: pointer; }
.hover { background: #cccccc; }
<!doctype html>

  <meta charset="utf-8">
  <title>sortable demo</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

Item 1

Item 2

Item 3

Item 4

Item 5

A: Found an undocumented option for the sortable, refreshPositions: true, did just what I needed.


text:
Q: Set 'From' address in Outlook on a per-message basis I'm trying to determine if it's possible in Outlook(2010 specifically) to select the from address on a per-message basis if the user has multiple valid SMTP addresses on their Exchange mailbox. This is one of those things that is apparently un-googleable. For bonus points, it would be awesome if you could set the default from address per-contact.

A: In the web interface...

*

*Start a new email

*Click three dots menu and select 'Show From'

*Right-click your name, select 'remove'

*Type in the distribution group address you have rights to send as

It will then be a selection in the From drop down going forward.

A: In the message window, switch to the Options tab, then enable "From". This will add a "From" input above the "To" line. You can put any mailbox for which you have Send As permission.

(Picture is from this guide)

A: It looks to me like the OP is asking to choose between multiple SMTP addresses assigned to an individual user's Exchange mailbox.
You cannot choose from the various SMTP (or other proxy types) set on the user's mailbox object in the Active Directory in Outlook. @Stephen Jennings describes how to choose a different recipient object to send "From", but the default SMTP address for the object you select  will be stamped on the outgoing message.
The only way to do what you want would be to create multiple recipient objects in the Directory, assign each the appropriate default "From" address, and grant the appropriate user "Send As" permission to them. Then the user can send "From" the appropriate recipient and the address stamped on the outgoing message will be as-expected.
I'd recommend creating Distribution Group objects for the alternate "From" addresses and making the user a member of the groups (as well as granting Send As permission on the groups to the user) so that they'll receive any replies sent to those addresses.
In general I try to never hand-specify alternate addresses (that is, add addresses not managed by policy) on Exchange recipients and to always use groups to facilitate "alternate" addresses for users. I do this for the reason above, amongst others.

A: The way I got around this was to set up the user with an another AD/Exchange account and then set the primary SMTP as your second/additional  address.
Then in your users original account open Outlook, go to Account Settings > Delegate Access and assign the new Exchange user permission of your Inbox. Add the From field in new messages and then flick between both addresses as needed.
Last part is shown here:
http://support.sherweb.com/Faqs/show/how-to-send-emails-from-multiple-from-addresses-in-outlook-2010
A bit long winded but handy if only needed for a few users.


text:
Q: Blank page instead of "Index of /" in one folder of a website An (old) friend of mine has a website (Apache/2.4.10 (Ubuntu) Server) since many years. He provide, in several folders, several PDF files (research papers from he). He is yet very old (over 80) and probably has made a mistake.
Since few days, in one of these folders, the content is entirely blank, instead of displaying the usual "Index of /".
In all other folders, the website display the content correctly, e.g.:

But in this particular folder, it's blank (no "Index of /", no "Apache/2.4.10 (Ubuntu) Server", nothing).
What might have happened? The files in the blank folder are still accessibles with the complete path (e.g. at "http://www.someWebSite.com/folder1/subfolder/paper.pdf" if "subfolder" is the blank folder).
I don't have great knowledge in websites, Apache and so on, but I like helping this friend. Is there a missing configuration file? Bad permissions? He uses the software FileZilla for managing his website. What can or must be controlled?

A: It was because there was an "index.html" file in the folder. After removing it, the correct displaying has returned.


text:
Q: Debugging partially encrypted software PHP I am working on partially encrypted software (encrypted with ionCube). If I use my PHPed dbg debugger along with this, Apache crashes many a times, may be because both the ionCube and PhpED database uses zend_extension.
Is there a PHP debugger which will work in this scenario?

A: Try CodeLobster. Its debugger probably doesn't use a Zend Framework extension.


text:
Q: Running a function multiple time and displaying output on tkinter I am coding 'The Game Of Life' and using tkinter as a GUI. I have a grid (just a grid of 20 by 20 Buttons), and and an 'updateGrid' function that takes the current values of the grid and updates it according to the rules of The Game Of Life. I linked the 'updateGrid' function to a 'Next' button, thus if the Next button is clicked, the grid is updated. I want to implement a 'runGrid' function, (connected to a 'Run' button) that runs the 'updateGrid' function numerous times. I've tried this:
def runGrid():
    for i in range(0, 10):
        updateGrid()
        time.sleep(4)

but it seems like the tkinter GUI only updates once the runGrid function is completed. I want the tkinter GUI to update after each iteration so that the user can see the progress of the runGrid function.
Here is a screenshot of the grid before any button is pressed:

Here is a screenshot of the grid after the 'runGrid' function is executed:

The glider (the pattern) 'moves' from the first position to the last position in 10 moves, however, only the first and the last position is can be seen with the runGrid function. If the updateGrid function is called 10 times in a row, every move can be seen.

A: When GUIs (tkitner, PyQt, other GUIs, other languages) run your function then they does't update widgets at once but they wait for end of your code and they update all widgets only once. This way they have less work and they redraw window only once so it doesn't blink.

You can use after(milliseconds, function_name, [arg1, ...]) to execute function periodically without blocking mainloop
Something like this
def runGrid(i=10):
    updateGrid()
    if i > 0:
       root.after(4000, runGrid, i-1)  # 4000ms = 4s

Eventually you can use root.update() to force mainloop to redraw window
def runGrid():
    for i in range(0, 10):
        updateGrid()
        root.update()
        time.sleep(4)


text:
Q: NPM fails to install Socket.io does it need x-server? I was trying to install socket.io on my linux server using NPM
root@camdev01-dev:# npm install socket.io
(npm:22742): Gtk-WARNING **: cannot open display:
OS:ubuntu.11.10 server

A: Here is a quick how to for installing npm on Ubuntu, or any variant of UNIX for that matter
$ `curl http://npmjs.org/install.sh | sh`

It is that simple!
So you want to check out the code from git and compile it yourself? Then follow these steps:
$ `git clone https://github.com/isaacs/npm`
$ `cd npm`
$ sudo make install

Now you can install interesting stuff like socket.io
$ npm install socket.io

X-server is not a dependency package of Socket.io...
Dependency packages


text:
Q: Create data frames for each unique permutation of groups of a Dataframe Suppose I have the following Dataframe in Python:
     input_df = pd.DataFrame({
    'Previous': ['1000', '1000', 'latex', 'latex'],
    'Ignore':[None, None, ['free'], ['free']],
    'New': ['100', '200', 'nylon', 'cloth']})

I would like to generate the following four dataframes:
    df1  = pd.DataFrame({
        'Previous': ['1000','latex'],
        'Ignore': [None, ['free']],
        'New': ['100','nylon']})
    df2  = pd.DataFrame({
        'Previous': ['1000','latex'],
        'Ignore': [None, ['free']],
        'New': ['100','cloth']})
    df3  = pd.DataFrame({
        'Previous': ['1000','latex'],
        'Ignore': [None, ['free']],
        'New': ['200','nylon']})
    df4  = pd.DataFrame({
        'Previous': ['1000','latex'],
        'Ignore': [None, ['free']],
        'New': ['200','cloth']})

How can I accomplish this?
Edit: I have arrived at the following solution by modifying @TheMaster 's answer:
out=[pd.DataFrame(j) for j in c([i[1] for i in input_df.iterrows()], len(input_df['Previous'].unique())) if len(pd.DataFrame(j)['Previous'].unique()) == len(input_df['Previous'].unique())]

This solution keeps only the output where the 'Previous' column has all unique entries.

A: Try combinations:
from itertools import combinations as c
out=[pd.DataFrame(j) for j in c([i[1] for i in df.iterrows()],2)]

Out[2]:
[  Previous  New
 0     1000  100
 1     1000  200,
   Previous    New
 0     1000    100
 2    latex  nylon,
   Previous    New
 0     1000    100
 3    latex  cloth,
   Previous    New
 1     1000    200
 2    latex  nylon,
   Previous    New
 1     1000    200
 3    latex  cloth,
   Previous    New
 2    latex  nylon
 3    latex  cloth]