text:
Q: Lorentz transformation of electric and magnetic field vs. 4-vector I have a very general question about Lorentz transformations of electric and magnetic fields vs. 4-vectors . It arised from my previous post. I will describe the difficulty I encountered.
Information and problem:

*

*The electric and magnetic field in a system $S$ which can be boosted to a frame $\bar{S}$ moving at relative velocity $\mathbf{v}$. The electric field $\mathbf{E}  =\mathbf{E}_\perp + \mathbf{E}_\parallel$ ($\perp$, $\parallel$ are with respect to $\mathbf{v}$) and the magnetic field $\mathbf{B} = \mathbf{B}_\perp + \mathbf{B}_\parallel$ will be transformed as:

$$\mathbf{\bar{E}}_\parallel = \mathbf{E}_\parallel$$
$$\mathbf{\bar{B}}_\parallel = \mathbf{B}_\parallel$$
$$\mathbf{\bar{E}}_\perp = \gamma(\mathbf{E}_\perp + \mathbf{v} \times \mathbf{B})$$
$$\mathbf{\bar{B}}_\perp = \gamma(\mathbf{B}_\perp - \frac{\mathbf{v}\times \mathbf{E}}{c^2}),$$
where $\gamma \equiv \frac{1}{\sqrt{1-\mathbf{v}\cdot \mathbf{v}/c^2}}$ is used.

*

*My problem with these equations is as follows. There is an equality of vectors at each line visible. This means that if we have for instance $\mathbf{E}_\parallel = E_0 \mathbf{\hat{x}}$, $\mathbf{v} = v\mathbf{\hat{x}}$ and $\mathbf{B} = \mathbf{0}$ then $\bar{\mathbf{E}}_\parallel = \mathbf{E}_\parallel = E_0 \mathbf{\hat{x}}$ according to the definition. My problem is that $\mathbf{\bar{E}}_\parallel$ is expressed in terms of basis vector $\mathbf{\hat{x}}$ from frame $S$ and not a new basis vector say $\mathbf{\bar{\hat{x}}}$ in frame $\bar{S}$.

*In the case of a Lorentz transformation of a 4-vector, we have that for example for the 4-potential $A \equiv \{A^{\mu}\} = (V/c,\mathbf{A})$ we have that $\bar{A}^{\mu} = \Lambda^{\mu}_{\nu} A^{\nu}$ and since the 4-vector itself does not change under a basis transformation we have $A = \bar{A} = \bar{A}^\mu \bar{e}_\mu = A^{\mu}e_\mu$, where $\{e_\mu\}_{\mu \in \{0,1,2,3\}}$ and $\{\bar{e}_\mu\}_{\mu \in \{0,1,2,3\}}$ are bases for $S$ and $\bar{S}$. The same Minkowski space is therefore described by different basis vectors in the 4-vector formalism when boosting to another frame. But in case of the electric and magnetic field (which I know do not form a 4-vector but are contained in the field tensor $\mathbf{F}$) do only change in components and not in the basis of $\mathbf{R}^3$. I have the feeling that 4-vectors do not change under a Lorentz transformation, only the components and the basis in which they are expressed (so the basis representation) and for 3-vectors, they change as a whole, meaning that the basis vectors can stay the same although the components change. But I am not sure about this.

*Coming back to the 4-potential. The components are also called $\bar{A}_x$, $\bar{A}_y$, $\bar{A}_z$, just like one can write $\bar{E}_x$, $\bar{E}_y$, $\bar{E}_z$ after a boost. Now the problem is if we write $\mathbf{\bar{E}} = \bar{E}^j \mathbf{e}_j$: is this basis also just $\{\mathbf{\hat{x}},\mathbf{\hat{y}},\mathbf{\hat{z}}\}$? And for $\mathbf{\bar{A}} = \bar{A}_x \mathbf{\hat{x}} + \bar{A}_y \mathbf{\hat{y}} + \bar{A}_z \mathbf{\hat{z}}$: is this also a valid expression?

*To conclude I think the main problem lies in the question whether a Lorentz transformation changes the basis in which 3-vectors (e.g. magnetic or electric field) or the 3-vector inside a 4-vector (e.g. 4-potential) are defined. And is the basis of $\mathbf{R}^3$ different from the basis of Minkowski space?

I hope someone can explain this rigorously by using equations.

A: There are different ways to think about these things, some more general than others. Since the question is calling for conceptual clarification, I'll offer a more general perspective. It is more general in two ways:

*

*It works for an arbitrary number of dimensions.

*It works for arbitrary coorindate transformations, not just Lorentz transformations.
Even though the goal is to deduce how $\mathbf{E}$ and $\mathbf{B}$ transform, it's easier to first deduce how
$$
F_{ab}\equiv \partial_a A_b-\partial_b A_a
\tag{1}
$$
transforms, with coordinates denoted
$$
x^0,\ x^1,\ x^2,\ ...
\tag{2}
$$
and the corresponding partial derivatives
$$
\partial_a\equiv\frac{\partial}{\partial x^a}.
\tag{3}
$$
Then we can specialize to 4-d spacetime (3-d space) using
$$
E_k\propto F_{0k} \hskip1cm \text{ for }k\geq 1\\
\tag{4a}
$$
and
$$
B_1 = F_{23}
\hskip2cm
B_2 = F_{31}
\hskip2cm
B_3 = F_{12}.
\tag{4b}
$$
(I'm using units in which the speed of light is $1$. You'll need to check the sign conventions for $\mathbf{E}$ and $\mathbf{B}$, but that's a separate issue. In fact, one of the advantages of formulating things this way is that it separates the sign-convention issue from the issue of how things transform.) Equation (4b) is specific to 3-d space, but equation (1) makes sense in any number of dimensions. Equation (1) is also independent of the spacetime metric, so there's no need distinguish between space and time when working with equation (1). That distinction only becomes important when we want to separate (1) into electric and magnetic components, as in (4).
Here's a more general perspective on what coordinates are:

*

*A coordinate system is any smooth assignment of numbers (the coordinates) to the points of spacetime so that each point is labelled by a unique combination of numbers.

*Coordinates are not the components of a vector, and a general coordinate transformation is not a rigid transformation. A coordinate transformation does not rely on concepts like "basis" or "axis." (There are special contexts in which those concepts are perfectly valid; but I'm offering a more general perspective here.)
A coordinate transformation expresses the old coordinates $x$ as functions of new coordinates $\tilde x$, or conversely. (The transformation must be invertible.) Given those functions and using the abbreviation
$$
\tilde\partial_a\equiv\frac{\partial}{\partial \tilde x^a},
\tag{5}
$$
we already know from calculus how the partial derivatives in the two coordinate systems are related to each other (the chain rule):
$$
\partial_a = \sum_b\frac{\partial \tilde x^b}{\partial x^a}\tilde\partial_b
\hskip2cm
\tilde\partial_b = \sum_a\frac{\partial  x^a}{\partial \tilde x^b}\partial_a
\tag{6}
$$
For equation (1) to make sense, $A_a$ should transform the same way that $\partial_a$ transforms, so
$$
A_a(x) = \sum_b\frac{\partial \tilde x^b}{\partial x^a}\tilde A_b(\tilde x).
\tag{7}
$$
Equation (7) says that $A_a$ are the components of a single-subscript tensor. The transformation rule for $F_{ab}$ (and therefore for $\mathbf{E}$ and $\mathbf{B}$) can be inferred from equations (6)-(7), and the result is simpler than the derivation. Thanks to the antisymmetry of the right-hand side of (1), the messy parts cancel each other, leaving the relatively simple result
$$
F_{ab}(x) = \sum_{c,d}
 \frac{\partial \tilde x^c}{\partial x^a}
 \frac{\partial \tilde x^d}{\partial x^b}
 \tilde F_{cd}(\tilde x).
\tag{8}
$$
Equation (8) says that $F_{ab}$ are the components of a two-subscript tensor.
So far, this has all been for an arbitrary coordinate transformation. To specialize to Lorentz transformations, we first need to define what that means: a Lorentz transformation is a linear coordinate transformation for which the relationship
$$
(dx^0)^2-\sum_{k>0}(dx^k)^2 =
(d\tilde x^0)^2-\sum_{k>0}(d\tilde x^k)^2
\tag{9}
$$
holds. The fact that it's a linear transformation implies that the quantities
$$
\Lambda^b_a\equiv \frac{\partial \tilde x^b}{\partial x^a}
\tag{10}
$$
are constants. One example of such a transformation is the boost
\begin{align}
\tilde x^0 &= x^0\cosh\theta + x^1\sinh\theta \\
\tilde x^1 &= x^1\cosh\theta + x^0\sinh\theta \\
\tilde x^k &= x^k \hskip1cm \text{ for }k\geq 2
\tag{11}
\end{align}
for any constant $\theta$. Then the components of $\Lambda$ depend on the constant $\theta$ but not on the coordinates (neither $x$ nor $\tilde x$). Given any such transformation, equation (8) tells us how $F_{ab}$ transforms, and then equations (4) tell us how $\mathbf{E}$ and $\mathbf{B}$ transform, with (4b) being specific to 3-d space.
All of this was expressed in terms of the quantities $F_{ab}$, which are the components of a tensor field. An even more satisfying formulation is one that doesn't refer to components or coordinates at all. Such a coordinate-free formulation does exist [1]. It gives a solid formal foundation for the heuristic reasoning that was used above, and it provides a more-general version of expressions like $\mathbf{A}=\sum_k A_k \mathbf{\hat x}^k$ that were written in the OP. Here's a preview that doesn't really convey the concepts, but it does provide some tips that can be used to help guide an on-line search: A scalar field is a function from the smooth manifold ("spacetime") to the set of real numbers.  A vector field is a special kind of map from the set of scalar fields to itself; it is special because it is a derivation. This means that in a coordinate representation, a vector field is a combination of partial derivatives, like this: $v(x) = \sum_a v^a(x)\partial_a$. The functions $v^a(x)$ are the components of the vector field. Under a coordinate transformation, the components $v^a$ transform in a way that enforces this equation:
$$
\sum_a v^a(x)\partial_a = \sum_a \tilde v^a(\tilde x)\tilde \partial_a.
$$
Together with the identities (6), this tells us how the components $v^a$ transform. The quantities $F_{ab}$ are the components of a two-form, which in a coordinate representation looks like $F(x) = \sum_{a,b} F_{ab}(x)dx^a\wedge dx^b$, where the objects $dx^a$ are coordinate differentials, which are one-forms. (Each coordinate is a scalar field, and the differential of any scalar field is a one-form, and a one-form is a special kind of map from the set of vector fields to the set of scalar fields, involving odd-looking identities like $dx^a(\partial_b)=\delta^a_b$.) Under a coordinate transformation, the components $F_{ab}$ transform in a way that enforces this equation:
$$
   \sum_{a,b}F_{ab}(x)dx^a\wedge dx^b =
   \sum_{a,b}\tilde F_{ab}(\tilde x)d\tilde x^a\wedge d\tilde x^b,
$$
from which equation (8) can be deduced. And so on.

Reference:
[1] Lee (2003), Introduction to Smooth Manifolds, Springer

A:
My problem with these equations is as follows. There is an equality of vectors at each line visible. This means that if we have for instance $\mathbf{E}_\parallel = E_0 \mathbf{\hat{x}}$, $\mathbf{v} = v\mathbf{\hat{x}}$ and $\mathbf{B} = \mathbf{0}$ then $\bar{\mathbf{E}}_\parallel = \mathbf{E}_\parallel = E_0 \mathbf{\hat{x}}$ according to the definition. My problem is that $\mathbf{\bar{E}}_\parallel$ is expressed in terms of basis vector $\mathbf{\hat{x}}$ from frame $S$ and not a new basis vector say $\mathbf{\bar{\hat{x}}}$ in frame $\bar{S}$.

The way this is customarily notated in terms of a set of relations among 3-vectors is convenient and concise but kind of misleading, because what is really being stated is a set of relations among components of a 4x4 tensor. It is not true that $\bar{\mathbf{E}}_\parallel = \mathbf{E}_\parallel = E_0 \mathbf{\hat{x}}$, and I think this is a nice example of what's fundamentally bad about the notation, because it violates the transitivity of the = sign. When we write $\bar{\mathbf{E}}_\parallel = \mathbf{E}_\parallel$, what we mean is that in the electromagnetic field tensor, $F^{x't'}=F^{xt}$, i.e., these components of the  tensor are equal in the two different bases. But for an observer in $\bar{S}$, $\bar{\mathbf{E}}$ is by definition a purely spatial vector (i.e., it lies in a plane of simultaneity), while to that observer $\mathbf{\hat{x}}$ has a nonzero time component. Therefore it cannot be true that $\bar{\mathbf{E}}_\parallel = E_0 \mathbf{\hat{x}}$

I have the feeling that 4-vectors do not change under a Lorentz transformation, only the components and the basis in which they are expressed (so the basis representation)[...]

Yes, this is the way most physicists and mathematicians think about it these days. (There is another point of view dating to ca. the 19th century and used by people like (IIRC) Sylvester. This WP article gives a description from this point of view.)

[...]and for 3-vectors, they change as a whole, meaning that the basis vectors can stay the same although the components change. But I am not sure about this.

The question of whether a vector changes as a whole under a change of coordinates is not one that automatically has a well-defined answer. People like Sylvester would probably have had a different way of thinking about this than people today. The modern trend is to try to make everything obey a standard set of tensor transformation rules, and to use notations that can't even express the question of whether a vector (as opposed to its components) changes when you change coordinates. For someone who is used to the modern language, attitudes, and notations, "3-vector" just means "ordered triple of components," i.e., unlike a true vector, a 3-vector is an object that has no meaning or existence that transcends its components.
It's not possible for the basis for the 3-vectors to stay the same, because they have to be purely spatial vectors for each observer, with no time component. By definition, $\mathbf{\hat{x}}$  means a unit vector that is parallel to an infinitesimal displacement in which only $x$ changes (or, if you want to be fancier, parallel to the directional derivative in the $x$ direction, see Wald, p. 15). By the same definition, $\mathbf{\hat{x}}'$  is parallel to an infinitesimal displacement in which only $x'$ changes, and this is a different direction in spacetime.

Coming back to the 4-potential. The components are also called $\bar{A}_x$, $\bar{A}_y$, $\bar{A}_z$, just like one can write $\bar{E}_x$, $\bar{E}_y$, $\bar{E}_z$ after a boost. Now the problem is if we write $\mathbf{\bar{E}} = \bar{E}^j \mathbf{e}_j$: is this basis also just $\{\mathbf{\hat{x}},\mathbf{\hat{y}},\mathbf{\hat{z}}\}$? And for $\mathbf{\bar{A}} = \bar{A}_x \mathbf{\hat{x}} + \bar{A}_y \mathbf{\hat{y}} + \bar{A}_z \mathbf{\hat{z}}$: is this also a valid expression?

You can do this kind of thing if you like, but in general we like 4-vectors better than 3-vectors, because 4-vectors have consistent transformation laws. Therefore when you have a nice, well-behaved 4-vector like $A$, you don't normally want to mess around making a 3-vector out of its spatial components.

To conclude I think the main problem lies in the question whether a Lorentz transformation changes the basis in which 3-vectors (e.g. magnetic or electric field) or the 3-vector inside a 4-vector (e.g. 4-potential) are defined.

Yes, as described above, it changes the basis in which the 3-vectors are defined, because the 3-vectors are just defined as triples of components of some tensorial object (in this case a 4x4 tensor), which is itself expressed in a basis that has changed.

And is the basis of $\mathbf{R}^3$ different from the basis of Minkowski space?

I think a better way of saying this is that if a particular observer is constructing a set of Minkowski coordinates, they will choose coordinates in which $(x,y,z)$ are purely spatial coordinates, so that their basis vectors span a 3-surface of simultaneity.
The best way to retain your sanity and avoid confusion in this stuff is to organize all your thoughts in terms of the transformation properties of tensors. Then when you come to something that is expressed in a different way, such as the transformation laws for the electromagnetic field's 3-vectors, just think of it as a shorthand for the actual underlying operations on tensors.

A: I think your confusion comes from what is called active and pasive transformations, one topic which was already well explained in the following post!.
When a coordinate transformation is performed there are two possibilities to interpret it:

*

*If the transformation acts only on the coordinate axes, we speak of the passive role (right image) of the transformation.

*While in the active point of view (left image) the transformation is consider to change directly the vector.

In this case for the parallel and perpendicular electric and magnetic fields the point of view used is the active, as you may have inferred, and the most common convention in the textbooks is to use the active point of view of the transformation.
In a slightly more formal way if you have a transformation $T$ which acts on a $\mathbb{R^3}$ vector $\mathbf{v}=v_i\mathbf{e}^i$ the passive point of view will give $\mathbf{v'}=T\mathbf{v}=v_iT\mathbf{e}^i=v_i\mathbf{e'}^i$ while the active one $\mathbf{v'}=T\mathbf{v}=Tv_i\mathbf{e}^i=v'_i\mathbf{e}^i$

A: In special relativity we can write statements such as $\bar{\bf E}_\parallel = {\bf E}_\parallel$ without ambiguity because there is a universal way to agree directions in space (it is not so simple in general relativity). Whenever we consider a 3-vector $\bf w$ at an event, we can, for the purpose of agreeing its direction between one frame and another, imagine it as the spatial part of a 4-vector lying in the plane of simultaneity of the frame of reference in which the 3-vector is specified. If we now change to another frame, and obtain another 3-vector $\bar{\bf w}$, then we can similarly construct a 4-vector lying in the plane of simultaneity of the new frame, with spatial part equal to $\bar{\bf w}$. Each of these 4-vectors can then be projected onto the plane of simultaneity of the other, and thus compared. In this way one arrives at a common sense of spatial direction between any two inertial frames (whether boosted, or rotated, or both, with respect to one another), and the concept of a 3-vector can therefore be employed, without the need to deconstruct it into components and basis vectors.
I think your question is quite deep and I had to think carefully before answering it (and I am supposed to be some sort of expert here ...) so it may be that others will give better answers; I would be pleased if they did and then I will learn something myself.

A: The unit vectors $\hat x$, $\hat y$, $\hat z$ are identical in two frames related by a boost along one of them.


text:
Q: how to use data from table 1 and divide by specific data in table 2 within sql I am writing a query where it pulls the previous months total # of renewals from table 1 and then divides it by the national average of working business days for that specific month from table 2 (both tables are in the same sever & database).
I have the queries for the above statement, I just do not know how to connect them.
The query is essentially: Total # of Renewal Volume for month A / # of business days in month A
From my understanding I need to make sure that the data in columns 'YR' and 'MTH' in table 1 match columns 'cal_month' and 'cal_year' in table 2. If so it would then take the total # of renewals in the 'volumes' column in table 1 and divide it by the # of business days in the 'national_avg' column in table 2.
select volume, YR, MTH
from example.dbo.table1
where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
      and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
group by MTH, YR

select cal_month, cal_year, National_Avg
from example.dbo.table2
where cal_month = DATENAME(mm, DATEADD(month,-1,current_timestamp))
    AND cal_year  = DATENAME(yyyy, DATEADD(month,-1,current_timestamp))

Example
Table 1
Volume / MTH / YR

200   / 2 / 2018

Table 2
cal_month / cal_year / national_avg

February / 2018 / 22

Expected result:
9.09
I am fairly new with sql, I think I got the logic correct I'm just having trouble writing the correct syntax. I was thinking of using a temptable, I just dont have experience with one. Thank you

A: Just wrap up both queries as subqueries and join on the necessary fields like below.  Then you can easily create your new column by dividing volume by nationalavg
select *, volume/ case when National_Avg=0 then 1 else National_Avg end NewColumn  from (select volume, YR, MTH
from example.dbo.table1
where month(datecompleted) = month(dateadd(month,-1,current_timestamp))
      and year(datecompleted) = year(dateadd(month,-1,current_timestamp))
group by MTH, YR)a
join
(select cal_month, cal_year, National_Avg
from example.dbo.table2
where cal_month = DATENAME(mm, DATEADD(month,-1,current_timestamp))
    AND cal_year  = DATENAME(yyyy, DATEADD(month,-1,current_timestamp)))b
    on a.yr=b.cal_year and a.mth=b.cal_month

A: The answer to your question is cross join:
select . . .
from (select t1.volume, t1.YR, t1.MTH
      from example.dbo.table1 t1
      where datecompleted >= dateadd(month, -1, dateadd(day, 1 - day(current_timestamp), current_timestamp)) and
            datecompleted < dateadd(day, 1 - day(current_timestamp), current_timestamp)
     ) v cross join
     (select cal_month, t2.cal_year, t2.National_Avg
      from example.dbo.table2 t2
      where t2.cal_month = DATENAME(month, DATEADD(month,-1, current_timestamp)) and
            t2.cal_year  = DATENAME(year, DATEADD(month, -1, current_timestamp))
     ) n;

Note that I changed the date logic for the first subquery.  It is better to not use function calls or type casts on the columns, because that can prevent the use of indexes.
I would recommend that you use the same time identifier in each table -- such as a date column for the beginning of the period.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show firestore uid etc. on Stripe Dasboard? I am trying to create stripe customer id. and trying to show my firestore uid as my Stripe customer id. what I have done so far i) I have created firestore id and linked it to my app. ii) I have created cloud functions i.e createStripeCustomer as index.js on my computer and suucessfully deployed it on the function console as you can see below:-

I have also create a collection - "stripe_customers" with firestore document uid  "ljO8PXBpI6gyqliXOTeqJf08dQ22" with email  "test@again.com", see image below:-

Now, I want - when the correct ViewController code should be, so that when I click a button in my app i.e. ViewController, then my  firestore document uid i.e. "ljO8PXBpI6gyqliXOTeqJf08dQ22" should show as the stripe customer id. If that is not possible, the firestore document uid "ljO8PXBpI6gyqliXOTeqJf08dQ22" should be linked with my Stripe Customer id with email  "test@again.com" when I click a button on the  ViewController.
The most important thing that should it should show on Stripe Dashboard .
Now my Viewcontroller code is:-
   import UIKit
   import Stripe
   import Firebase

   class NewStripeViewController: UIViewController, STPAuthenticationContext {
  let functions = Functions.functions()
   // MARK: UIViews
  var productStackView=UIStackView()
  var paymentStackView=UIStackView()
  var productImageView=UIImageView()
  var productLabel=UILabel()
  var payButton=UIButton()
  var loadingSpinner=UIActivityIndicatorView()
  var outputTextView=UITextView()
  var paymentTextField=STPPaymentCardTextField()
  let backendURL : String =   "console.firebase.google.com/project/totemic-point-318509/overview"

   override func viewDidLoad() {
     super.viewDidLoad()
   // Do any additional setup after loading the view.

    // Setup UI (images, labels, debug text view)
    // Also setup STPPaymentCardTextField from Stripe-iOS
    self.setupUI()
    }

    // MARK: UIView setup

    func setupUI() {
    setupProductImage()
    setupProductLabel()
    setupLoadingSpinner()
     setupPaymentTextField()
    setupPayButton()
    setUptOutputTextView()

    self.productStackView.frame = CGRect(x:0,y:70,width:330, height:150)
    self.productStackView.center.x = self.view.center.x
   self.productStackView.alignment = .center
   self.productStackView.axis = .vertical
   self.productStackView.distribution = .equalSpacing

 self.productStackView.addArrangedSubview(self.productImageView)
   self.productStackView.setCustomSpacing(10,after:self.productImageView)
   self.productStackView.addArrangedSubview(self.productLabel)

  self.view.addSubview(self.productStackView)

  self.paymentStackView.frame = CGRect(x:0,y:250,width:300,height:100)
   self.paymentStackView.center.x = self.view.center.x
  self.paymentStackView.alignment = .fill
  self.paymentStackView.axis = .vertical
  self.paymentStackView.distribution = .equalSpacing

              self.paymentStackView.addArrangedSubview(self.paymentTextField)
   self.paymentStackView.addArrangedSubview(self.payButton)

    self.view.addSubview(self.paymentStackView)
   }

  func setupProductImage() {
  self.productImageView = UIImageView(frame:CGRect(x:50, y:50,     width:275, height:200))

  self.productImageView.image = UIImage(named:"ic_cart")
 self.productImageView.contentMode = .scaleAspectFit

  }

   func setupProductLabel() {
   self.productLabel.frame = CGRect(x:0, y:270, width:      self.view.frame.width, height:50)
   self.productLabel.text = "buy a stripe press book for $ 5"
   self.productLabel.textAlignment = . center
     }

  func setUptOutputTextView() {
  self.outputTextView.frame =   CGRect(x:0,y:420,width:self.view.frame.width-50, height:100)
  self.outputTextView.center.x = self.view.center.x
  self.outputTextView.textAlignment = .left
  self.outputTextView.font = UIFont.systemFont(ofSize:20)
  self.outputTextView.text = ""
  self.outputTextView.layer.borderColor = UIColor.purple.cgColor
  self.outputTextView.layer.borderWidth = 1.0
  self.outputTextView.isEditable = false
  self.view.addSubview(self.outputTextView)
  }

  func setupPaymentTextField() {
  self.paymentTextField.frame = CGRect(x:0, y:0, width: 300,  height:50)
     }

    func setupPayButton() {
    self.payButton.frame = CGRect(x:60, y:480, width: 150, height:50)
    self.payButton.setTitle("submit payment", for:.normal)
    self.payButton.setTitleColor(UIColor.white, for:.normal)
    self.payButton.layer.cornerRadius = 5.0
    self.payButton.backgroundColor = UIColor.init(red:50/250,green:50/250,blue:90/250,alpha:1.0)
    self.payButton.layer.borderWidth = 1.0
    self.payButton.addTarget(self, action: #selector(pay), for: .touchUpInside)
      }
    func setupLoadingSpinner() {
    self.loadingSpinner.color = UIColor.darkGray
   self.loadingSpinner.frame = CGRect(x:60, y:400, width: 25,         height:25)
    self.loadingSpinner.center.x = self.view.center.x
    self.view.addSubview(self.loadingSpinner)
  }

    func startLoading() {
    DispatchQueue.main.async {
    self.loadingSpinner.startAnimating()
    self.loadingSpinner.isHidden=false
      }
     }

   func stopLoading() {
    DispatchQueue.main.async {
    self.loadingSpinner.stopAnimating()
    self.loadingSpinner.isHidden=true
     }
    }

    func displayStatus(_ message: String) {
    DispatchQueue.main.async {
    self.outputTextView.text! += message + "\n"
         self.outputTextView.scrollRangeToVisible(NSMakeRange(self.outputText  View.text.count - 1, 1))
     }
   }

    // MARK: Button Actions

      @objc func pay() {
      // 1) [server-side] Create a PaymentIntent
      // 2) [client-side] Confirm the PaymentIntent

    // make a POST request to the /create_payment_intent endpoint
     self.startLoading()
     self.displayStatus("Creating PaymentIntent")

      self.createPaymentIntent { (paymentIntentResponse, error) in
      if let error=error {
        self.stopLoading()
        self.displayStatus(error.localizedDescription)
        print(error)
        return
           }
        else {
        guard let responseDictionary=paymentIntentResponse as? [String: AnyObject] else {
            print("Incorrect response")
            return
        }

        print(responseDictionary)
        let clientSecret=responseDictionary["secret"] as! String

        self.displayStatus("Created PaymentIntent")

        // Confirm the PaymentIntent using STPPaymentHandler
        // implement delegates for STPAuthenticationContext

         let paymentIntentParams=STPPaymentIntentParams(clientSecret: clientSecret)
         let paymentMethodParams=STPPaymentMethodParams(card:            self.paymentTextField.cardParams, billingDetails: nil, metadata: nil)
             paymentIntentParams.paymentMethodParams=paymentMethodParams

        STPPaymentHandler.shared().confirmPayment(withParams:  paymentIntentParams, authenticationContext: self) { (status, paymentIntent, error) in

            self.stopLoading()

            var resultString=""

            switch (status) {
            case .canceled:
                resultString="Payment canceled"
            case .failed:
                resultString="Payment failed, please try a different card"
            case .succeeded:
                resultString="Payment successful"
            }

            print(resultString)
            self.displayStatus(resultString)
        }
    }
   }

}

      func createPaymentIntent(completion: @escaping STPJSONResponseCompletionBlock) {
     functions.httpsCallable("createPaymentIntent").call(["amount": 1099]) { result, error in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
    // ...
    }
    if let data = result?.data as? [String: Any] {
    // do something with data
     }
            }
   }

    // MARK: STPAuthenticationContext Delegate

     func authenticationPresentingViewController() -> UIViewController {
return self
   }
 }

My index.js is -
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');

   const stripe = require('stripe')('sk_test_51HmAsMFzRM1fSBZ2CkBBjW5a3sEpxEQLGT7OkGxa8BZMMfgzT1Jeqs7dq63AlPRLIJmzHFC0HHAmKHDazcpriuh9001IWIVmw1');
    // initialize admin SDK with defaults
  admin.initializeApp();

 // [START chargecustomer]
 // Charge the Stripe customer whenever an amount is written to the firestore
          exports.createStripeCharge = functions.firestore.document('stripe_customers/{userId}/charges/{id}').onCreate(async (snap, context) => {
  const val = snap.data();
  try {
    // Look up the Stripe customer id written in createStripeCustomer
    const snapshot = await admin.firestore().collection(`stripe_customers`).doc(context.params.userId).get()
    const snapval = snapshot.data();
    const customer = snapval.customer_id
    // Create a charge using the pushId as the idempotency key
    // protecting against double charges
    const amount = val.amount;
    const idempotencyKey = context.params.id;
    const charge = {amount, currency, customer};
    if (val.source !== null) {
      charge.source = val.source;
      }
      const response = await stripe.charges.create(charge, {idempotency_key: idempotencyKey});
    // If the result is successful, write it back to the     database
    return snap.ref.set(response, { merge: true });
    } catch(error) {
    // We want to capture errors and render them in a user-   friendly way, while
    // still logging an exception with StackDriver
    console.log(error);
    await snap.ref.set({error: userFacingMessage(error)}, {  merge: true });
      return reportError(error, {user: context.params.userId});
     }
   });

   // [END chargecustomer]]

   // When a user is created, register them with Stripe
   exports.createStripeCustomer =        functions.auth.user().onCreate(async (user) => {
   const customer = await stripe.customers.create({email:   user.email});
   return         admin.firestore().collection('stripe_customers').doc(user.uid).set({   customer_id: customer.id});
     });

 // Add a payment source (card) for a user by writing a stripe         payment source token to Realtime database
  exports.addPaymentSource =         functions.firestore.document('/stripe_customers/{userId}/tokens/{pushId}').onCreate(async (snap, context) => {

   const source = snap.data();
   const token = source.token;
    if (source === null){
    return null;
     }

    try {
const snapshot = await  admin.firestore().collection('stripe_customers').doc(context.params.userId).get();
const customer =  snapshot.data().customer_id;
const response = await stripe.customers.createSource(customer, {source: token});
return admin.firestore().collection('stripe_customers').doc(context.params.userId).collection("sources").doc(response.fingerprint).set(response, {merge: true});
 } catch (error) {
await snap.ref.set({'error':userFacingMessage(error)}, {merge:true});
return reportError(error, {user: context.params.userId});
   }
 });

 // When a user deletes their account, clean up after them
      exports.cleanupUser = functions.auth.user().onDelete(async (user) =>   {
     const snapshot = await    admin.firestore().collection('stripe_customers').doc(user.uid).get()   ;
      const customer = snapshot.data();
      await stripe.customers.del(customer.customer_id);
     return      admin.firestore().collection('stripe_customers').doc(user.uid).delete(     );
    });

    // To keep on top of errors, we should raise a verbose error report with Stackdriver rather
    // than simply relying on console.error. This will calculate users affected + send you email
    // alerts, if you've opted into receiving them.
    // [START reporterror]
    function reportError(err, context = {}) {
    // This is the name of the StackDriver log stream that will  receive the log
     // entry. This name can be any valid log stream name, but     must contain "err"
    // in order for the error to be picked up by StackDriver Error    Reporting.
   const logName = 'errors';
   const log = logging.log(logName);

      // https://cloud.google.com/logging/docs/api/ref_v2beta1/rest/v2beta1/MonitoredResource

    const metadata = {
    resource: {
     type: 'cloud_function',
     labels: {function_name: process.env.FUNCTION_NAME},
     },
   };

   // https://cloud.google.com/error-reporting/reference/rest/v1beta1/ErrorEvent
    const errorEvent = {
    message: err.stack,
     serviceContext: {
     service: process.env.FUNCTION_NAME,
  resourceType: 'cloud_function',
     },
     context: context,
      };

  // Write the error log entry
     return new Promise((resolve, reject) => {
     log.write(log.entry(metadata, errorEvent), (error) => {
     if (error) {
     return reject(error);
    }
      return resolve();
      });
      });
      }
     // [END reporterror]

     // Sanitize the error message for the user
     function userFacingMessage(error) {
     return error.type ? error.message : 'An error occurred,      developers have been alerted';
      }

Now, everytime I click on "Submit Payment" button, it just says "creating PaymentIntent" as shown in the figure below: -

and  the Stripe Dashboard is empty:-

I have tried and failed. I hope you will assist me with that.
Thanks.

A: This sorts of custom attributes are best used via metadata on Stripe objects, including for Customer objects (api reference). I'm not sure how this would be done with your particular integration, but it would be added to whichever code you use to create customers.
It would appear in the Dashboard like this:

and in search:


text:
Q: React project build production is not working in Xampp Am developing a project in reactJS. In this project there is a login page, if user login successful then he redirects to dashboard page. This is working in locally but i Created a build folder and uploaded in Server. From server i tried to login, user logged in successful then it redirects to dashboard page, there its showing error called "The requested URL was not found on this server." Can anyone take me out of this problem. Here is the code
if (response.data['status'] === "Data not found") {
    alert("Enter valid credentials")
    window.location.reload();
}
else {
    localStorage.setItem("login", JSON.stringify(response.data))
    window.open("/Foldername/Dashboard", "_top");
}

This is the Routing Folder
<Route exact path="/Foldername/Dashboard" component={Dashboard} />

Thanks

A: You need to tell apache to serve the index for any files it can't find:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule . /index.html [L]
</IfModule>


text:
Q: Signing a folder using digital signature in java I am trying to sign a folder using digital signature.I am able to sign  a file.But Now i need to sign  a folder containing multiple files.Please help me with an example that will suffice my requirement

A: You should use this way to iterate on folder here: How do I iterate through the files in a directory in Java?, but except of calling System.out.println("File: " + file.getName()); for each file call you signing method.
Good luck !

A: You might want to take a look at the Javadocs for security and digital sign generation. https://docs.oracle.com/javase/tutorial/security/apisign/gensig.html


text:
Q: A collection of ADTs with no duplicate constructors If I have a data type:
data Component = PositionC Double Double | HealthC Double | NameC String

*

*I want a collection of Components

*I won't be storing any duplicates (ie: It won't have two HealthCs)

*I don't want to manually duplicate code

What technique, data structure, TemplateHaskell feature, etc, can I use to fulfil the above criteria?
I've experimented with Data.Set and Data.Map without success.
Data.Map attempt:
import Data.Map

data Component = PositionC Double Double | HealthC Double | NameC String

-- Unacceptable code duplication
data ComponentType = PositionCT | HealthCT | NameCT
    deriving (Eq, Ord)

type ComponentMap = Map ComponentType Component

foo :: ComponentMap
-- More annoying code duplication
foo = fromList [(HealthCT, HealthC 100), (NameCT, NameC "John")]

fooHealth = foo ! HealthCT -- However, accessing works great

Data.Set attempt:
import Data.Set (Set)
import qualified Data.Set as Set

data Component = PositionC Double Double | HealthC Double | NameC String
    deriving Eq

foo :: Set Component
foo = Set.fromAscList [HealthC 100, NameC "John"] -- This works well

-- But accessing elements is very bad
fooHealth = Set.elemAt 0 $ Set.filter p foo
    where p (HealthC _) = True
          p _           = False

A: An option is to use a record with optional fields:
data Component = Component
                 { positionC :: Maybe (Double, Double)
                 ; healthC :: Maybe Double
                 ; nameC :: Maybe String
                 }

Intuitively, access to fields will also be cheaper than using a Set or Map.
Setting a field
moveToOrigin c = c { positionC = Just (0,0) }

Getting a field
-- Requires health to be present
isDead c = fromJust (healthC c) == 0

-- If health is unknown returns False
saferIsDead c = health C == Just 0


text:
Q: how to move in to next tab using tab key I want to create functionality when user use Tab key for moving in to next tab. every tab contains some text boxes. When user in last text box of tab 1 when it press the tab key it will go into next text box of tab2. I am craeting tab using  plain htlm css and jquery. I am not using tabs functionality of jquery. the below is my html. I am creating tab using ul an li. how I move into next li when my tab in first text box.
html

Tab 1

Tab 2

Tab 3

  test 1<asp:TextBox runat="server"  ID="test1" />

  test 2<asp:TextBox runat="server"  ID="test2" />

  test 3<asp:TextBox runat="server"  ID="test3" />

  test 4<asp:TextBox runat="server"  ID="test4" />

  test 5<asp:TextBox runat="server"  ID="test5" />

  test 6<asp:TextBox runat="server"  ID="test6" />

this is  jquery
// Wait until the DOM has loaded before querying the document
    $(document).ready(function(){
        $('ul.tabs').each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
        $active.addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

        // Bind the click event handler
        $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
     });
  });
            </script>

and this css
    * {padding:0; margin:0;}

    html {
        background:url(/img/tiles/wood.png) 0 0 repeat;
        padding:15px 15px 0;
        font-family:sans-serif;
        font-size:14px;
    }

    p, h3 {
        margin-bottom:15px;
    }

    div {
        padding:10px;
        width:600px;
        background:#fff;
    }

    .tabs li {
        list-style:none;
        display:inline;
    }

    .tabs a {
        padding:5px 10px;
        display:inline-block;
        background:#666;
        color:#fff;
        text-decoration:none;
    }

    .tabs a.active {
        background:#fff;
        color:#000;
    }

A: Use this javascript:
Demonstration.
// Wait until the DOM has loaded before querying the document
$(document).ready(function () {
    $('ul.tabs').each(function () {
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="' + location.hash + '"]')[0] || $links[0]);
        $active.addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not($active).each(function () {
            $($(this).attr('href')).hide();
        });

        // Bind the click event handler
        $(this).on('focus', 'a', function (e) { //from click handler to focus handler
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = $(this);
            $content = $($(this).attr('href'));

            // Make the tab active.
            $active.addClass('active');
            $content.show();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
});

And this HTML:

Tab 1

Tab 2

Tab 3

test 1
            <asp:TextBox runat="server" ID="test1" />

test 2
            <asp:TextBox runat="server" ID="test2" />

test 3
            <asp:TextBox runat="server" ID="test3" />

test 4
            <asp:TextBox runat="server" ID="test4" />

test 5
            <asp:TextBox runat="server" ID="test5" />

test 6
            <asp:TextBox runat="server" ID="test6" />

Code Explanation
Explanation of JS:
I have changed the event handler from click to focus so that when the div would be focused the script could run rather then on clicking it.
Explanation of HTML:
I have added tabindex to the tabs so that they could be accessed by using the tab key.


text:
Q: Two similiar InfoPath 2010 form views but required fields on only one of them? I have a form with two views, one view has all fields like title, date, subject, country, Yes/No and  state. The other view only has date and Yes/No (a checkbox).
On the first view all fields are required but if the user selects the second view only tilte and date should be required. My issue is that if I add required rules on the first form the fields that are not present on the second view still are required. I tried to add a condition like required if state is present but on the second view where it is not present it is still required.
Any ideas?
Thanks in advance.

A: Check the field properties on InfoPath2010(and also on SharePointDesigner2010). On the properties, AllowNullValues must be unchecked. After that, you can use rules to set field's requirements.

A: With form services you can't use validation rules.
The approach I've used in the past is have a defined "Null" value.  So if you don't need a "Subject" value you still populated it with something like "NA".  In your form you use rules to set the content.  I prefer to keep them in the Submit section prior to save, so I would check if Subject has a value and if not I set it to "NA".  So now you can set the fields as required on the form and regardless of view they have to fill in only the fields you show, and the form logic fills in the rest.
Now, if you don't like seeing these "NA" or "999", etc values in your list, you can edit the list view in SharePoint Designer and add formatting rules that can remove rendering of values if they equal whatever it is you chose.


text:
Q: how to send query string parameters in XMLHttpRequest to php page I have following php variable of name
    $name=$_POST["name"];
    <script>
    pge = '<?php echo $name ;?>';
    var url = "searchCustomerByNameApi2.php"
    //some code
   xmlhttp.open("GET", url, true);
   xmlhttp.send();

how can I send pge variable along with url as aquery string and access it on the php page ??

A: Simple you have your javascript code look like this.
<script>

   var  name  = '';

   name = '<?php print $_POST["name"]?>';
   var url = "searchCustomerByNameApi2.php?name"+name;
   xhttp.open("GET", url, true);
   xhttp.send();

</script>

and php code look like searchCustomerByNameApi2.php page
   $name = $_REQUEST['name'];

A: Try "searchCustomerByNameApi2.php?pge="+pge and get it on php page like $_REQUEST['pge'].

A: You can use a function to create a query string from an object:
And append that result to your url:
$name=$_POST["name"];

<script>
function encodeQueryData(data) {
   let ret = [];
   for (let d in data)
          ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
   return ret.join('&');
 }

pge = '<?php echo $name ;?>';
var data = {pge: pge};
var query =encodeQueryData(data);
var url = "searchCustomerByNameApi2.php";
url += "?" +query;
xmlhttp.open("GET", url, true);
xmlhttp.send();

A: Have you tried below?
var url = "searchCustomerByNameApi2.php";
var test = "name=<?php echo $_POST["name"]; ?>";

xmlhttp.open("GET", url, true);
xmlhttp.send(test);

Hope this resolve your issue.


text:
Q: Excel VBA: How to put formula in next available column for unique number of rows? I am still new to VBA and am trying to perform a vlookup in the next available column from row 4 until the used range for the vlookup is over. In addition, once the vlookup is completed, in the line under I need to sum all the values in the cells above. If that is confusing, here is the code I have so far:
 Sub vlookup2()
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Set sourceSheet = Worksheets("Data1")
Set outputSheet = Worksheets("Pivot")
With sourceSheet
     SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
    OutputLastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    .Range("*4:*" & OutputLastRow).Formula = _
         "=VLOOKUP(D4,'" & sourceSheet.Name & "'!$A$2:$H$" & SourceLastRow & ",3,0)"
End With
End Sub

Where I have the "*4: *" is where I'd imagine I need to put the data for the next available column. After that I would just need to sum everything from that column in the next available from in that column. Can someone please help?

A: Finds the next available column and inserts your formula in the range and sums it at the bottom. If your column count is greater than 26 then you need to modify it.
        Dim SourceLastRow As Long
        Dim OutputLastRow As Long
        Dim sourceSheet As Worksheet
        Dim outputSheet As Worksheet

        Dim NextColumn As Long
        Dim ColumnStr As String
         Dim ColumnStr2 As String
          Dim ColumnStr3 As String
        Set sourceSheet = Worksheets("Data1")
        Set outputSheet = Worksheets("Pivot")
        With sourceSheet
             SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        End With

        With outputSheet
            NextColumn = .Cells(4, Columns.Count).End(xlToLeft).Column + 1
            If NextColumn + 1 < 27 Then
               ColumnStr = Chr(64 + NextColumn + 1)
            Else
                ColumnStr = Chr(64 + Int((NextColumn + 1) / 26)) & Chr(64 + ((NextColumn + 1) Mod 26))
            End If
            If NextColumn - 1 < 27 Then
               ColumnStr3 = Chr(64 + NextColumn - 1)
            Else
                ColumnStr3 = Chr(64 + Int((NextColumn - 1) / 26)) & Chr(64 + ((NextColumn - 1) Mod 26))
            End If
            If NextColumn < 27 Then
               ColumnStr2 = Chr(64 + NextColumn)
            Else
                ColumnStr2 = Chr(64 + Int((NextColumn) / 26)) & Chr(64 + ((NextColumn) Mod 26))
            End If
            OutputLastRow = .Cells(.Rows.Count, "D").End(xlUp).Row

            .Range(Cells(4, NextColumn), Cells(OutputLastRow, NextColumn)).Formula = _
                 "=VLOOKUP(D4,'" & sourceSheet.Name & "'!$A$2:$H$" & SourceLastRow & ",3,0)" & "*" & ColumnStr3 & 4
            DoEvents
            .Cells(OutputLastRow + 1, NextColumn).Formula = "=SUM(" & ColumnStr2 & "4:" & ColumnStr2 & OutputLastRow & ")"
        End With


text:
Q: Outlook 2011 - clicking email addresses inside the application opening in Apple Mail I use Apple Mail for my personal mail, and Outlook 2011 for work.  I have Mail as my default client, as when browsing the web / writing mail, I want to send all emails from that account.
However, I use Outlook for work.  When I need to send a new email to someone in outlook, say an email, and their name is blue and highlighted, I click their name. However, it opens a new mail message in Apple Mail instead of Outlook.
How can I have Outlook know that if I'm using Outlook, I want to send new messages FROM Outlook?  I hope the question is clear!

A: Setting Default mail Client tells your system to use that one when requesting email from other applications. (outside of Email).
While in Email (Outlook or Mail) they will do as told.
In your case using MS Office Word, Excel, PowerPoint with email link in one of the documents, will by default use the chosen default mail client.
There is a simple work around.
Since you are probably not using heavy duty MS Office applications to handle your Mail.app but do so with Outlook, I would make the Outlook the default mail application.
Now you can use Mail as email and Outlook will be the default mail client for your work.

A: I have had the opportunity to directly ask this question to the Mac Outlook team. The answer is that this is by design. When you click on a hyperlink Outlook doesn't first check to see what kind of link it is. Outlook asks OS X to decide how to open the hyperlink. If some email app other than Outlook is the current default email app then that's what will open the mailto: hyperlink.

A: SImple solution. you need to set your default mail app.  Read here:
https://support.apple.com/en-us/HT201607


text:
Q: Homebrew installation of ffmpeg is not detecting librsvg-2.0 I'm attempting to use homebrew to build and install ffmpeg (homebrew currently uses 5.1.2) with SVG support on macOS (12.5.1, M1 Pro) . This requires the use of librsvg (homebrew currently uses 2.55.1).
During the (re-)installation, the process fails with:

ERROR: librsvg-2.0 not found using pkg-config

The following was done:

*

*brew edit ffmpeg to include depends_on "librsvg" below the existing dependencies, and --enable_librsvg within the installation args.

*brew reinstall ffmpeg --build-from-source (ffmpeg was installed prior).

librsvg is detected as a dependency and installed prior to the re-installation of ffmpeg, as seen in its installation log.
Running pkg-config --exists librsvg-2.0 returns exit code 0. This is what ffmpeg uses to check for dependencies at point of build.
Result of brew config: ([...] changes are mine)
HOMEBREW_VERSION: 3.6.17-57-gea0b786
ORIGIN: https://github.com/Homebrew/homebrew-core
HEAD: ea0b786[...]fc234e
Last commit: 10 hours ago
Core tap ORIGIN: https://github.com/Homebrew/homebrew-core
Core tap HEAD: 3635b0d[...]a7df1b
Core tap last commit: 55 minutes ago
Core tap branch: master
HOMEBREW_PREFIX: /opt/homebrew
HOMEBREW_CASK_OPTS: []
HOMEBREW_MAKE_JOBS: 10
Homebrew Ruby: 2.6.8 => /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby
CPU: 10-core 64-bit arm_firestorm_icestorm
Clang: 13.1.6 build 1316
Git: 2.39.0 => /opt/homebrew/bin/git
Curl: 7.79.1 => /usr/bin/curl
macOS: 12.5.1-arm64
CLT: 13.4.0.0.1.1651278267
Xcode: N/A
Rosetta 2: false

There are no envvar overrides such as PKG_CONFIG_PATH as far as I can see in my session.
I imagine these are being set / changed during brew's installation process, but librsvg's folder is included in the path list within the env vars shown when the installation is ran with -vvv.
Oddly, I had ran through the same process about a month ago and it had worked. I'm not sure what's changed since!
The librsvg package can be found alongside all other brew packages in /opt/homebrew/Cellar[/librsvg], and /opt/homebrew/opt[/librsvg]


text:
Q: add_rewrite_rule behaving strangely I'm customizing another plugin by changing the rewrite rule, from:
    add_rewrite_rule('^api/auth/([0-9]+)?/?','index.php?__api=1&uid=$matches[1]','top');

to:
    add_rewrite_rule('^api/auth/','index.php?__api=1','top');

After making the change (and not forgetting to refresh the permalinks) my endpoint fails to work. When I attempt something like:
file_get_contents("http://mydomain.com/api/auth/")

...instead of the json object that should be returned, I get the user login form.

What's even weirder is that when I add an integer to the end like this:
file_get_contents("http://mydomain.com/api/auth/3")

...I get the json object that I expect! What's going on here?

A: So I've solved this problem, but I'm still scratching my head about the "solution":
add_rewrite_rule('api/autho/?$','index.php?__api=1','top');

This version of the rewrite rule works for some reason. I'm guessing that there's some sort of namespace conflict that I accidentally stumbled across. Maybe /auth/ is used somewhere else?


text:
Q: Continuous mapping onto itself s.t. $f(A) = A$ where $A$ is closed
Let $f$ be a continuous mapping of a Hausdorff non-separable space $(X,\tau)$ onto itself. Prove that there exists a proper non-empty closed subset $A$ of $X$ such that $f(A) = A$.
[ Hint: Let $x_0 \in X$ and define a set $S = \{x_n : n \in \mathbb{Z}\}$ such that $x_{n+1} = f(x_n)$ for every integer n ]
Is the above result true if $(X,\tau)$ is separable? (Justify your answer.)

I can find some examples of such maps and closed sets.
Let $f$ be a continuous function:
$$f: \mathbb{R} \to \mathbb{R}$$
$$f(x) = -x$$
and let set $A = \{-1, 1\}$. Then $A$ is closed, proper and non-empty and $f(A) = A$.
I need some help with general proof. If at some stage $f(x_n) = x_0$ then sequence $\{f(x_n)\}$ is finite and closed. Otherwise it's infinite countable. Can't guess how to use non-separability here ...

A: Let $A=\overline{\{x_n\,|\,n\in\mathbb{N}\}}$. Since $X$ is non-separable, $A\neq X$. On the other hand, $A$ is closed and $f(A)=A$.
On the other hand, if $S^1=\{z\in\mathbb{C}\,|\,|z|=1\}$ and $f\colon S^1\longrightarrow S^1$ is defined by $f(z)=e^{i\theta}z$, where $\theta\in\mathbb R$ is such that $\frac\theta\pi\notin\mathbb Q$, then there is no such $A$.

A: You can choose as $A=cl(S)$ and in this case your set is closed and proper (and oviously non-empty) because if $cl(S)=A=X$ than X is separable ($S$ is a countable set) and so $A\neq X$
Now we prove that $f(A)=A$:
$f(S)=S$ and so $ f(A)=f(cl(S))\subset cl(f(S))=cl(S)=A$ and for the other side you can use the property $T_2$


text:
Q: bash script with permanent ssh connection I use a bash script which runs
/usr/bin/ssh -f -N -T -L8888:127.0.0.1:3306 serveradmin@34.324.234.23

However, when I run the bash script, it waits.. I see the connection coming up but the script doesn't exit.. it's like it's waiting for the SSH process to finish, because when I manually kill it the bash script finishes as well.
Any ideas how to resolve this?
UPDATE:
I have croned this script.. and the cron process is the one that becomes a zombie.. the actual scripts runs just fine, sorry about that, with ps -auxf I get:
root       597  0.0  0.7   2372   912 ?        Ss   Jul12   0:00 cron
root      2595  0.0  0.8   2552  1064 ?        S    02:09   0:00  \_ CRON
1001      2597  0.0  0.0      0     0 ?        Zs   02:09   0:00      \_ [sh] <defunct>
1001      2603  0.0  0.0      0     0 ?        Z    02:09   0:00      \_ [cron] <defunct>

and when I kill the ssh the defuncts disappear.. why would they become defunct?

A: It seems you're trying to reimplement bits of autossh (apt-get install autossh).
Create a RSA key pair without a passphrase, install the public key on serveradmin@34.324.234.23 and try:
autossh -f -N -L8888:127.0.0.1:3306 serveradmin@34.324.234.23

A: Detach ssh process from your terminal:

*

*Send it to background
/usr/bin/ssh -f -N -T -L8888:127.0.0.1:3306 serveradmin@$34.324.234.23 &

*Nohup it
nohup /usr/bin/ssh -f -N -T -L8888:127.0.0.1:3306 serveradmin@$34.324.234.23

A: Remove the $.
workstation:~$ /usr/bin/ssh -f -N -T -L8888:127.0.0.1:3306 server.host.com
DSA host key for IP address '205.205.219.5' not in list of known hosts.
workstation:~$ ps x | grep '\-f'
16170 ?        S      0:00 /usr/bin/ssh -f -N -T -L8888:127.0.0.1:3306 server.host.com

It goes straight to the background as you detail for me.  I do have a keypair setup on my test server, however.
Do you already have something listening on 8888 on your local server?  Do you already have an instance in the background?


text:
Q: How to check if the element is visible using jQuery? I'm using
$('#analytics').toggle("slide");

to toggle an item's visibility. But when I try to check if it's visible using
$('#analytics').is(":visible")
It always shows up as visible once it was toggled visible once...
What is the best way of checking the item's visibility if it's controlled using jQuery toggle function?

A: I think display is what you are looking for:
EDIT
I just tried your own $('#analytics').is(":visible") and think there might be a problem with your timing (think asynchronous); try this code which waits until the animation ends before querying for visibility, at least in the snippet works, I would really appreciate your feedback.

$('button').click(function(){
  $('#analytics').toggle("slide", function(){
    console.log($('#analytics').is(":visible") ? 'visible':'hidden');
  });

});

analytics

<button>button</button>


text:
Q: HTTP Basic Auth Upon Image View (.htaccess) I saw this and I'd love to know how to recreate it. Unfortunately, I don't know .htaccess.
Upon viewing an image, there was an HTTP Basic Auth style dialog that asked to enter some sort of authentication (albeit nothing actually submitted anywhere).
I'm sorry for the skid question, but I'd really love some insight as to how this can be done using .htaccess or .htpasswd.
Thanks.

A: In your apache site conf, add something like:
Alias /image /path/to/img
 <Directory "/path/to/img">
     AuthType Basic
     AuthName "LoginImage"
     AuthUserFile /path/to/.htpasswd
     Require valid-user
  </Directory>

Then, create the .htpasswd file with:
htpasswd -c .htpasswd someusername

and you'll be prompted to create a password.


text:
Q: Centos7: How to change desktop icons size? After Centos updated recently the desktop icons became huge.
How do I make them smaller again?
Edit: I already tried
gsettings set org.gnome.nautilus.icon-view default-zoom-level small
but it did not work for me.

A: Open any folder explorer, and hit the options (3 lines) in the top right corner, and use the - ##% + buttons to change the icon size.  (This also modifies the desktop icon size.)

A: On CentOs Linux 7, to reduce the desktop icon size, right click the icon and select Resize icon from  the drop-down menu.
For the folder icons, use the solution suggested by @selenium (though it no more effects the desktop icons)


text:
Q: How to convert HTML form to C# for PayPal subscription I have the following HTML which works well for subscription payments in my test environment.
<form action="paypalWebAddress" method="post" target="_top">
    <input type="hidden" name="cmd" value="_xclick-subscriptions"/>
    <input type="hidden" name="business" value="myPaypalAccountId"/>
    <input type="hidden" name="paymentaction" value="sale"/>
    <input type="hidden" name="item_name" value="Subscription For abc123"/>
    <input type="hidden" name="currency_code" value="GBP"/>
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="a3" value="50"/>
    <input type="hidden" name="p3" value="6"/>
    <input type="hidden" name="t3" value="M"/>
    <input type="hidden" name="src" value="1" />
    <input type="hidden" name="srt" value="0" /><!--needs to be never ending-->
    <input type="hidden" name="return" value="www."/>
    <input type="hidden" name="notify_url" value="www."/>
    <input type="hidden" name="cancel_url" value="www."/>
    <input type="hidden" name="custom" value="abc123"/>
    <input TYPE="hidden" name="charset" value="utf-8">
    <input type="hidden" name="bn" value="Me_Subscribe_WPS_UK" />
    <input type="submit" name="submit" value="Make Payment"/>
</form>

I'm about to go live and concerned that some one could easily manipulate the DOM and I'm suddenly sending bogus payments. I feel it would be safer to somehow post these values from the code behind so the user can't tamper with the values but, the user will still need to use the PayPal interface in their browser to log in and subscribe.
PayPal-NET-SDK has a quick start and shows how to get going. I have completed this (copied and pasted and ran in debug mode) and it executes fine. However, this doesn't cover subscriptions, probably for the reason explained above (and would probably prevent them accessing the PayPal gui in their browser).
I get the option in the PayPal dashboard area to create a button and reference by button, but, this won't work for me as I need to be able to set the custom field per subscription as a user can subscribe to 1 or more services and each service is unique to that user.
I can't understand how to achieve this

A: If I understand this right, every subscription is unique per customer in your case and that won't work with the static buttons, so the API seems the only way to go.
The PayPal API does cover subscriptions, they're called Billing Plans. Because each subscription is different, you could create a new Billing Plan for each unique service (or combination of services). This can be done without any intermediate SDK using the HttpClient directly to their API.
Alternatively, the PayPal-NET-SDK you mentioned also seems to cover Billing plans. Their Sample application has quite a lot of examples on how to create, enumerate and issue Billing Plans. Make sure you check out the billing_agreement_tokens collection on the Payment class. You might add multiple "service" tokens there.
No matter how close you are to releasing, a lot of testing still seems to be in order here.

A: You can try using HttpClient, something like this will help
    HttpContent content = new FormUrlEncodedContent(
            new List<KeyValuePair<string, string>> {
                new KeyValuePair<string, string>("key1",
      "value1"),
                new KeyValuePair<string,string>("key2","value2")
            });
        content.Headers.ContentType = new
       MediaTypeHeaderValue("application/x-www-form-
       urlencoded");
        content.Headers.ContentType.CharSet = "UTF-8";
        HttpResponseMessage resposne = await
        client.PostAsync(new Uri("paypalWebAddress"),
       content);

A: You should not hardcode the values in forms, instead you should create an API in the backend which will return the correspoding values.Then you can dynamically create the form based on the response of the API.
Make sure you create this form after you have received the response from the API.You can have a check like if response is null show some spinner.
<form action="paypalWebAddress" method="post" target="_top">
    <input type="hidden" name="cmd" value="{response.cmd}"/>
    <input type="hidden" name="business" value={response.business}"/>
    <input type="hidden" name="paymentaction" value={response.action}/>
    <input type="hidden" name="item_name" value="{response.item}"/>
 <input type="submit" name="submit" value="Make Payment"/>
</form>

A: <form action="https://www.paypal.com/cgi-bin/webscr" method="post">
  <input type="hidden" name="cmd" value="_xclick">
  <input type="hidden" name="business" value="business.test.com">
  <input type="hidden" name="item_name" value="Memory Stick">
  <input type="hidden" name="item_number" value="MEM32507725">
  <input type="hidden" name="amount" value="3">
  <input type="hidden" name="tax" value="1">
  <input type="hidden" name="quantity" value="1">
  <input type="hidden" name="currency_code" value="USD">

  <!-- Enable override of buyers's address stored with PayPal . -->
  <input type="hidden" name="address_override" value="1">
  <!-- Set variables that override the address stored with PayPal. -->
  <input type="hidden" name="first_name" value="John">
  <input type="hidden" name="last_name" value="Doe">
  <input type="hidden" name="address1" value="345 Lark Ave">
  <input type="hidden" name="city" value="San Jose">
  <input type="hidden" name="state" value="CA">
  <input type="hidden" name="zip" value="95121">
  <input type="hidden" name="country" value="US">
  <input type="image" name="submit"
    src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"
    alt="PayPal - The safer, easier way to pay online">
</form>

On Click on buy now :
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

  <!-- Identify your business so that you can collect the payments. -->
  <input type="hidden" name="business" value="herschelgomez@xyzzyu.com">

  <!-- Specify a Buy Now button. -->
  <input type="hidden" name="cmd" value="_xclick">

  <!-- Specify details about the item that buyers will purchase. -->
  <input type="hidden" name="item_name" value="Premium Umbrella">
  <input type="hidden" name="amount" value="50.00">
  <input type="hidden" name="currency_code" value="USD">

  <!-- Prompt buyers to enter the quantities they want. -->
  <input type="hidden" name="undefined_quantity" value="1">

  <!-- Display the payment button. -->
  <input type="image" name="submit" border="0"
    src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif"
    alt="Buy Now">
  <img alt="" border="0" width="1" height="1"
    src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" >

</form>


text:
Q: Bash: How do I round a variable down to the next even number? Say I've got an integer variable from a parameter $1 that's 1025.
I need it to be 1024. How can I round it down?

A: You can write arithmetic expressions with this syntax:
$(( expr ))

So you'd want something like:
$(( $1 - ($1 % 2) ))

A: You can do:
round() {
    echo $(( ${1:?need one argument} / 2 * 2))
}

round 1025
1024

round 1024
1024

A: This should work:
(( $(echo $var%2|bc) != 0 )) && ((var--))
echo $var


text:
Q: Perl - have a comma separated output , want to write that in a CSV Here is the code:
my @col= sort keys %colnames;

print "mRNA,".join(",",@col)."\n";
foreach my $row(keys %rownames){
    print "$row";
    foreach my $col(@col){
        my $num=$mat{$col}->{$row};
        $num=~s/(\.\d\d)\d+/$1/;
        print ",$num";
    }
    print "\n";
}

Output:
mRNA,Benzopyrene12h_replica1,Benzopyrene12h_replica2
E2F1,5.01,4.72
REV1,2.76,2.67
POLK,1.21,1.87
POLH,1.49,1.56
POLI,1.94,2.45

Please help me write this output to .csv file.

A: Something like this might work... Combining with Miller's answer. I didn't test it, just giving you an idea. And it's defiantly could be written more cleanly and less redundant.
use strict;
use warnings;
use autodie;

my $csvFile = Text::CSV->new ( { binary => 1, eol => "\n" } )
                or die "Cannot use CSV: ".Text::CSV->error_diag ();

my @col= sort keys %colnames;
my @csv;

$csv[0][0] = "mRNA,";
my @joinCol = join(",",@col);
my $i =1;
foreach (@joinCol) {
    $csv[0][$i] = $_;
    $i++;
}

my $k = 1;
foreach my $row(keys %rownames){
    my $j = 0;
    print "$row";
    $csv[$k][$j] = $row;
    foreach my $col(@col){
        my $num=$mat{$col}->{$row};
        $num=~s/(\.\d\d)\d+/$1/;
        print ",$num";
        $csv[$k][$j] = $num;
        $j++;
    }
    print "\n";
    $k++;
}

open $fh, '>', "new.csv" or die "Couldn't open csv file: $! \n";

for (@csv) {
    $csvFile->print($fh, $_);
}

close $fh;

A: To write to a CSV file, use Text::CSV
use strict;
use warnings;
use autodie;

# Your Data Initialization
my %colnames; # = Something
my %rownames; # = Something else
my %mat; # = a hash of hash

# Prepare CSV
my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
                or die "Cannot use CSV: ".Text::CSV->error_diag ();
open $fh, '>', "new.csv";

my @col = sort keys %colnames;

# Output Header
$csv->print($fh, ['mRNA', @col]);

# Output Rows
for my $row (keys %rownames){
    my @data = ($row);
    for my $col (@col){
        my $num = $mat{$col}{$row};
        $num =~ s/(\.\d\d)\d+/$1/;
        push @data, $num;
    }
    $csv->print($fh, \@data);
}

close $fh;


text:
Q: JaxRS validate java.lang.Long as @QueryParam I have an JaxRS API like this :
@GET
@Path("list")
public Response list(@QueryParam("id") Long id) {
...
}

How can i handle exception when send non digits parameter as id ?
actually i can not found any validation annotation on JakartaEE framework for handle this problem .
example request :
curl http://localhost:8080/api/list?id=ABCD

NOTE: I won't change Long to String .

A: You should add validate annotation after @QueryParam:
@GET
@Path("list")
public Response list(@QueryParam("id")
                     @Min(value=0L, message="insert number value")
                     Long id) {
...
}

A: Finally i catch that exception.
first of all:
I try to handle this problem with this annotations :
@Min
@PositiveOrZero
@Pattern(regexp = "\\[0-9]+") or @Pattern(regexp = "\\d+")
@Digits
...

None of them worked, Because that string must first be converted into a number and then validated. so JaxRs could not do that !
I used this solution:
@Provider
public class NumberExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(Exception exception) {
        Exception numberFormatException = getNumberFormatException(exception);
        if (numberFormatException != null) {
            return Response.status(Response.Status.BAD_REQUEST).entity("Invalid Parameter").build();
        } else {
            return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
        }
    }

    private Exception getNumberFormatException(Exception e) {
        if (e instanceof NumberFormatException nfe) return nfe;
        return getNumberFormatException((Exception) e.getCause());
    }
}

Worked without any problem .
Thank you .


text:
Q: mySQL database efficienty question I have a database efficiency question.
Here is some info about my table:
-table of about 500-1000 records
-records are added and deleted every day.
- usually have about the same amount being added and deleted every day (size of active records stays the same)
Now, my question is.....when I delete records,...should I (A) delete the record and move it to a new table?
Or,...should I (B) just have and "active" column and set the record to 0 when it is no long active.
The reason I am hesitant to use B is because my site is based on the user being able to filter/sort this table of 500-1000 records on the fly (using ajax)....so I need it to be as fast as possible,..(i'm guessing a table with more records would be slower to filter)...and I am using mySQL InnoDB.
Any input would be great, Thanks
Andrew

A: ~1000 records is a very small number.
If a record can be deleted and re-added later, maybe it makes sense to have an "active" indicator.

A: Realistically, this isn't a question about DB efficiency but about network latency and the amount of data you're sending over the wire.  As far as MySQL goes, 1000 rows or 100k rows are going to be lightning-fast, so that's not a problem.
However, if you've got a substantial amount of data in those rows, and you're transmitting it all to the client through AJAX for filtering, the network latency is your bottleneck.  If you're transmitting a handful of bytes (say 20) per row and your table stays around 1000 records in length, not a huge problem.
On the other hand, if your table grows (with inactive records) to, say, 20k rows, now you're transmitting 400k instead of 20k.  Your users will notice.  If the records are larger, the problem will be more severe as the table grows.
You should really do the filtering on the server side.  Let MySQL spend 2ms filtering your table before you spend a full second or two sending it through Ajax.

A: It depends on what you are filtering/sorting on and how the table is indexed.
A third, and not uncommon, option, you could have a hybrid approach where you inactivate records (B) (optionally with a timestamp) and periodically archive them to a separate table (A) (either en masse or based on the timestamp age).
Realistically, if your table is in the order 1000 rows, it's probably not worth fussing too much over it (assuming the scalability of other factors is known).

A: If you need to keep the records for some future purpose, I would set an Inactive bit.
As long as you have a primary key on the table, performance should be excellent when SELECTing the records.
Also, if you do the filtering/sorting on the client-side then the records would only have to be retrieved once.


text:
Q: Asset pipeline in namespace, what am I doing wrong? I have split my app up into two part: A website part, and a /admin-part, with seperate javascripts and stylesheets.
I have converted all my admin plugins to fit this structure:
vendor/assets/ADMIN/mws
|-- index.js
|-- images/
|    |-- <various button/gradient images>
|-- javascripts/
|    |-- mws.js
|-- stylesheets/
|    |-- mws-buttons.css
|        mws-horizontal.css

vendor/assets/ADMIN/mws/index.js:
//= require mws
//= require_tree .

In my layout-file:
<%= javascript_include_tag "admin/mws" %>

^ this gives a 404 pointing to http://127.0.0.1:3000/assets/admin/mws.js
rails c
Loading development environment (Rails 3.2.2)
1.9.3p125 :001 > Rails.application.config.assets.paths
=> ["/Users/me/Projects/rails-project/vendor/assets/admin"]

What am I doing wrong?

A: You want the manifest in the javascript_include_tag so in your case
<%= javascript_include_tag 'admin/index' %>

I don't think the
//= require mws
Is correct


text:
Q: On Facebook's own website LIKE buttons are instantanious, but on my website they can take up to 30 seconds to render This question has been bugging me for a long time, and since I found no discussion of it anywhere, I figured I'd finally start one.
If you go to Facebook's own website (Example: here), and scroll to the bottom of the page, you will see an implementation of the "Like + Share" buttons.
These are the same buttons which you can implement on your own website as well (Facebook Like Button Configurator), with one major difference:
On Facebook's own website the buttons load instantaneously, and by that I mean there is not even a 1 second delay. They render as if they were regular text. It's that fast.
However, it is a completely different story when it comes to rendering these buttons when embedding them on your website. These facebook 'like' elements are always the last to load and are the slowest. For first time visitors it can take up to 20-30 seconds for the facebook elements to render.
The code is implemented to the letter as such:
<!DOCTYPE html>

...

I tried adding dns-prefetch headers in the  tag for facebook's domains hoping to speed things up, but it doesn't seem to have had much effect.

<link rel="dns-prefetch" href="//www.facebook.com" />
<link rel="dns-prefetch" href="//staticxx.facebook.com" />
<link rel="dns-prefetch" href="//connect.facebook.net" />

I tried digging a little deeper, and one difference I noticed from looking at the code used on facebook.com's implementation was that they used the fbml version of the code <fb:like></fb:like>, as opposed to the code that they provide us, the end users, to implement the buttons on our own websites.
I've also noticed that there was no link to "http://connect.facebook.net/en_US/sdk.js", which is the script we are meant to use. This seems to suggest facebook are perhaps using a custom stripped down version of the script specific to their implementation of the 'like buttons' only?
This is just my limited analysis, as I'm an amateur web developer and am no expert in xbml. Hope someone can shed some light on this.
One thing that is for certain: Facebook's own implementation of the "LIKE" buttons is totally different from the one they are instructing us to do, and the speed difference is astronomical.
Can anyone shed some light on this?
Ideally, can anyone suggest how to make our implementation of the "like button" code more like that of Facebook's own implementation, so that we can also enjoy the speed benefits?


text:
Q: How to skip first two numbers in provide argument? (python) I'm having issues skipping or trimming the first two numbers in a provided argument.
As an example I am passing the value of "00123456" to 'id'. I want the request.args.get against 123456 instead 00123456. is there a function I can use to drop off the zero's. Also relatively new to the python world so please advise if I need to provide more info.
@main.route('/test')
def test():
    """
    Test route for validating number
    example - /test?id=00123456
    """

    # Get number passed in id argument
    varNum = request.args.get('id')

A: You can convert the "00123456" to an int and it will remove all the zeros at the start of the string.
print(int("00123456"))

output:
123456

Edit:
Use this only if you want to remove any zeros at the start of the number, if you want to remove the first two chars use string slicing.
Also, use this only if u know for sure that the str will only contain numbers.

A: You can use string slicing, if you know that there are always two zeroes:
varNum = request.args.get('id')[2:]

Alternatively, you can use .lstrip(), if you don't know how many leading zeroes there are in advance:
varNum = request.args.get('id').lstrip('0')


text:
Q: get process mdoules c# with kernel.dll I'm getting some trouble while running this:
    public MODULEENTRY32 getModule(String ModuleName)
    {
        MODULEENTRY32 module32;
        module32.dwSize = (uint) Marshal.SizeOf(typeof(MODULEENTRY32));
        IntPtr hSnap = CreateToolhelp32Snapshot(SnapshotFlags.TH32CS_SNAPMODULE | SnapshotFlags.TH32CS_SNAPMODULE32, (uint) process.Id);
        Module32First(hSnap, out module32);
        if (hSnap == IntPtr.Zero)
        {
            return new MODULEENTRY32();
        }
        do
        {
            if (module32.szModule.Equals(ModuleName))
            {
                CloseHandle(hSnap);
                return module32;
            }
        } while (Module32Next(hSnap, out module32));
        return new MODULEENTRY32();
    }

I was trying to get modules from a process but it always return 0,
I'm sure that the module name is corrent and the process id too

A: I don't think you have provided enough information to determine what the problem is.
If you read the CreateToolHelp32Snapshot documentation you should check if hSnap returned is INVALID_HANDLE_VALUE (-1).  If it is, you need to call GetLastError to determine the reason for the failure.
Possible reasons for failures are documented:

If the specified process is the Idle process or one of the CSRSS
  processes, this function fails and the last error code is
  ERROR_ACCESS_DENIED because their access restrictions prevent
  user-level code from opening them.
If the specified process is a 64-bit process and the caller is a
  32-bit process, this function fails and the last error code is
  ERROR_PARTIAL_COPY (299).

and:

When taking snapshots that include heaps and modules for a process
  other than the current process, the CreateToolhelp32Snapshot function
  can fail or return incorrect information for a variety of reasons. For
  example, if the loader data table in the target process is corrupted
  or not initialized, or if the module list changes during the function
  call as a result of DLLs being loaded or unloaded, the function might
  fail with ERROR_BAD_LENGTH or other error code. Ensure that the target
  process was not started in a suspended state, and try calling the
  function again. If the function fails with ERROR_BAD_LENGTH when
  called with TH32CS_SNAPMODULE or TH32CS_SNAPMODULE32, call the
  function again until it succeeds.


text:
Q: How to configure global transactionmanager in spring-boot with atomikos and hikari This i my database configuration and app.properties
@Configuration
public class DatabaseConfig {

    @Bean
    @ConfigurationProperties(prefix = "datasource.two")
    public HikariConfig hikariConfig2() {
        return new HikariConfig();
    }

    @Bean
    public DataSource dataSource2() {
        HikariDataSource hds = new HikariDataSource(new hikariConfig2());
        return hds;
    }

    @Bean
    public JdbcTemplate jdbcTemplate2() {
        return new JdbcTemplate(dataSource2());
    }

    @Bean
    @ConfigurationProperties(prefix = "datasource.one")
    public HikariConfig hikariConfig2() {
        return new HikariConfig();
    }

    @Bean
    public DataSource dataSource1() {
        HikariDataSource hds = new HikariDataSource(hikariConfig1());
        return hds;
    }

    @Bean
    public JdbcTemplate jdbcTemplate1() {
        return new JdbcTemplate(dataSource1());
    }

}

and
datasource.one.jdbc-url=...
datasource.one.username=...
datasource.one.password=...
datasource.one.driver-class-name=...

datasource.two.jdbcUrl=...
datasource.two.username=...
datasource.two.password=...
datasource.two.driver-class-name=...

How should I create global transaction manager which will support two phase commit. I want to run this app inside docker with Tomcat so no JavaEE.
Also no hibernate. I am using sql-processor with spring-stack:
PS: In some very old article I found this but idk if it rigth sollution
@Bean
public DataSourceTransactionManager tm1() {
    DataSourceTransactionManager txm = new DataSourceTransactionManager(refDataSource());
    return txm;
}

@Bean
public DataSourceTransactionManager tm2() {
    DataSourceTransactionManager txm = new DataSourceTransactionManager(logDataSource());
    return txm;
}

@Bean(name = "transactionManager")
@Primary
public PlatformTransactionManager transactionManager() throws Throwable {
    return new ChainedTransactionManager(tm1(), tm2());

}


text:
Q: Get Koa Actual route I am new in koa. I need to get a actual route in koa request.
Example 1 : If i hit a route  /user and i get the ctx origin url /user/.
Example 2 : If i hit a route user/:id and i get the ctx origin url /user/1.
I try to get the path like
exports.checkAuth = async ctx => {
   console.log(ctx.originalUrl); // return -> /user/1
   console.log(ctx.path); // return -> /user/1
 };

I want to get the actual route path like user/:id in each request .
In express route get a actual path like this
 app.get('/user/:id', function userIdHandler(req, res) {
     console.log(req.route);
 });

Output:
{ path: '/user/:id',
stack:
   [ { handle: [Function: userIdHandler],
   name: 'userIdHandler',
   params: undefined,
   path: undefined,
   keys: [],
   regexp: /^\/?$/i,
   method: 'get' } ],
methods: { get: true } }

A: In koa.js when a route is matched, its path is available at ctx._matchedRoute and if named, the name is available at ctx._matchedRouteName
ctx._matchedRoute -> which will return in your case user/:id
Just keep in mind that ctx._matchedRoute is part of koa-router.


text:
Q: Accessing C# List variable in JavaScript C#
public List<double> Coordinatesx = new List<Double>();
    public List<double> Coordinatesy = new List<Double>();

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
         SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["TRY"].ConnectionString);
        string query = "select x,y from Addresses";
        cnn.Open();
        SqlCommand cmd = new SqlCommand(query, cnn);
        SqlDataReader id = cmd.ExecuteReader();
        while(id.Read())
        {
            Coordinatesx.Add(Convert.ToDouble(id[0]));
            Coordinatesy.Add(Convert.ToDouble(id[1]));
         }
         cnn.Close();

   }

JAVASCRIPT
function calculateinside()
    {

         for (var j = 0; j < <%=Coordinatesx.Count%>; j++) {
             var point = new google.maps.LatLng(<%=Coordinatesx%>[j],<%=Coordinatesy%>[j]);
             if(google.maps.geometry.poly.containsLocation(point,poly)){
                 marker2 = new google.maps.Marker({

                     position: point,
                     map: map,
                     icon: 'images/point2.png',

                 });
             }
      }

    }   }

I am trying to take variables from c# to javascript, I have tried that code but there is an error.
var point = new google.maps.LatLng(<%=Coordinatesx%>[j],<%=Coordinatesy%>[j]);

How can I access each value of Coordinatesx and Coordinatesy list?

A: You must generate the arrays in the javascript code:
function calculateinside()
{
     var Coordinatesx = [<%=string.Join(",", Coordinatesx)%>];
     var Coordinatesy = [<%=string.Join(",", Coordinatesy)%>];
     for (var j = 0; j < Coordinatesx.lenght; j++) {
         var point = new google.maps.LatLng(Coordinatesx[j],Coordinatesy[j]);
         if(google.maps.geometry.poly.containsLocation(point,poly)){
             marker2 = new google.maps.Marker({

                 position: point,
                 map: map,
                 icon: 'images/point2.png',

             });
         }
     }
}

if Coordinatesx = {1,2} and Coordinatesy = {5,7} in server-side code, it will generate the javascript like this:
function calculateinside()
{
     var Coordinatesx = [1,2];
     var Coordinatesy = [5,7];
     for (var j = 0; j < Coordinatesx.lenght; j++) {
         var point = new google.maps.LatLng(Coordinatesx[j],Coordinatesy[j]);
         if(google.maps.geometry.poly.containsLocation(point,poly)){
             marker2 = new google.maps.Marker({

                 position: point,
                 map: map,
                 icon: 'images/point2.png',

             });
         }
     }
}

You can see this, by viewing the page's html source.


text:
Q: SimpleCursorTreeAdapter constructor not being called on Android 2.2 On Android 2.2 mContext=context (or anything else I put there) is never called. It does work on 2.3+.
Is it a known issue? Is there a workaround?
public class ExpListCursorAdapter extends SimpleCursorTreeAdapter {
    Context mContext;

    public ExpListCursorAdapter(Context context, Cursor cursor,
            int groupLayout, String[] groupFrom, int[] groupTo,
            int childLayout, String[] childFrom, int[] childTo) {
         super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childFrom,
            childTo);
        mContext=context;
}

    @Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {
        int id=groupCursor.getInt(DatabasePazienti.ROWID);
        DatabaseTests mDbTests=new DatabaseTests(mContext);
        mDbTests.open();

        Cursor cursor=mDbTests.fetchPatientTests(id);
        return cursor;
    }

A: I confirm that is an Android 2.2 bug (even if I couldn't find any reference of it). I included SimpleCursorTreeAdapter.java from Android 2.3.3 in my package and now it works.

A: The implementation of SimpleCursorTreeAdapter in the API 2.2 is different from API 2.3.
As you can see in here:
API 2.2

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/widget/SimpleCursorTreeAdapter.java

API 2.3

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3_r1/android/widget/SimpleCursorTreeAdapter.java

When you use API 2.2 it says mContext = context is never called due to the sequence of the methods that are called in the constructor.


text:
Q: Specific style on an ordered list I'd like some help to integrate a design made on sketch 2 years ago ! The goal is to do a beautiful orderer list but I have difficulties to integrate the content.
This is what i've done so far :
HTML :

 50%

60%

70%

80%

90%

CSS :
.stepbar_block {
  margin: 0;
  padding: 0;
  counter-reset: step;
  position: relative;
  margin-top: 40px;
}

.stepbar_block:before {
  width: 1px;
  height :10px;
  background-color : rgba(87,87,86,0.3);
  content : '';
  position : absolute;
  left : 30px;
  top : -4px;
}

.stepbar_block:after {
  width: 1px;
  height :10px;
  background-color : rgba(87,87,86,0.3);
  content : '';
  position : absolute;
  right : 30px;
  top : -4px;
}

.stepbar_list li {
  list-style-type: none;
  float: left;
  width: 20%;
  height : 5px;
  position: relative;
  font-family: Roboto;
  font-size: 10px;
  line-height: 11px;
  text-align: center;
  color: rgba(87,87,86,0.5);
}

.stepbar_list:after {
    content: '';
  position: absolute;
  height: 1px;
  background-color: rgba(87,87,86,0.3);
  left: 30px;
  right: 30px;
  z-index: 3;
}

.stepbar_list li:before {
  content : '';
  counter-increment: step;
  width: 5px;
  height: 5px;
  border: 1px solid black;
  display: block;
  background-color : black;
  border-radius: 40px;
  text-align: center;
  margin: -2px auto 10px auto;
}

.stepbar_list_item:after {
  content: counter(step);
  position: absolute;
  top: -25px;
  background-color: white;
  left: 0;
  right: 0;
  color: rgba(87,87,86,0.5);
    font-size: 10px;
  line-height: 11px;    text-align: center;
}

.stepbar_list_elem_active:after {
    content: counter(step);
  position: absolute;
  top: -25px;
  background-color: red;
  left: 0;
  right: 0;
}

.stepbar_list_elem_current:after {
    content: counter(step);
  position: absolute;
  top: -25px;
  background-color: blue;
  left: 0;
  right: 0;
}

https://jsfiddle.net/zawt9hL6/
However I'm able to colorise the items but not the circles, so I'd like to know what is missing because when I play with :before and :after it seems to colorize the whole list item and not a specific content
That is the result i'd like to have

It is possible to have a render like this ? Moreover it's a gradiant background on the circles..
THank you for advices

A: Use something like this for all.
.stepbar_list_elem_active:before {
   width: 10px;
   height: 10px;
   background-color: #fff;
   content: '';
   position: absolute;
   left: 0;
   top: -6px;
   border: 2px solid red;
   border-radius: 50%;
   right: 0;
   margin: 0 auto;
}

A: You can use :before and :after pseudo elements to create that circle with gradient. First you can create just regular circle with gradient and then add one more white circle with other pseudo-element on top of the frist one.

10* {
  box-sizing: border-box;
}
ul {
  display: inline-flex;
  list-style: none;
  position: relative;
  padding: 0;
  margin: 0 50px;
}

ul:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: gray;
}

li {
  padding: 25px;
  position: relative;
}

li:after,
li.color:before {
  position: absolute;
  content: '';
  bottom: 0;
  left: 50%;
  height: 10px;
  width: 10px;
  background: gray;
  border-radius: 50%;
  transform: translate(-50%, 40%);
  z-index: 1;
}
li.color:after {
  width: 20px;
  height: 20px;
  transform: translate(-50%, 9px);
}

li.color:before {
  background: white;
  z-index: 2;
  width: 10px;
  height: 10px;
}

li.yellow:after {
    background: linear-gradient(to right, rgba(240,184,88,1) 0%, rgba(230,139,60,1) 38%, rgba(240,47,23,1) 71%, rgba(231,56,39,1) 100%);
}

li.blue:after {
   background: linear-gradient(to right, rgba(52,163,247,1) 0%, rgba(52,163,247,1) 32%, rgba(19,100,158,1) 71%, rgba(19,100,158,1) 100%);
}

.yellow {
  color: #ED4620;
}

.blue {
  color: #64A3D1;
}

1

2

3

4


text:
Q: How to convert minutes to days, hours, and minutes? I am a beginner to Python so I do not know a lot of terms or anything really. Can I ask on how to convert minutes to hours and minutes
EX: 75 minutes ->0 days, 1 hour, 15 minutes
print("Welcome to the Scheduler!")
print("What is your name?")
name = input()
print("How many chocolates are there in the order?")
chocolates = input()
print("How many chocolate cakes are there in the order?")
chocolate_cakes = input()
print("How many chocolate ice creams are in the order?")
chocolate_ice_creams = input()
total_time = float(chocolates) + float(chocolate_cakes) + float(chocolate_ice_creams)
print("Total Time:")
print("How many minutes do you have before the order is due?")
minutes = input()
extra_time = float(minutes) - float(total_time)
print("Your extra time for this order is", extra_time)

time = extra_time // 60

print("Thank you,", name)

A: Well if you're given an input in minutes that is greater than equal to 1440 minutes, then you have at least a day. So to handle this (and the other aspects of time) we can use modulus (%).
days = 0
hours = 0
mins = 0

time = given_number_of_minutes
days = time / 1440
leftover_minutes = time % 1440
hours = leftover_minutes / 60
mins = time - (days*1440) - (hours*60)
print(str(days) + " days, " + str(hours) + " hours, " + str(mins) +  " mins. ")

This should work.

A: # Python Program to Convert seconds
# into hours, minutes and seconds

def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60

    return "%d:%02d:%02d" % (hour, minutes, seconds)

# Driver program
n = 12345
print(convert(n))

method = a
import datetime
str(datetime.timedelta(seconds=666))
'0:11:06'

method = b
def convert(seconds):
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%d:%02d:%02d" % (hour, minutes, seconds)

A: from datetime import datetime

day = minutes = hours = 0

day = datetime.now ()
day = day.day
minutes = datetime.now ()
minutes = minutes.minute
hours = datetime.now ()
hours = hours.hour

print ("It's day" + str (day) + "and it's" + str (minutes) + "minutes and" + str (hours) + "hours.")

A: This code above does not work I started to make my own version of how this code could help you remember I am an amateur is true
from datetime import datetime

day = minutes = hours = 0

time = datetime.now().minute
days = time / 1440
leftover_minutes = time % 1440
hours = leftover_minutes / 60
mins = time - (days*1440) - (hours*60)
print(str(days) + " days, " + str(hours) + " hours, " + str(mins) +  " mins. ")

A: You actually have to round down values in order to get integers.
import math

def transform_minutes(total_minutes):

    days = math.floor(total_minutes / (24*60))
    leftover_minutes = total_minutes % (24*60)

    hours = math.floor(leftover_minutes / 60)
    mins = total_minutes - (days*1440) - (hours*60)

    #out format = "days-hours:minutes:seconds"
    out = '{}-{}:{}:00'.format(days, hours, mins)
    return out

A: n = int (input())
day = int (n // 1440)
hours = int (n % 1440) // 60
mins = int (n % 1440) % 60

print(day)
print(hours)
print(mins)


text:
Q: wxPython - how to colour the text of a statusbar I searched for the answer in the forum, but I didn't find anything, if I am wrong, I am sorry.
Anyway, question is simple, I have this Frame, with a Status Bar I use to print messages or notifies.
I would like to use it for mistakes or not permitted operations. But I would like these messages to be coloured. I am looking for a solution on wxPython demo -because i read somewhere on the web to get some inspirations by it-, but i still did not find anything.
Do you have any ideas or solutions?
thank you in advance.

A: I would try the SetForegroundColour or SetBackgroundColour methods of the status bar widget. These methods don't always work on every platform though as each OS has its own rules and wxPython follows those rules. If they do not work, then you'll have to roll your own statusbar, probably by using a couple of panels in a sizer or a splitter window.
There is also the 3rd party EnhancedStatusbar widget which might work for you. It can be found at http://xoomer.virgilio.it/infinity77/main/EnhancedStatusBar.html

A: Simple solution: pin wx.StaticText on the status bar and write text in it. Text coloring in wx.StaticText works well.
For example:
    self.sb = self.ws.CreateStatusBar()
    self.sbtext = wx.StaticText(self.sb, -1, '', pos=(8, 4))
    ...
    self.sbtext.SetForegroundColour(wx.Colour(color))
    self.sbtext.SetLabel(text)


text:
Q: Binding to Auto-value in XAML I guess the auto-value is set after parsed by the binding.
Binding code:
Width="{Binding Capacity, Converter={StaticResource CapacityConverter}, ElementName=LayoutPath}"
Height="{Binding Capacity, Converter={StaticResource CapacityConverter}, ElementName=LayoutPath}"

Source:
<LayoutPath
    x:Name="LayoutPath"
    SourceElement="{Binding ElementName=ellipse}"
    FillBehavior="NoOverlap"
    Orientation="OrientToPath"
    Capacity="auto"
    Padding="34"
    Distribution="Even"/>

It works if I set capacity to a fixed value, but not when it auto-calculates based on total nodes in xml.
Any solution?
-

A: Try binding to ActualCapacity instead.