text:
Q: How to handle development for multiple customers of ours using the Postmates API We would like to develop an app which can be used by multiple customers (of ours). Each app will be customized to each customer of ours.
What we are unsure about is how to handle authentication keys and API keys? Do we create one set of these for each of our customers or do we just have one account and all our customers use the one set of API keys. The latter approach makes me nervous because if one customer is banned (for what ever reason) then all my customers will suffer since they all share the same API key.
Any guidance from Postmates development team would be appreciated.

A: Currently, we do not support provisioning multiple API keys for a single account.
I recommend having each client create an API key. This also would allow your customers to use their own payment method, versus a single payment method for every customer.
Hope this helps, let me know if you have any more questions!


text:
Q: How to compose UIButton from CAGradientLayers and CAShapeLayers? I'd like to recreate a bevel-effect circular UIButton subclass, as pictured below (but with a user-chosen base color). I am confused on how to set the bounds for a CAGradientLayer / masking CAShapeLayer.

I figured to compose this of several CAShapeLayers as I would in SwiftUI. This renders as desired (sans-gradients).

However, when masking a CAGradientLayer with a previously-rendered CAShapeLayer, the gradient is not drawn visibly.

I assume my error is related to bounds/frame setting. When I move the sublayer additions to layoutSubviews(), part of the gradient ring is rendered. Also, the user-color circle obeys constraints set by a parent VC, but the other layers do not.

I've read several posts (1 2, 3, 4) on applying a CAShapeLayer as a mask to a CAGradientLayer, but am failing to understand how to properly set frames for these multiple layers.

extension BeveledButton {

    /// Draws yellow ring in desired location
    func makeEmbossmentRingAsShapeLayer()  -> CAShapeLayer {
        let pathFrame = frame.insetBy(dx: insetBevel, dy: insetBevel)
        let path = CGPath.circleStroked(width: bevelRingWidth, inFrame: pathFrame)

        let shape = CAShapeLayer()
        shape.path = path
        shape.fillColor = UIColor.yellow.cgColor
        return shape
    }

    /// Does not draw gradient (visibly) where yellow ring was
    func makeEmbossmentRingAsGradientLayer()  -> CAGradientLayer {
        let pathFrame = frame.insetBy(dx: insetBevel, dy: insetBevel)
        let path = CGPath.circleStroked(width: bevelRingWidth, inFrame: frame)

        let mask = CAShapeLayer()
        mask.path = path
        mask.fillColor = UIColor.black.cgColor
        mask.lineWidth = 4
        mask.frame = pathFrame

        let gradient = CAGradientLayer(colors: [UIColor.orange, UIColor.green], in: pathFrame)
        gradient.frame = pathFrame
        gradient.mask = mask
        return gradient
    }
}

extension CGPath {

    static func circle(inFrame: CGRect) -> CGPath {
        CGPath(ellipseIn: inFrame, transform: nil)
    }

    static func circleStroked(width: CGFloat, inFrame: CGRect) -> CGPath {
        var path = CGPath(ellipseIn: inFrame, transform: nil)
        path = path.copy(strokingWithWidth: width, lineCap: .round, lineJoin: .round, miterLimit: 0)
        return path
    }
}

extension CAGradientLayer {

    convenience init(colors: [UIColor], in frame: CGRect) {
        self.init()
        self.colors = colors.map(\.cgColor)
        self.frame = frame
    }
}

import UIKit
import Combine

class BeveledButton: UIButton {

    weak var userColor: CurrentValueSubject<UIColor,Never>?
    private var updates: AnyCancellable? = nil

    private lazy var outerRing: CAShapeLayer = makeOuterRing()
    private lazy var innerReflection: CAShapeLayer = makeReflectionCircle()
    private lazy var userColorCircle: CAShapeLayer = makeUserColorCircle()
    private lazy var embossmentRing: CAGradientLayer = makeEmbossmentRingAsGradientLayer()
    //    private lazy var embossmentRing: CAShapeLayer = makeEmbossmentRingAsShapeLayer()

    init(frame: CGRect, userColor: CurrentValueSubject<UIColor,Never>) {
        self.userColor = userColor
        super.init(frame: frame)
        setupRings()
        updateUserColor(userColor)
    }

    required init?(coder: NSCoder) { fatalError("") }

    private let outerRingWidth: CGFloat = 2.5
    private let inset: CGFloat = 3
    private let insetReflection: CGFloat = 5
    private lazy var insetBevel: CGFloat = inset + 1
    private let bevelRingWidth: CGFloat = 2
}

private extension BeveledButton {

    func setupRings() {
        layer.addSublayer(outerRing)
        layer.addSublayer(userColorCircle)
        layer.addSublayer(innerReflection)
        layer.addSublayer(embossmentRing)
    }

    func makeOuterRing() -> CAShapeLayer {
        let path = CGPath.circle(inFrame: frame)
        let shape = CAShapeLayer()
        shape.fillColor = UIColor.clear.cgColor
        shape.strokeColor = UIColor.lightGray.cgColor
        shape.lineWidth = outerRingWidth
        shape.path = path
        return shape
    }

    func makeUserColorCircle()  -> CAShapeLayer {
        let pathFrame = frame.insetBy(dx: inset, dy: inset)
        let path = CGPath.circle(inFrame: pathFrame)

        let shape = CAShapeLayer()
        shape.path = path
        shape.fillColor = userColor?.value.cgColor
        return shape
    }

    func makeReflectionCircle()  -> CAShapeLayer {
        let pathFrame = frame.insetBy(dx: insetReflection, dy: insetReflection)
        let path = CGPath.circle(inFrame: pathFrame)

        let shape = CAShapeLayer()
        shape.path = path
        shape.fillColor = UIColor.lightGray.cgColor.copy(alpha: 0.4)
        return shape
    }

    func updateUserColor(_ userColor: CurrentValueSubject<UIColor,Never>) {
        updates = userColor.sink { [weak self] color in
            UIView.animate(withDuration: 0.3) {
                self?.userColorCircle.fillColor = color.cgColor
            }
        }
    }
}

A: You're on the right track...
The idea is to add 4 sublayers:

*

*"outer" CAShapeLayer

*"ring" CAShapeLayer

*"bevel" CAGradientLayer with CAShapeLayer mask

*"inner" CAGradientLayer with CAShapeLayer mask

Inset the frame of each layer by the width of the previous layer, so:

*

*rect = bounds

*outer layer frame will be rect

*inset rect by "outer width"

*ring layer frame will be that inset rect

*inset rect by "ring width"

*bevel layer frame will be that inset rect

*inset rect by "bevel width"

*inner layer frame will be that inset rect

So layoutSubviews will look something like this:
override func layoutSubviews() {
    super.layoutSubviews()

    var pth: UIBezierPath = UIBezierPath()
    var frameRect: CGRect = .zero
    var pathRect: CGRect = .zero

    frameRect = bounds

    outerLayer.frame = frameRect
    pathRect.size = frameRect.size
    pth = UIBezierPath(ovalIn: pathRect)
    outerLayer.path = pth.cgPath

    frameRect = frameRect.insetBy(dx: outerWidth, dy: outerWidth)

    ringLayer.frame = frameRect
    pathRect.size = frameRect.size
    pth = UIBezierPath(ovalIn: pathRect)
    ringLayer.path = pth.cgPath

    frameRect = frameRect.insetBy(dx: ringWidth, dy: ringWidth)

    bevelGradLayer.frame = frameRect
    pathRect.size = frameRect.size
    pth = UIBezierPath(ovalIn: pathRect)
    bevelLayerMask.path = pth.cgPath

    frameRect = frameRect.insetBy(dx: bevelWidth, dy: bevelWidth)

    innerGradLayer.frame = frameRect
    pathRect.size = frameRect.size
    pth = UIBezierPath(ovalIn: pathRect)
    innerLayerMask.path = pth.cgPath

}

In the code you posted, you are using extension to try and segment the code functions... that can be helpful, but it can also make things more complicated, and can make it a little difficult to follow the flow - particularly when elements need to be related.
Here is a version of what you're going for... note that it is @IBDesignable with various user-available @IBInspectable properties, so you can see it in IB / Storyboard (if desired):
@IBDesignable
class BevelButton: UIButton {

    @IBInspectable
    var outerColor: UIColor = UIColor(white: 0.75, alpha: 1.0) {
        didSet {
            outerLayer.fillColor = outerColor.cgColor
        }
    }
    @IBInspectable
    var ringColor: UIColor = .black {
        didSet {
            ringLayer.fillColor = ringColor.cgColor
        }
    }
    @IBInspectable
    var startColor: UIColor = UIColor(white: 0.9, alpha: 1.0) {
        didSet {
            bevelGradLayer.colors = [startColor.cgColor, endColor.cgColor]
            innerGradLayer.colors = [endColor.cgColor, startColor.cgColor]
        }
    }
    @IBInspectable
    var endColor: UIColor = UIColor(white: 0.75, alpha: 1.0) {
        didSet {
            bevelGradLayer.colors = [startColor.cgColor, endColor.cgColor]
            innerGradLayer.colors = [endColor.cgColor, startColor.cgColor]
        }
    }

    @IBInspectable
    var outerWidth: CGFloat = 6

    @IBInspectable
    var ringWidth: CGFloat = 2

    @IBInspectable
    var bevelWidth: CGFloat = 6

    private let outerLayer = CAShapeLayer()
    private let ringLayer = CAShapeLayer()
    private let innerLayerMask = CAShapeLayer()
    private let innerGradLayer = CAGradientLayer()
    private let bevelLayerMask = CAShapeLayer()
    private let bevelGradLayer = CAGradientLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    private func commonInit() -> Void {

        layer.addSublayer(outerLayer)
        layer.addSublayer(ringLayer)
        layer.addSublayer(bevelGradLayer)
        layer.addSublayer(innerGradLayer)

        bevelGradLayer.mask = bevelLayerMask
        innerGradLayer.mask = innerLayerMask

        bevelLayerMask.fillColor = UIColor.black.cgColor
        innerLayerMask.fillColor = UIColor.black.cgColor

        outerLayer.fillColor = outerColor.cgColor
        ringLayer.fillColor = ringColor.cgColor

        bevelGradLayer.colors = [startColor.cgColor, endColor.cgColor]
        innerGradLayer.colors = [endColor.cgColor, startColor.cgColor]

    }

    override func layoutSubviews() {
        super.layoutSubviews()

        var pth: UIBezierPath = UIBezierPath()
        var frameRect: CGRect = .zero
        var pathRect: CGRect = .zero

        frameRect = bounds

        outerLayer.frame = frameRect
        pathRect.size = frameRect.size
        pth = UIBezierPath(ovalIn: pathRect)
        outerLayer.path = pth.cgPath

        frameRect = frameRect.insetBy(dx: outerWidth, dy: outerWidth)

        ringLayer.frame = frameRect
        pathRect.size = frameRect.size
        pth = UIBezierPath(ovalIn: pathRect)
        ringLayer.path = pth.cgPath

        frameRect = frameRect.insetBy(dx: ringWidth, dy: ringWidth)

        bevelGradLayer.frame = frameRect
        pathRect.size = frameRect.size
        pth = UIBezierPath(ovalIn: pathRect)
        bevelLayerMask.path = pth.cgPath

        frameRect = frameRect.insetBy(dx: bevelWidth, dy: bevelWidth)

        innerGradLayer.frame = frameRect
        pathRect.size = frameRect.size
        pth = UIBezierPath(ovalIn: pathRect)
        innerLayerMask.path = pth.cgPath

    }

    override var isHighlighted: Bool {
        get {
            return super.isHighlighted
        }
        set {
            if newValue {
                innerGradLayer.colors = [startColor.cgColor, endColor.cgColor]
                bevelGradLayer.colors = [endColor.cgColor, startColor.cgColor]
            } else {
                bevelGradLayer.colors = [startColor.cgColor, endColor.cgColor]
                innerGradLayer.colors = [endColor.cgColor, startColor.cgColor]
            }
            super.isHighlighted = newValue
        }
    }
}

Here's how it looks (with default properties) in Storyboard:

Here's the IBInspectable properties panel:

And, at run-time, default state:

and Highlighted state (with the gradients flipped vertically):

redpajama_set_name: RedPajamaStackExchange


text:
Q: Zxing library not displaying scanned result in fragment activity I am using zxing library in my app...below code working fine in fragment and displaying result..problem is in launching fragment activity i added below code..
on that time its not displaying scanned result..can anyone tell me
    button = (Button) view.findViewById(R.id.zing);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("com.journeyapps.barcodescanner.CaptureActivity");
            intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
           startActivityForResult(intent,0);

        }
    });

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            String contents = data.getStringExtra("SCAN_RESULT");

            // Handle successful scan
            Toast toast = Toast.makeText(getActivity(), "Content:" + contents, Toast.LENGTH_LONG);
            toast.show();

        } else if (resultCode == Activity.RESULT_CANCELED) {
            // Handle cancel
            Toast toast = Toast.makeText(getActivity(), " Cancelled", Toast.LENGTH_SHORT);
            toast.show();

        }
        }
    else
    super.onActivityResult(requestCode, resultCode, data);
}

A: try this, working for me
add this code in Main activity
  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
                for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


text:
Q: Proof of $\gcd(n!+1, (n+1)!+1)=1$? I guess the canonical proof to this problem is attained using the Euclidean Algorithm (I've seen some posts like this already). I came with this proof, based on gcd definition and some divisibility properties. I'd like to know if it seems correct to you.
Proof:
Let $d$ be a common divisor of both terms. Then $n! +1$ = $d$.$s$ and $(n+1)! +1 = d.t$, for $s, t$ in $\Bbb Z/{0}$. Therefore $(n +1)n! + 1 = n.n! + n! + 1 = n.n! + d.s = d.t$, and it follows that $d|n.n!$. Now, since $n=d(t-s)/n!$, $d|n$. Then $d$ must divide 1 ($n! + 1 = d.s$), and $|d|$ = 1. Being $d'$ another common divisor, it is clear that $d'$ must divide 1 also, and therefore it does divide $d$, so we have $d = gcd(n! + 1, (n+1)! +1) = 1$

A: You can simplify this a lot by letting $a=n!$. From there, you have $\gcd(a+1,(n+1)*a+1)$. From there, you could just find $(n+1)*a+1\equiv1\mod a+1$.

A: There is one mistake in the proof:  $n=d(t-s)/n! $ does not imply that $d|n$, because $(t-s)/n!$ may not be an integer. However, you can prove $d|n$ in this way:
$d|n!+1$ implies $ d|(n+1)(n!+1)= (n+1)!+n+1$. This and $d|(n+1)!+1$ imply $d|n$. Like you said in the question this implies $d|1$, because $d|n$ implies $d|n!$ and by hypothesis $d|n!+1$.
Once we get $d|1$ we are done, because these means there isn't any prime number dividing $n!+1$ and $(n+1)!+1$, therefore the greatest common divisor is $1$

A: Note that the result is right iff $n\neq 0$.
We have for all $n\in \mathbb{N^*}$, $(n+1)!+1\ge n!+1$.
Now we use euclidean algorithm :
$(n+1)!+1=(n+1)(n!+1)-n$ with $0<\vert- n\vert<n!+1$
Then $n!+1=(n-1)!\vert -n\vert+1$ with $0<1<\vert-n\vert$.
Then $\vert-n\vert = \vert-n\vert \times 1 +0.$
So we take the last remainder $\neq 0$. And it's $1$. So $\gcd(n!+1,(n+1)!+1)=1$


text:
Q: Is there a way to sync xmpp messages across different devices, with standard xmpp client? I currently use google with a standard xmpp client, and another xmpp account is on a server of my own. I know that if I use google hangout I can get synchronized, but can I get the same feature with my own server or google's server on a standard xmpp client?

A: Yes, there is. Have a look at XEP-0280: Message Carbons
( http://xmpp.org/extensions/xep-0280.html )
Both your client as well as your server have to support it in order to fully work.


text:
Q: lotus notes start session I'm looking for a way to start Lotus Notes and control its utilisation from a vb.net project.
By controlling I mean litle things like getting the window position, closing active document and other stuff.
But the main objective is to start a session.
I'm confused because I tried to use the Lotus Notes Automation Classes dll and nothing worked well...
If anyone had some tips for me, I would apreciate a lot!
Thanks! (by the way, sorry english is not my main language)

A: In Notes speak, a session is a backend object, not a UI object. What you describe (changing window position, closing active window, etc) is UI functionality.
Notes supports COM, and you have full access to all backend classes. But you don't have access to the UI classes.
Why would you want to automate the actual Notes client? If you describe what you are ultimately wanting to do, perhaps we can help. I am sure that the correct way to solve what you are trying to do is to use the backend classes...

A: I found a way to start Notes, I needed to use process:
 Private Sub StartNotes()
    Dim p As Process = New Process()

    p.StartInfo.FileName = "C:\Program Files\Notes\notes.exe"
    p.StartInfo.Arguments = ""

    p.Start()

  End Sub

I automate it after using backend classes from lotus and domino dll

A: Sub Send_Email_via_Lotus_Notes()
Dim Maildb As Object
Dim MailDoc As Object
Dim Body As Object
Dim Session As Object
'Start a session of Lotus Notes
    Set Session = CreateObject("Lotus.NotesSession")
'This line prompts for password of current ID noted in Notes.INI
    Call Session.Initialize
'or use below to provide password of the current ID (to avoid Password prompt)
    'Call Session.Initialize("<password>")
'Open the Mail Database of your Lotus Notes
    Set Maildb = Session.GETDATABASE("", "D:\Notes\data\Mail\eXceLiTems.nsf")
    If Not Maildb.IsOpen = True Then Call Maildb.Open
'Create the Mail Document
    Set MailDoc = Maildb.CREATEDOCUMENT
    Call MailDoc.REPLACEITEMVALUE("Form", "Memo")
'Set the Recipient of the mail
    Call MailDoc.REPLACEITEMVALUE("SendTo", "Ashish Jain")
'Set subject of the mail
    Call MailDoc.REPLACEITEMVALUE("Subject", "Subject Text")
'Create and set the Body content of the mail
    Set Body = MailDoc.CREATERICHTEXTITEM("Body")
    Call Body.APPENDTEXT("Body text here")
'Example to create an attachment (optional)
    Call Body.ADDNEWLINE(2)
    Call Body.EMBEDOBJECT(1454, "", "C:\dummy.txt", "Attachment")
'Example to save the message (optional) in Sent items
    MailDoc.SAVEMESSAGEONSEND = True
'Send the document
'Gets the mail to appear in the Sent items folder
    Call MailDoc.REPLACEITEMVALUE("PostedDate", Now())
    Call MailDoc.SEND(False)
'Clean Up the Object variables - Recover memory
    Set Maildb = Nothing
    Set MailDoc = Nothing
    Set Body = Nothing
    Set Session = Nothing
End Sub


text:
Q: When does free game time for ESO start? I'm thinking of buying Elder Scrolls Online since its currently on sale. With this purchase I'll get free in-game time, but I don't think I'll start to play it yet.
When does this free game time start to count down? Is it when I install it? When I make an ESO account? Or does it start counting down at some other point?

A: Normally, the game time would start from the moment you apply your key (either your game key, or the game time card key) to your account, or upon applying it when creating an account.
Though I can't give you an explicit answer specific to ESO, this is a structure shared by most paid MMOs, like World of Warcraft and so on.
That said, it should be safe buying the game now and not making an account until you want to start playing. To be absolutely safe, you could try checking with the publisher, if they respond in time.


text:
Q: Align text under a colon In plain text, this is what I want to do:
Explanation: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend.
             Praesent sed orci commodo, venenatis neque vel, pulvinar velit.
             Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.

update
If hspace{5cm} fit the length of the word "Explanation: " and if hspace worked in the enumerate environment, the following would be what I want my document to look like:
\documentclass[11pt]{article}

\begin{document}

\begin{enumerate}

\item 1

answer

\item 2

explanation: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend.\\ \hspace {5cm}Praesent sed orci commodo, venenatis neque vel, pulvinar velit.\\ \hspace {5cm}Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.

\item 3

answer

\end{enumerate}

\end{document}

Basically, imagine
Explanation: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend.
             Praesent sed orci commodo, venenatis neque vel, pulvinar velit.
             Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.

is in an enumerate environment.
This is what I want:

A: Revised answer based on revised question. There are many ways to skin a cat. Here are two possible ways that might provide some inspiration.
\documentclass{article}
\usepackage{hanging}
\usepackage{longtable}
\newlength{\hangwidth}
\newcommand{\newhang}[1]{\settowidth{\hangwidth}{#1}\par\hangpara{\hangwidth}{1}#1}
\newcounter{myquestion}

\begin{document}
\stepcounter{myquestion}
\newhang{\arabic{myquestion}. Question: }What is the question?
\newhang{Answer: }Lorem ipsum dolor sit amet, consectetur adipiscing elit.\\Phasellus volutpat eu orci vitae eleifend.\\Praesent sed orci commodo, venenatis neque vel, pulvinar velit.\\Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.
\stepcounter{myquestion}
\newhang{\arabic{myquestion}. Question: }What is the question?
\newhang{Answer: }Lorem ipsum dolor sit amet, consectetur adipiscing elit.\\Phasellus volutpat eu orci vitae eleifend.\\Praesent sed orci commodo, venenatis neque vel, pulvinar velit.\\Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.
\stepcounter{myquestion}
\newhang{\arabic{myquestion}. Question: }What is the question?
\newhang{Answer: }Lorem ipsum dolor sit amet, consectetur adipiscing elit.\\Phasellus volutpat eu orci vitae eleifend.\\Praesent sed orci commodo, venenatis neque vel, pulvinar velit.\\Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.

\setcounter{myquestion}{0}
\begin{longtable}{rp{0.7\textwidth}}
\stepcounter{myquestion}\arabic{myquestion}. Question: &What is the question?\\
Answer: &Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend. Praesent sed orci commodo, venenatis neque vel, pulvinar velit. Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.\\
\stepcounter{myquestion}\arabic{myquestion}. Question: &What is the question?\\
Answer: &Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend. Praesent sed orci commodo, venenatis neque vel, pulvinar velit. Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.\\
\stepcounter{myquestion}\arabic{myquestion}. Question: &What is the question?\\
Answer: &Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat eu orci vitae eleifend. Praesent sed orci commodo, venenatis neque vel, pulvinar velit. Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis nisl dapibus.\\
\stepcounter{myquestion}\arabic{myquestion}. Question: &What is the question?\\
\end{longtable}

\end{document}

A: A quick hacky way to achieve this is with phantom which produces space equivalent to how much its argument would have it wasn't phantom'd.
\begin{enumerate}
  \item Question\\
  explanation: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus.\\
  \phantom{explanation:} Praesent sed orci commodo.\\
  \phantom{explanation:} Mauris ullamcorper tellus sed quam pellentesque, vitae sagittis.
\end{enumerate}

gives me (in Beamer):


text:
Q: Ruby - Accessing class that is not in the current scope? I have 2 classes
MyController which is under app/controllers/api
MyManager which is under libs/managers
I am trying to use this manager class from my controller and I'm getting the following error.
Uninitialized constant API::MyController::MyManager
How do I reference and use MyManager class from MyController class?
Controller
class API::MyController < API::BaseController
  before_action :setup

  def something
    @myManager.doSomething
  end

  def setup
    # Exception is thrown here
    @myManager = MyManager.new
  end

end

Manager
class MyManager
   def doSomething
      puts('something')
   end
end

A: Make sure you autoloaded the lib/managers directory:
# in config/application.rb
config.autoload_paths += %W(#{config.root}/lib/managers)

If MyManager is a Class (not a module) then you can just call MyManager.new without any problem.
Also just a note.  In Rails 4 there are a couple of 'concerns' directories added under app/controllers and app/models (app/controllers/concerns and app/models/concerns).  Any files under these directories will be autoloaded.  By standards, only model related concerns (be it modules or classes) will be placed under app/models/concerns (same applies for controller related concerns).

A: This has to do with the way rails loads modules, take a look at this
I think what you want is to make sure your autoloading the lib directory and then call ::MyManager.method since its trying to get the module from the Controller context.
::Module indicates the absolute module.


text:
Q: Is this normal? I don't get how this late static binding works.
abstract class A{

  final public static function doprint(){
    print get_called_class() . '<br>';
  }

  public static function wrapper(){
    self::doprint();
    static::doprint();
  }

}

class A2 extends A{}

A2::wrapper();

get_called_class() prints A2 in both cases, even when I called the doprint method with self. why?

A: I think get_called_class() is telling you which class was called, and its output is correct.
Late static binding allows the self context to bubble up, so methods defined higher can operate on the called method's object.

A: get_called_class() always returns the class you actually call. You call A2:: so it's A2.
On my site there's a tutorial with an LSB singleton abstract class. I'm not linking here because there's always a zombie vigilante that comes and removes the links without even looking. But it's in my description.
The catch with LSB is that a method in A can call a method in B which can call a method in A back. See this example:
header('Content-Type: text/plain'); // Pretty text output
// LSB Parent
class A {
    // NOLSB: Will call Current Class method
    static public function TriggerSelf() {
        self::OverrideMe();
    }
    // LSB: Will call Inheriting Class method (or Current if none Inherits)
    static public function TriggerStatic() {
        static::OverrideMe();
    }
    // Method to Override
    static public function OverrideMe() {
        echo 'A here', PHP_EOL;
    }
}

// LSB Child
class B extends A {
    // Override by LSB
    static public function OverrideMe() {
        echo 'B here', PHP_EOL;
    }
}

A::TriggerSelf(); // <- NO LSB
A::TriggerStatic(); // <- LSB (but not inheritance)

B::TriggerSelf(); // <- NO LSB
B::TriggerStatic(); // <- LSB (with inheritance, so it works)

See how B::TriggerStatic() allows A to call a B method while B::TriggerSelf() calls a A method. That's LSB. Parent class static methods can call child class static methods. It's pretty much static abstracts :)
Study the example, it'll make sense.


text:
Q: Finding symmetric difference with LINQ I have two collections a and b. I would like to compute the set of items in either a or b, but not in both (a logical exclusive or). With LINQ, I can come up with this:
IEnumerable<T> Delta<T>(IEnumerable<T> a, IEnumerable<T> b)
{
    return a.Except (b).Union (b.Except (a));
}

I wonder if there are other more efficient or more compact ways of producing the difference between the two collections.
Edit 1: Jon Skeet posted a first solution which does not preserve the order of the items by relying on a HashSet. I wonder if there are other approaches which would preserve the order of a and b in the output.

A: Given a.Except(b) and b.Except(a) are disjoint, you can use concat instead of union, saving a set operator (and concat is more efficient).
return a.Except (b).Concat (b.Except (a));

This still runs through each list twice.

A: Use HashSet<T> directly - it has a SymmetricExceptWith method:
HashSet<T> data = new HashSet<T>(a);
data.SymmetricExceptWith(b);

EDIT: If you want to maintain the order, here's an alternative:
HashSet<T> data = new HashSet<T>(a);
data.IntersectWith(b);
foreach (T t in a.Concat(b))
{
    if (!data.Contains(t))
    {
        yield return t;
    }
}

This has the following important differences:

*

*Both a and b are iterated over twice. In some cases that could be a very bad thing - you could call ToList on each of them to start with to retain a buffer.

*If there are duplicates in either a or b, they will be yielded multiple times. If you wanted to avoid this you could keep a set of already-yielded values. At this point, it would be equivalent to:
a.Concat(b).Except(a.Intersect(b))

That's still only two set operations instead of the three in your original code though.

A: We had a similar need for a project in my company, so we wrote this extension:
public class EnumerablePair<T> : IReadOnlyCollection<T>
{
    private IReadOnlyCollection<T> _Left;
    private IReadOnlyCollection<T> _Right;
    private IEnumerable<T> _Union;
    private int _Count;
    public EnumerablePair(IEnumerable<T> left, IEnumerable<T> right)
    {
        _Left = left?.ToList() ?? Enumerable.Empty<T>().ToList();
        _Right = right?.ToList() ?? Enumerable.Empty<T>().ToList();
        _Count = Left.Count + Right.Count;
        _Union = Left.Union(Right);
    }

    public int Count => _Count;
    public IReadOnlyCollection<T> Left { get => _Left; }
    public IReadOnlyCollection<T> Right { get => _Right; }

    public IEnumerator<T> GetEnumerator()
    {
        return _Union.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _Union.GetEnumerator();
    }
}

public static class EnumerableExtension
{
    public static EnumerablePair<T> ExclusiveDisjunction<T>(this IEnumerable<T> leftOperand, IEnumerable<T> rightOperand, IEqualityComparer<T> comparer = null)
    {
        if (leftOperand == null)
            throw new ArgumentNullException(nameof(leftOperand), $"{nameof(leftOperand)} is null.");
        if (rightOperand == null)
            throw new ArgumentNullException(nameof(rightOperand), $"{nameof(rightOperand)} is null.");

        // TODO : Can be optimized if one of the IEnumerable parameters is empty.

        bool leftIsBigger = leftOperand.Count() > rightOperand.Count();
        var biggestOperand = leftIsBigger ? leftOperand.ToList() : rightOperand.ToList();
        var smallestOperand = leftIsBigger ? rightOperand.ToList() : leftOperand.ToList();

        var except1 = biggestOperand.ToList();
        var except2 = Enumerable.Empty<T>().ToList();

        Func<T, T, bool> areEquals;
        if (comparer != null)
            areEquals = (one, theOther) => comparer.Equals(one, theOther);
        else
            areEquals = (one, theOther) => one?.Equals(theOther) ?? theOther == null;

        foreach (T t in smallestOperand)
            if (except1.RemoveAll(item => areEquals(item, t)) == 0)
                except2.Add(t);

        if (leftIsBigger)
            return new EnumerablePair<T>(except1, except2);
        return new EnumerablePair<T>(except2, except1);
    }
}

It compares elements of two collections (using an IEqualityComparer or not, at your choice).

*

*The returned object, an EnumerablePair<T>, contains objects that are in leftOperand or rightOperand, but not both (XOR).

*EnumerablePair<T>.Left contains objects that are in leftOperand but not in rightOperand.

*EnumerablePair<T>.Right contains objects that are in rightOperand but not in leftOperand.

You can use the extension like this :
var xorList = list1.ExclusiveDisjunction(list2);
var leftXor = xorList.Left;
var rightXor = xorList.Right;

xorList, leftXor and rightXor are IEnumerable<T>.


text:
Q: Different way to mix jQuery and Angular4 I recently started learning Angular 4 in hopes to pick it up on a few projects (I am still learning a lot of the basics, so my question may seem obvious). In the past I have been using jQuery for most of my DOM manipulation, however now with using Angular, there are very obvious changes which make using jQuery within an Angular application a little more troublesome.
I have read over many Stack Overflow posts regarding using jQuery within an Angular project, however all of them suggest to write your jQuery functions from within the component typescript files. This makes sense since Angular is supposed to be based on components. My only question/concern is how about would you create global level jQuery functions outside of the component themselves.
For example, in the past I have always just created a js file to hold my jQuery functions and have them referenced within my html file. An example of this would be a parallax function for images. If I wanted to add a little different styling to different parallax images I could do this fine and still have my jQuery do its job, but now say for example I have two different parallax components that use the same jQuery code, is there a (right) way to reference the same function from within different components via a global js file that holds the jQuery code?
My assumption would be I could just create a file "xxxx.js" that holds the functions and have it referenced in the index.html file. I just want to know if something like what I have described is possible, and if so what is the best approach.

A: I would possibly be using dependency injection ,
 The approach would be :

*

*Create a services file which holds all the common functionality
across the functions.

*Use them as providers in my target components.

*Using Dependancy injection create object for such services and use them in my component.

As far as approach with " Create a js and include in index.html and use across component" ,
yes it is possible .
 I have used it for 1 of the external library in my project which was a js file. Steps should be :

*

*Copy the js file in src/assets/javascript

*Add them in index.html
<script src="assets/javascript/yourFile.js"></script>

*declare your js function as shown in component section ( before component directive) as shown :
declare var yourFunction: any;

*Now you can use your function in the target component.

A: When you use a framework as the angular, it starts to manipulate the elements and their events. Jquery does not work as you are accustomed because if you enter the scripts only once at the end of the page, the events will be applied to the current elements, but after the angular make any modification, the events will no longer be working.
Jquery is not recommended in conjunction with angular, however, if you want to take advantage of some features you have not yet found in a particular angled plugin, you can create an angular component that makes that binding, so you'll have to make the jquery call by applying to Elements you want, and obviously the ideal is you also take care of performing the unbind for some types of event.
Here's an example: Example


text:
Q: ar.js FBX model doesn't show up I've started learning to create AR scenes with AR.js and I'm having trouble with loading custom 3D FBX. I've tried many examples and all of them work perfectly, but none with fbx models. Im using a model from mixamo.
<!DOCTYPE html>

        >

Do I need some other library?
CODE IMAGE


text:
Q: Where (under what name) can I find these breakable female pin headers? I'm looking for these pin headers:

They're easier to work with than the regular pin headers because of the grooves.
There are similar headers that are also breakable but with round sockets (I'm not looking for these).
So I'm looking for a name or a search term so that I can find these on typical stores (e.g. aliexpress).

A: I know it's been a long time since you asked this, but I was looking for the same thing and found those BL 1 36 Z, which are available in many electronics hardware stores. There are different lengths and are available in gold plated version too. No luck on aliexpress for this one.

A: Single row PCB socket header, breakable, through-hole, straight, on Digikey. More than 100 options.
They don't have a machined pin (round), just like you asked.


text:
Q: Restrict computation time of optimization algorithms in python When using optimization algorithms in Python such as scipy.optimize.minimize() from the Scipy library, one can specify the maximum number of iterations via the optional argument "maxiter". However, I would rather like to restrict the total computation time of this algorithm, since I would like to use it in a time-critical application. The number of iterations is secondary.
Is there a way to restrict the maximum computation time in the Scipy optimization functions? If this means that the result is less accurate, that's fine.


text:
Q: Is "Down to the word" a popular phrase as an idiom? I found the phrase, "the message is the same every time, almost down to the word" in the article titled "As debates loom, Romney grasps for a closing argument" appearing in October 1st Time magazine.
The article reports that everywhere he goes lately, President Obama begins his stump speech with a story about a four-year-old boy named Samm. When Samm's parents asked their son if he recognized the leader of the free world, he did. "What does Barack Obama do?" they asked Sammy, and Sammy replies: "He approves this message." Then the writer follows:

"It's a funny little ice-breaker. But it's also a bridge to the
  message itself, which is that Obama wants to emphasize the middle
  class as the foundation of a strong economy, whereas Romney's top-down
  economics benefits the rich. The message is the same every time,
  almost down to the word."

From the context, I guessed "almost down to the word" is synonymous with "almost verbatim."
But I don't find "down to the word" in any of Cambridge, Oxford and Merriam-Webster dictionary as an idiom, though they register "down to earth," "down to the wire," "down to the present day,"and "down to there."
On the other hand, Google Ngram registers "down to the word." It shows usage of this phrase existed ever since before 1840, but its currency has been declining sharply after peaking during 1860 to 1920.
Is my understanding of "down to the word" as synonymous with "verbatim" right?
Is "down to the word" an idiom, or a simple set of words. Is it still a popular phrase , or pretty old-fashioned expression because I can't find it in any dictionaries I've checked?

A: "Down to the word" and other constructions like it (usually you hear "down to the letter") simply refers to the sameness of one thing with respect to another. What it asks you to do is to consider the detail mentioned, not whatever standard of sameness you may normally be tempted to apply.
Consider two identical twin girls: you could say both are human beings. You could also say they are both female, both are the same height, the same weight, the same age (give or take a few minutes), the same race, etc. But instead of these coarse comparisons, you could emphasize how alike they are by saying

They are alike down to their facial features.

The idea of "down" in this sense calls to mind going from broad comparatives down to finer and finer ones — ultimately to whatever level of granularity is specified. If one oral presentation, such as a speech, is like another "down to the word" it is identical at that level. If it is a written document (one student's homework is identical to another's, say) it could be said to be the same down to the letter, or down to the line breaks, or whatever metric you wish to apply.
Imagine viewing something from the top of a building. You would have to go down closer to view the details. That is the sense of it: zooming in to consider minute details.


text:
Q: Repeating error code from jQuery The below code works correctly but when I click the submit on my user login form with an incorrect user name and password I get this error:

Incorrect Informatiın

Then I click submit again with incorrect values and this error message repeats over and over. Because of this my div strangely expands. How can I fix this?

$("#giris").submit(function (event) {
    var kullanici_adi = $("#kullanici_ad").val();
    var sifre = $("#sifre").val();
    $.ajax({
        type: "POST",
        url: "girisislemi.php",
        data: {
            kullanici_adi: kullanici_adi,
            sifre: sifre
        },
        dataType: "json",
        success: function (data) {
            if (data.tip === 'yonetici') {
                window.location.href = "yonetici.php";
            }
            if (data.tip === 'kullanici') {
                window.location.href = "kullanici.php";
            }
            if (data.tip === 'error') {
                $('input[type=text]').css("border", "3px solid red");
                $('input[type=password]').css("border", "3px solid red");
                $('#giris').after("
Incorrect Information
");
                $('font').css("color", "red");
            }

        }

    });
    event.preventDefault();
});

A: The issue is due to your use of after() which will always add new content each time it's run. Instead, you could check to see if the error has already been shown:
if (data.tip === 'error') {
    $('input[type=text], input[type=password]').addClass('login-error');
    if (!$('p.login-error').length)
        $('#giris').after('
Incorrect Information
');
}

Also note that the  element is very outdated, and shouldn't be used any more, and you should set your styling rules in classes in a stylesheet and using add/removeClass instead of setting inline css().
input.login-error {
    border: 3px solid red;
}
p.login-error {
    color: red;
}


text:
Q: Are sqlite3 commands within a sqlite transaction safe? If I have multiple threads that can run queries on a database, will a sqlite3_step ever return sqlite busy if the step is within a transaction?

A: It is possible that sqlite3_step needs to acquire the write lock on the database, and that this is not possible because of some other thread's read lock that is not released.
To prevent this deadlock, transactions that intend to write to the database should be started with BEGIN IMMEDIATE instead of BEGIN.


text:
Q: Ring homomorphism is injective if and only if the induced maps on localizations are injective Suppose $\phi:A\to B$ is a ring homomorphism, where $A,B$ are commutative. Then for every $p\in A$, there is an induced map $\phi_p: A_p\to B_{\phi(p)}$ on the localization defined by $\phi_p(x/q) = \phi(x)/\phi(q)$.

I would like to show that $\phi$ is injective if and only if $\phi_p$ is injective for every $p\in A$, but I have some problems.

Suppose $\phi$ is injective. If $\phi_p(x/q) = 0$, then $\phi(x)/\phi(q) = 0$. Thus there exists an $r\in \{\phi(p)^n | n \in \mathbb N\}$ such that $r\phi(x) =0$. If I could show that this implies that there exists an $s\in \{p^n | n\in \mathbb N\}$ such that $sx =0$, then this would show that $\phi_p$ is injective.
Edit: I got confused between localization at a prime and what I really wanted. Now it is easy to solve the problem.
Any help would be appreciated! Thanks!

A: First suppose $\phi$ is injective, and suppose that
$$\frac{\phi(x)}{\phi(q)}=\frac{\phi(x)}{\phi(p^n)}=\frac{\phi(x)}{\phi(p)^n}=0\in B_{\phi(p)}$$
This means there is some $m\in\mathbb{N}$ such that $\phi(p)^m\phi(x)=0$ in $B$.  By injectivity it follows that $p^mx=0$ in $A$ so that
$$\frac{x}{q}=\frac{x}{p^n}=0\in A_p$$
Hence, $\phi_p$ is injective for all $p\in A$.
The reverse direction follows from considering the case $p=1\in A$.


text:
Q: How to use Rotate Animation with Translate animation? I am using gesture listener in my sample app, and in it;s onFling() method I want to perform both Rotate and Translate Animation.
individual both work fine, but when I Integrate it in Animation Set , it's not work in proper .
Please suggest me how can I Handle  this.
Following is code of my onFling method :
onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
    translateAnimation =  new TranslateAnimation(0,x2,0,y2); // x2=e2.getX() and y2=e2.getY()

    translateAnimation.setDuration(3000);

    rotateAnimation = new RotateAnimation(0, 90, RotateAnimation.RELATIVE_TO_SELF, RotateAnimation.RELATIVE_TO_SELF);

    rotateAnimation.setStartOffset(1400);

    rotateAnimation.setInterpolator(new AccelerateInterpolator());

    animationSet.addAnimation(translateAnimation);

    animationSet.addAnimation(rotateAnimation);

    animationSet.setAnimationListener(this);

    animationSet.setDuration(3000);

    lastView.startAnimation(animationSet);

}
Thanking you lot

A:
Try this

 @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.rotate);
    AnimationSet snowMov1 = new AnimationSet(true);
    RotateAnimation rotate1 = new RotateAnimation(0, 360,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
    rotate1.setStartOffset(50);
    rotate1.setDuration(300);
    rotate1.setRepeatCount(-1);
    snowMov1.addAnimation(rotate1);
    TranslateAnimation trans1 = new TranslateAnimation(
            Animation.RELATIVE_TO_PARENT, 0.1f,
            Animation.RELATIVE_TO_PARENT, 0.3f,
            Animation.RELATIVE_TO_PARENT, 0.0f,
            Animation.RELATIVE_TO_PARENT, 0.9f);
    trans1.setDuration(300);
    trans1.setRepeatCount(-1);

    snowMov1.addAnimation(trans1);
    ImageView view = (ImageView) findViewById(R.id.image);
    view.startAnimation(snowMov1);

}


text:
Q: How this middle number helps to count sum of series. I am reading a book and there are some exercise and methods shown in book. But they didn't describe how they work. Ok so if i have to sum of a series like
$1,2,3,4,5,...  $
then according to that book we can take the middle number and multiply by total terms so , middle number $= 3$ and total terms $5$ so $5\times3=15$. they do same with finding the sum of a $3\times3$ square numbers. Now i am not getting how this method works? How middle number plays an important role here? What's the logic behind it?

A: Take the story of little Carl Friedrich Gauss and how his mathematics teacher thought he could get a lesson off by telling all hist students to add the numbers from $1$ to $100$.
Gauss noted that if you don't do it in order, but rather add the first to the last, the second to the second-to-last, and so on, you get something which is much easier to work with: you get a bunch of $101$'s. How many of them? Exactly half as many as the length of the list he started out with: $\frac{100}2$. Thus the sum of all these $101$'s, and therefore the sum of all the numbers from $1$ to $100$ is
$$
101\cdot \frac{100}{2}
$$
If we want to apply this to your question, take the $\frac{}2$ and move to be below $101$ instead, so that we get
$$
\frac{101}{2}\cdot 100
$$
We can see that the first term here is the middle of the list, $50.5$ (when there are an even number of elements in the list, the middle itself is not in the list), while the last term is the number of elements in the list.
This trick works whenever all the pairs of elements in the list (first and last, second and second-to-last, and so on) add up to the same number. This specifically happens when the difference between any two consecutive numbers on the list is the same all along the list (although there are other cases where it works as well, those aren't as common).

A:
The key-word is symmetry. When looking at $$1,2,3,4,5$$ consider
  \begin{align*}
1+2+\color{blue}{3}+4+5 &= (3-2)+(3-1)+\color{blue}{3}+(3+1)+(3+2)\\
&=3+3+\color{blue}{3}+3+3\\
&=5\cdot \color{blue}{3}\\
&=15
\end{align*}

A: The middle number of a series of consecutive numbers is their average.
And of course the average multiplied by their count equals their sum.


text:
Q: Should I use React hooks when starting new project? The title should give you the general idea. I (my company) want to start a new project, which is a reboot for our current website writing in Angular v1, with React.
I want to know if this is a good time to use React Hooks in production and what risks that I'll take if it is.
PS: There'll be no right answer, I just want to get some opinions to consider before implementing. Thanks in advance.

A: As of now, hooks have some problems with testability and debugging. The state of a hook can't be tracked with a debugger on component instance as it's done with class components, this is possible only with React dev tools. Enzyme doesn't fully support hooks yet. Hooks may be harder to mock or spy than component lifecycle methods because this can't be done on component instance.
Hooks have several inherent problems that sometimes need to be addressed in counterintuitive and overly complicated ways.
There are well-known problems with useEffect and useLayoutEffect function scopes that don't work well with setTimeout, events and other kinds of callback-based APIs (workarounds are described in this answer).
That there's no counterpart to shouldComponentUpdate may result in component nesting to prevent unnecessary updates. This especially applies to useContext. If there's a need to prevent updates, this isn't much better than context Consumer and requires to use nested component:
const WrapperWithConsumer = () => {
  return <FooContext.Consumer>
    {({ foo }) => <PureWrappedComponent foo={foo}/>}
  </FooContext.Consumer>;
}

const WrapperWithHook = () => {
  const { foo } = useContext(FooContext);
  return <PureWrappedComponent foo={foo}/>
}

As any other recent API, hooks restrict a project to be used with up-to-date React version, prevent its components from being reused in older projects and take away the opportunity to switch to alternative implementations - Preact, Inferno, etc.

A: You can always try, but i wouldn't recommend it as that technology is still in an early stage, try a class component first and then evaluate to use hooks.
also maybe this article helps you:
https://blog.logrocket.com/react-hooks-lets-not-get-too-attached-11b0ac09b4b5


text:
Q: Export selected node and edge in cytoscape.js is there a way that I can export selected node and edge from graph and display the selected ones in another graph. maxkfranz said that we can export as json. Do you have any idea how I can do that? Thanks。

A: Have you tried something along the lines of:
cy.$(':selected').json()
Edit : The API now also allows for multiple elements, e.g. cy.$(':selected').jsons()


text:
Q: Can GNU as process struct and function prototypes in assembly file(.s)? As we know, assembly files(.S) would get preprocessing before assembling, but I found that after preprocessing there may be struct/function prototypes in the resulting assembly files, How would the gnu as deal with these prototypes? Just ignored it?
For example, the following command:

gcc -E -o tmp.result arch/x86/boot/copy.S -Iinclude/ -Iarch/x86/include/

and the resulting assembly file (tmp.result) is:
# 1 "arch/x86/boot/copy.S"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "arch/x86/boot/copy.S"
# 11 "arch/x86/boot/copy.S"
# 1 "include/linux/linkage.h" 1
# 1 "include/linux/compiler.h" 1
# 5 "include/linux/linkage.h" 2
# 1 "include/linux/stringify.h" 1
# 6 "include/linux/linkage.h" 2
# 1 "include/linux/export.h" 1
# 26 "include/linux/export.h"
struct kernel_symbol
{
 unsigned long value;
 const char *name;
};
# 7 "include/linux/linkage.h" 2
# 1 "arch/x86/include/asm/linkage.h" 1
# 8 "include/linux/linkage.h" 2
# 12 "arch/x86/boot/copy.S" 2
.code16
.text
GLOBAL(memcpy)
 pushw %si
 pushw %di
 movw %ax, %di
 movw %dx, %si
 pushw %cx
 shrw $2, %cx
 rep; movsl
 popw %cx
 andw $3, %cx
 rep; movsb
 popw %di
 popw %si
 retl
ENDPROC(memcpy)

but when trying to assemble this file:

as -o tmp.o tmp.result

produce following error:
include/linux/export.h: Assembler messages:
include/linux/export.h:26: Error: no such instruction: `struct kernel_symbol'
include/linux/export.h:27: Error: junk at end of line, first unrecognized character is `{'
include/linux/export.h:28: Error: no such instruction: `unsigned long value'
include/linux/export.h:29: Error: no such instruction: `const char *name'
include/linux/export.h:30: Error: junk at end of line, first unrecognized character is `}'
arch/x86/boot/copy.S:20: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:34: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:36: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:49: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:51: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:58: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:60: Error: invalid character '(' in mnemonic
arch/x86/boot/copy.S:67: Error: invalid character '(' in mnemonic

It seems that the assembler can not deal with the struct in tmp.result. How can Linux source code(.S) get through the assembling?

A: as cannot process struct and function prototypes - they are just for the C compiler, and get "pulled in" in your preprocessing by mistake. In facts, if you look at the header that provides that struct definition, you'll see:
#ifndef __ASSEMBLY__
struct kernel_symbol
{
        unsigned long value;
        const char *name;
};

So, the header above is thought to be included both from assembly and from C, but you didn't define __ASSEMBLY__ to tell it that you are including it into an assembly file.
Interestingly, gcc does have a builtin __ASSEMBLER__ predefined macro to discriminate between an inclusion in an assembly file or a C file, but it seems that the kernel does not use it for historical reasons, relying instead on defining manually __ASSEMBLY__ when preprocessing assembly files.
Long story short: to get the correct output from the preprocessor, you should be doing something like
gcc -E -D__ASSEMBLY__ -o tmp.result arch/x86/boot/copy.S -Iinclude/ -Iarch/x86/include/

(disclaimer: I'm not entirely familiar with the kernel build process, the line above may have other problems with include paths, or maybe the correct way would be to invoke cpp instead of gcc or whatever - I don't know)


text:
Q: Memcached running but ec2 security group settings need to be checked Hi I'm running memcached on my webserver on an AWS ec2 instance. So it has a public IP address and a private IP address.
I followed the following page to install memcached:
https://www.thefanclub.co.za/how-to/how-install-memcached-on-ubuntu-for-drupal
One step is to "Open firewall port 11211"
My question is what rule should I add to the ec2 security group? I want to know the source ip setting.
Right now in the ec2 security group, Inbound rules, I've added allow 11211 port tcp from source private ip address of the ec2 instance. Is that correct for memcached to work for anonymous users from the internet visiting my website? Thanks!

A:
what rule should I add to the ec2 security group?

No rule at all.
If you are running memcached on the same machine your web server, then you do not need any security group settings for memcached.  If the connection never leaves the machine, the security group settings have no impact on it.


text:
Q: Import Warning: Not Importing Directory issues using wxPython, don't know how to fix I keep getting this warning every time I use wxPython:
Warning (from warnings module):
  File "/usr/local/lib/wxPython-unicode-2.8.12.1/lib/python2.7/site-packages/wx-2.8-mac-unicode/wx/_core.py", line 14581
    import locale
ImportWarning: Not importing directory '/usr/local/lib/wxPython-unicode-2.8.12.1/lib/python2.7/site-packages/wx-2.8-mac-unicode/wx/locale': missing __init__.py

How do I fix this? I'm using wxPython on Mac.

A: It is just a warning; there is no need to fix anything here. You could suppress the warning, perhaps. But it is up to the wxPython project to properly silence that warning.
To suppress the warning, you can use the warnings module:
import warnings
warnings.filterwarnings('ignore', message='Not importing directory .*', module='wx.*')


text:
Q: Problemas em uma crud class Estou tentando construir uma classe para ser utilizada com mysql a principio tenho so dois arquivos então vou colar o codigo que ja fiz aqui e explicar minha duvida.
classes/connect.php

<?php

/**
 * Created by PhpStorm.
 * User: evtns
 * Date: 08/06/2016
 * Time: 17:55
 */
class Database
{
    private $db_ip = '127.0.0.1';
    private $db_user = 'root';
    private $db_pass = 'aaxd31mubr';
    private $db_select = 'sistema';

    public function connet(){
        $dbc = mysqli_connect($this->db_ip,$this->db_user,$this->db_pass) or die("falha ao conectar");

        if(mysqli_select_db($dbc, $this->db_select ))
        {
            echo 'DB selecionado com sucesso
';
            return $dbc;
        }
        else{
            echo 'falhou';
            return false;
        }
    }

    public function __construct()
    {

    }

    public function select($cols='*',$tables ,$where=null, $value=null, $order=null)
    {
        $query = "SELECT $cols ";
        $query .="FROM $tables ";

        if(isset($where) and isset($value))
        {
            $query .="WHERE $where='$value'";
            echo 'teste 1 ok';
        }

        if(isset($order))
        {
            $query .="ORDER BY $order";
        }

        if($result_query = mysqli_query($this->connet(), $query)){
            return $result_query;

        }
        echo 'Falha ao executar querry da função select.';
    return false;
    }
}

index.php

<?php
/**
 * Created by PhpStorm.
 * User: evtns
 * Date: 08/06/2016
 * Time: 18:33
 */

include_once 'classes/connect.php';

$db = new Database();
//$cols='*',$tables,$where, $state//

$row = mysqli_fetch_array($db->select('*', 'estado'));

print_r(array_count_values($row));

?>

Meu problema está aqui fiz uma instância da classe, mas ao tentar acessar os elementos do result_query da public function select, com mysqli_fetch_array(), ele so me retorna o primeiro elemento do banco, agora se tentar direto na função ele me retorna todos os valores cadastrados no banco.
alguém sabe como resolver este problema?

A: O problema está em usar a função array_count_values
O sistema acaba parando devido existir campos que não sejam STRING ou INTEGER.
Substitua o final do index.php pelo seguinte código:
$db = new Database();
//$cols='*',$tables,$where, $state//

$row = mysqli_fetch_array($db->select('*', 'estado'));

echo "
" . var_dump(($row));

A: Consegui resolver o problema, apenas criei uma variavel para receber o valor da função e utilizei da variavel para manipular os dados!
segue exemplo do codigo!
<?php
/**
 * Created by PhpStorm.
 * User: evtns
 * Date: 08/06/2016
 * Time: 18:33
 */

include_once 'classes/connect.php';

error_reporting(E_ALL);
$db = new Database();
//$cols='*',$tables,$where, $state//
$result = $db->select('*', 'tbl_clientes');

while($row = mysqli_fetch_array($result)){
    echo $row['id'] .' ID '. $row['nome'].'
';
}
?>


text:
Q: How to open a new tab with SCRIPT SRC I'm trying to add a payment button to my web page (wix). When clicked, it opens in the same iframe like a widget, but I would like it to open in a new tab when clicked. target="_blank" does not work.
Example code:

A: With Bootstrap you can use an anchor like a button.

OR use style to customize link as to appear like a button.

And use target="_blank" to open the link in a new tab.

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

        open google in new tab

A: If you want to open a link in a new tab from velo, I made a video workaround below:
https://joelgrayson.com/open-in-new-tab-wix-code
https://youtu.be/7yp-kLGu1Yw

Essentially, you cannot use  in velo, but you can do it in an HTML frame. In the workaround, I messaged the HTML frame from velo. Upon receiving the message, the HTML frame opened using <a href='' target='_blank'.


text:
Q: Rails rest-client put getting 400 bad request In a Rails app, I need to read a seed number from another application and then update the seed by 1 using a REST interface.  I'm using the gem 'rest-client'.
I can read the seed number OK using this:
      <% xml_data = RestClient.get "http://www.xxxxx.com/maxrest/rest/os/mxautokey?_lid=mxintadm&_lpwd=mxintadm&autokeyname=WORKORDERNUM&ORGID=AAAA" %>
      <% doc = Nokogiri::XML(xml_data)%>
      <% prefix = doc.at("PREFIX").text %>
      <% seed = doc.at("SEED").text %>
      <% wonum = prefix + seed %>

But, I'm trying to put back a new seed using this (at first I'm just trying to use a hard coded number):
<% RestClient.put "http://www.xxxxx.com/maxrest/rest/os/mxautokey?_lid=mxintadm&_lpwd=mxintadm&autokeyname=WORKORDERNUM&ORGID=AAAA", {:seed => 38980} %>

I get back - 400 Bad Request
I appreciate the help!


text:
Q: How to overwrite values in a dataframe with NaN if it's NaN in another dataframe (Same size) If I have two dataframes with the same size in python, let's say df1 and df2. How can I overwrite values in df2 (with NaN) if they are NaN in df1.
Is this correct:
df2[df1.isnull()] = np.NaN

A: You can try this code:
imagin that you have two dataframes: df1 and df2
import pandas as pd
import numpy as np
df1 = pd.DataFrame([['a', 1], ['b', 2], ['c', np.NaN]],columns=['name','id'])
df2 = pd.DataFrame([['c', 1], ['d', 2], ['e', 3]],columns=['name','id'])

In order to overwrite values in df2 (with NaN) if they are NaN in df1:
df2.loc[df1.id.isna(), 'id'] = np.NaN


text:
Q: Location services not working for unity in vivo y50 I'm new to Unity and AR app development, i am trying to create a small app to constantly get current location of the device, but the location is never getting updated no matter how much i try
This is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GPS1 : MonoBehaviour
{
    public static GPS1 Instance { set; get; }
    public double lat,lon;
    private void Start()
    {
        Instance=this;
        DontDestroyOnLoad(gameObject);
        StartCoroutine(StartLocationService());
    }
    private IEnumerator StartLocationService()
    {
        if(!Input.location.isEnabledByUser)
        {
            Debug.Log("User has not enabled the GPS");
            yield break;
        }
        Input.location.Start();
        Input.compass.enabled=true;
        int maxWait=20;
        while(Input.location.status==LocationServiceStatus.Initializing && maxWait > 0)
        {
            yield return new WaitForSeconds(1);
            maxWait--;
        }
        if (maxWait<=0)
        {
            Debug.Log("Timed Out");
            yield break;
        }
        if(Input.location.status==LocationServiceStatus.Failed)
        {
            Debug.Log("Unable to determine");
            yield break;
        }
        lat=Input.location.lastData.latitude;
        lon=Input.location.lastData.longitude;
        yield break;

    }
}

[on play][1]
[1]: https://i.stack.imgur.com/KPqSf.png
Please help me with this if possible i tried everything and it isn't working yet.


text:
Q: Python / PyGame: Get window size I've got a program / game with a resizable window. But how do I refresh my xSize and ySize variables, when my window gets resized? I need that in order to resize my surface etc.
If you don't get the sense of my question, feel free to ask.

A: I just found the answer myself:
if event.type == VIDEORESIZE:
            xSize = event.dict['size'][0]
            xSize = event.dict['size'][1]
            screen = pygame.display.set_mode((xSize, ySize), HWSURFACE|DOUBLEBUF|RESIZABLE)

But somehow the variables are right, but the drawings on my window don't change in size. (They are told to fit at the variables, and they're updated all the time..)

A: I think it should be like this:
if event.type == VIDEORESIZE:
    xSize = event.dict['size'][0]
    ySize = event.dict['size'][1]
    screen = pygame.display.set_mode((xSize, ySize), HWSURFACE|DOUBLEBUF|RESIZABLE

The second one should be ySize not xSize


text:
Q: Plotting a second axis with percentage on a histogram plotly chart I have plotted a histogram using plotly and the following code;
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np

from plotly.offline import init_notebook_mode
plotly.offline.init_notebook_mode(connected=True)

x0 = np.random.randn(500)
x1 = np.random.randn(500)+1

trace1 = go.Histogram(
    x=x0
)
trace2 = go.Histogram(
    x=x1
)

data = [trace1, trace2]
layout = go.Layout(barmode='stack')
fig = go.Figure(data=data, layout=layout)

plotly.offline.plot(fig)

What I would like to add is the percentage of the total on the right hand side of the chart as a second axis.

A: I don't know if there's any other way but I can think of adding a phantom trace as a workaround:
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np

from plotly.offline import init_notebook_mode
plotly.offline.init_notebook_mode(connected=True)

x0 = np.random.randn(500)
x1 = np.random.randn(500)+1

trace1 = go.Histogram(
    x=x0
)
trace2 = go.Histogram(
    x=x1
)
phantom_trace = go.Histogram(
    x=np.hstack([x1, x0]),
    histnorm='percent',
    yaxis='y2',
    showlegend=False,
    hoverinfo='skip',
    marker=go.histogram.Marker(color='rgba(0,0,0,0)')
)

data = [trace1, trace2, phantom_trace]
layout = go.Layout(
    barmode='stack',
    yaxis2=go.layout.YAxis(
        side='right',
        overlaying='y1',
        ticksuffix='%'
    )
)
fig = go.Figure(data=data, layout=layout)

plotly.offline.plot(fig)


text:
Q: Why am I seeing the Savage!, Elusive!, and Baroque! Qualities? I've noticed that I recently gained a few new Qualities, namely Savage!, Elusive!, and Baroque!:

It seems that these Qualities are part of the forbidden game of Knife-and-Candle, but I haven't put myself so in harm's way as to gain admittance to this dark sport.
I also have another picture to show how perplexing this situation is to me:

If I am not a player in the game of Knife-and-Candle, why am I seeing these Qualities?

A: A (very!) late response: I've found that, when you go on a zee-voyage, it clears a large number of progress qualities. This includes SAVAGE!, ELUSIVE!, and BAROQUE!.
If this problem happens again, and you have access to a zee-vessel, go on a cruise and it should clear things up.

A: If you're not in Knife-and-Candle, but these qualities are showing up, it's a bug in the game. Writing to support@failbettergames.com with your character name and an explanation of the bug will generally get it cleared up in short order.


text:
Q: Installing Vertica JDBC jar file in WIndows 7 Having trouble installing vertica_5.1.1_jdk_5 on my Windows 7 PC. I installed the latest Java SDK. When I type java -jar vertica_5.1.1_jdk_5.jar, I get "no main manifest attributes". I opened the MANIFEST file within the JAR, and found "Manifest-Version: 1.0
Created-By: 1.5.0_07 (Sun Microsystems Inc.)". So from what I've read, I'm missing a Main Class statement in here. How do I figure out what to add to this MANIFEST file?

A: A JDBC driver is a library to be used by a Java application. It is not a program itself, so it doesn't have a Main-Class attribute, and therefor cannot be run like you are trying to do.

A: Senza - vertica does not ship the java libraries as a self installing application.  Instead they ship just the jar that you can include in your classpath for your application.  Are you trying to make it work with a specific application? If so, message me and I will send instructions on how to make it work.


text:
Q: Error while running Emulator in Android Studio I'm new to android, i've wriiten a code for printing 'Hello World' which will show the result in emulator but there is a strange problem, which i'm unable to understand. please help me
here is the error
Cannot launch AVD in emulator.
Output:
emulator: WARNING: Classic qemu does not support SMP. The hw.cpu.ncore option from your config file is ignored.
libpng warning: iCCP: known incorrect sRGB profile
### WARNING: unable to configure any DNS servers, name resolution will not work
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
libpng warning: iCCP: known incorrect sRGB profile
Warning: No DNS servers found
emulator: warning: opening audio input failed
Unknown cp14 write op1:6 crn:0 crm:8 op2:6
qemu: fatal: Trying to execute code outside RAM or ROM at 0xff91c756
emulator: WARNING: UpdateCheck: Failure: Error
emulator: WARNING: UpdateCheck: failed to get the latest version, skipping check (current version '25.1.7'
R00=00000000 R01=000005a1 R02=00000100 R03=00000000
R04=00000000 R05=00000000 R06=00000000 R07=00000000
R08=00000000 R09=00000000 R10=00000000 R11=00000000
R12=00000000 R13=00000000 R14=00010010 R15=ff91c756
PSR=400001f3 -Z-- T svc32
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Now please help me what i can do in it.. It is all so complicated for me.

A: Did you already try disabling Hyper-V? If you didn't, you should do that, since the AVD is not compatible with Hyper-V.
If you're using Windows, you need to open a command prompt with administrator rights.
Enter following command then:
dism.exe /Online /Disable-Feature:Microsoft-Hyper-V-All


text:
Q: Cannot read property 'textContent' of null The below written code says cannot read property 'textContent' of null:
<form action="{%url 'Eats_app:pause_button'%}" method="post">
              {% csrf_token %}
              <button class="btn btn-primary " type="submit" value="Pause" id="pausebutton" style="padding-left: 3rem; padding-right: 3rem;" >Pause</button>
              <!-- /* <input class="btn btn-primary " type="submit" value="Pause" id="pausebutton" onclick="toggleTheButton()" style="padding-left: 3rem; padding-right: 3rem;"> */ -->
</form>

document.querySelector('#pausebuttons').textContent.toggle('Pause', 'Resume');

A: Your id that you are selecting is wrong. Try:
document.querySelector('#pausebutton').textContent.toggle('Pause', 'Resume');
To match the id of the element:
<button class="btn btn-primary" type="submit" value="Pause" id="pausebutton" style="padding-left: 3rem; padding-right: 3rem;" >Pause</button>

A: Error explanation to avoid future errors like this.
You are trying to get element pausebuttons with query selector but that is null.
The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned
Here you are getting null so no matches found with this selector. May be spelling mistake or something.
Please check it once again in your code.
 document.querySelector('#pausebuttons') is null that's why you are getting this error.

Solution:
You have id as pausebutton but in selector arguments you are passing pausebuttons . Extra s at the end.
document.querySelector('#pausebutton').textContent.toggle('Pause', 'Resume');


text:
Q: Dropbox PLAINTEXT REST API on AppEngine DownloadError I feel like I'm taking crazy pills. I've made a little dropbox API app which:

*

*Gets the list of /Photos using the /diff API

*Fetches each photo

*Parses the EXIF data

*Stores the EXIF data back into appengine.

I wrote it up and it works great on dev_appserver, but it fails when deployed to appengine.
The calls to the /delta work correctly, but calls to /files fail with an opaque "DownloadError".
Anyways, here is the relevant chunk of code:
def fetch_image(self, path):
  url = 'https://api-content.dropbox.com/1/files/dropbox' + path
  try:
    result = urlfetch.fetch(
      url=url,
      method=urlfetch.GET,
      allow_truncated=True,
      headers={ 'Authorization': get_authorization_header(self.authorization) })
  except DownloadError, exception:
    logging.exception(exception)
    logging.debug(get_authorization_header(self.authorization))

def get_delta(self, cursor=None):
  url = 'https://api.dropbox.com/1/delta'
  params = {
    'path_prefix': '/Photos',
  }
  if cursor is not None:
    params['cursor'] = cursor
  result = urlfetch.fetch(
    url=url,
    method=urlfetch.POST,
    payload=urllib.urlencode(params),
    headers={ 'Authorization': get_authorization_header(self.authorization) })
  return json.loads(result.content)

get_authorization_header produces the output like:
OAuth oauth_version="1.0", oauth_signature_method="PLAINTEXT", oauth_consumer_key="<app-key>", oauth_token="<access-token>", oauth_signature="<app-secret>&<access-token-secret>"

An example stack trace shows that there doesn't appear to be any error_detail.

Unable to fetch URL: https://api-content.dropbox.com/1/files/dropbox/Photos/**redacted**
Traceback (most recent call last):
  File "/base/data/home/apps/**redacted**", line 295, in update_image
    headers={ 'Authorization': getAuthorizationHeader(self.authorization) })
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 270, in fetch
    return rpc.get_result()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 612, in get_result
    return self.__get_result_hook(self)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/urlfetch.py", line 416, in _get_fetch_result
    raise DownloadError("Unable to fetch URL: " + url + error_detail)
DownloadError: Unable to fetch URL: https://api-content.dropbox.com/1/files/dropbox/Photos/**redacted**

I vaguely suspect this might be related to appengine mangling the authorization header into something like what happened in question 14716545 since it works on api and not on api-content, but I haven't been able to set up a test for that yet. Even if it is the case, there isn't anything I can do about it.

A: So I have it figured out. Basically I wasn't encoding the request url correctly. I was getting something like:
https://api-content.dropbox.com/1/files/dropbox/Photos/Some Event/Some File Name.jpg
which fails, but:
https://api-content.dropbox.com/1/files/dropbox/Photos/Some%20Event/Some%20File%20Name.jpg
works!


text:
Q: Rails - undefined method `delete' for nil:NilClass I'm getting the undefined method error when trying to run a search on Flickr using the Flickraw gem.
I'm quite new to Rails and have tried a few different methods but can't seem to get it to work.
Here is my application.html.erb,
<html>
<head>
 <title>Workspace</title>
 <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
 <%= javascript_include_tag 'application', 'data-turbolinks-track' => true%>
 <%= csrf_meta_tags %>
</head>
<body>
 <%= form_tag controller: "photos", action: "search", class: "navbar-form navbar-left", method: "get" do %>
 <div class="form-group">
   <%=text_field_tag :search, params[:text]%>
 </div>
 <%= submit_tag "Search", class: "btn btn-default" %>
 <% end %>

<%= yield %>
</body>
</html>

Here is my PhotosController,
class PhotosController < ApplicationController

require "flickraw"

def index
    @list = flickr.photos.getRecent
end

def search
    @results = flickr.photos.search(params[:text => "text"])
end
end

I thought that by passing the text parameter it would return with a list of public photos related to the text input.
Any help is appreciated.

A: params[:text => "text"] this is looking in the params hash for an entry with the key :text => text. It's extremely unlikely that this is actually what you wanted to do.
What you probably want is this:
@results = flickr.photos.search(params[:text] => "text")

(or something else like it... which matches how the search method works... which I don't know I'm just guessing)
Possibly more like just this:
@results = flickr.photos.search(params[:text])


text:
Q: view contains a convert that is imprecise or non-deterministic? My query:
IF OBJECT_ID ('vw_F_GWLVL_RAW', 'V') IS NOT NULL
DROP VIEW vw_F_GWLVL_RAW ;
GO

CREATE VIEW vw_F_GWLVL_RAW WITH SCHEMABINDING
AS
SELECT  S.SiteName,  CAST(D.[Date] as Date) as [Date], CONVERT(CHAR(5),T.[Time]) as [Time], CAST(F.SampleValue as NUMERIC(6,3)) as ValueAsRecorded,
            Q.Code as DataQualityCode, Q.QualityDesc as DataQualityDesc

FROM        dbo.F_GWLVL_RAW AS F INNER JOIN
                      dbo.D_Site AS S ON F.D_Site_Key = S.D_Site_Key INNER JOIN
                      dbo.D_Date AS D ON F.D_Date_Key = D.D_Date_Key INNER JOIN
                      dbo.D_Time AS T ON F.D_Time_Key = T.D_Time_Key INNER JOIN
                      dbo.F_ODP_QC_GWLVL AS Q ON Q.[Site] collate database_default = S.[SiteName] AND
                      (CONVERT(datetime,CAST(D.[Date] as VARCHAR(30))+' '+CAST(T.[Time] as VARCHAR(30)),121) BETWEEN Q.StartTime AND Q.EndTime)

GO
CREATE UNIQUE CLUSTERED INDEX IX_GWLVL_RAW1 ON vw_F_GWLVL_RAW(SiteName,[Date],[Time])

Gives me this error even though my convert is using deterministic 121 type:
'Cannot create index on view "dbo.vw_F_GWLVL_RAW". The view contains a convert that is imprecise or non-deterministic.'

A: Create INDEXED VIEWS.
You need to use a Deterministic Style in your CONVERT clause. The default is non-deterministic
Try,CONVERT(DECIMAL(10,2)) OR CONVERT(DATETIME, '20131202', 103)


text:
Q: Python Google API Web Crawler using OAuth 2 I currently crawl Google API using an API Key. It turns out I'd get a lot more request quota if I use OAuth. I already applied the OAuth in my website, but I don't know how to handle the token I got from those OAuth. I can't find the sample easy enough somehow. Have seen it a little bit, but lose it right away. Google API documentation is not guiding enough.
If someone can give me a sample code, that will be awesome.
This is my current code (with no OAuth, just normal API key):
import pprint
from apiclient.discovery import build

service = build('plus', 'v1', developerKey="my-api-key")
person = service.people().search(query='fransisca', language='id').execute()
pprint.pprint(person)

A: Never mind. Found it! It was hard. I think Google need to rethink of their own content SEO.
https://www.youtube.com/watch?v=h-gBeC9Y9cE&list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq&index=3
See minute 2 in the video.


text:
Q: Find a critical point satisfied the Lagrange condition is not local extremum We know that Lagrange Multiplier gives necessary conditions for an extremum.It locates all possible condidates.But not all such points need be extrma.
I want to find an example of  the point is neither local maxima nor local minima,but It is well satisfied the Lagrange Multiplier Condition.

A: In 1D calculus, an example of a function $f : \mathbb R \to \mathbb R$ where $f'(x) = 0$ does not give a local max or min is $f(x) = x^3$. Inspired by that, try this example:
Let $g(x,y) = x^2y$ with the constraint $h(x,y) = x - y = 0$. Then $\nabla g - \lambda \nabla h = 0$ iff
$$2xy - \lambda = 0 \ \text{ and } x^2 + \lambda = 0$$
I.e., $2xy = -x^2$ or $x(2y + x) = 0$. Which with the constraint necessarily implies $x = y = 0$. However $g(0,0) = 0$ is neither a local minimum or maximum.

For an example in higher dimensions, using the same inspiration:
Let $f(x_1, x_2, \cdots, x_n) = x_n$ with constraint $g(x_1, x_2, \cdots, x_n) = x_1^3 - x_n = 0$.
$\nabla f - \lambda \nabla g = 0$ iff $0 = -2\lambda x_1^2 = 1 + \lambda$ iff $\lambda = -1, x_1 = 0$. Thus $x_n = 0$, $f(x_1, ..., x_n = 0) = 0$. Which is again neither a local min or max.


text:
Q: What kind component is this? What kind of component is this? And is that crack normal or is it a sign that it's bad?

A: Spark Gap over voltage protector.
Here is another E.SE question relating to a similar air gap component.
The component could also incorporate a capacitor or MOV (metal oxide varistor) that the lead wire straddles and the spark gap is there to protect this component or provide additional protection.
The component lead wire was a continuous inverted U moulded into one or more layers of epoxy.  The component is then cut with a fine saw with a selected blade thickness to set the desired gap in the top of the wire loop. The ends of the cut component lead are the flat embedded electrodes of the spark gap.  Having decent gauge wire in a heavy epoxy body allows for decent heat dissipation.
The illustrated component manufacturer MDC also sells varistors and as this device is missing a capacitance rating it is more likely a plain spark gap or a varistor with a spark gap.
There is a similar looking product called variously a GAP-KAP or GAP CAP that incorporates the capacitor and protection spark gap.  These devices are found in higher voltage power supply circuits, CRT electron gun circuits and also in the front end protection of some (including Fluke) digital multi-meters.  Component failure is often characterised by burn marks in the gap area.
Just to speculate, but it might be possible in some variants that the epoxy will char and swell and short out the gap with a continued over voltage condition and blow a protection fuse.
EDIT:
It looks like some of the Fluke meters as described in this forum thread come with spark gaps that look like this component and have had them replaced with MOVs in later design revisions.  Components with kV ratings in places that should never have high voltages present are going to be some kind of protection device.  It also looks like the charring may act as an optical and electrical failure indicator.


text:
Q: Picker Unavailable. There was an error while preparing the picker. Please try again later I got this error when using photo picker, it only appeared occasionally when I swipe down to download more photos or tap the search box.

2020-09-29 21:20:21.268201+0700 Widgets[16820:1808484] [lifecycle] [u 154CDFD9-7610-4333-99DE-0FDA8CF04E77:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin interrupted while in use.
2020-09-29 21:20:21.268855+0700 Widgets[16820:1808408] [lifecycle] [u 154CDFD9-7610-4333-99DE-0FDA8CF04E77:m (null)] [com.apple.mobileslideshow.photospicker(1.0)] Connection to plugin invalidated while in use.
2020-09-29 21:20:21.268581+0700 Widgets[16820:1806436] [Picker] Picker failed with error: Error Domain=PXErrorDomain Code=-1 "PHPickerViewController did receive interruption." UserInfo={NSDebugDescription=PHPickerViewController did receive interruption.}
2020-09-29 21:20:21.293818+0700 Widgets[16820:1806436] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}

How do i fix it? :(

A: I was getting the same errors and was able to resolve my issue by moving the .sheet modifier (for the picker) from a List row to the List itself.


text:
Q: c++ passing std::function with custom object as argument in threading I have an seperate class to handle threading, and there is a function need to create a thread and repeat the function for a specific interval
void timer_start_custom(std::function<void(string, string&, vector<CustomObject>&)> func, string filename, string& lastline, vector<CustomObject>& dict, unsigned int interval){
     std::thread([func, interval, filename, lastline, dict](){
         while (true){
             auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
             func(filename, lastline, dict);
             std::this_thread::sleep_until(x);
         }
     }).detach();
}

however, right now the compiler compain :
No matching function for call to object of type 'const
std::function<void (string, string &, vector<RowData> &)>' (aka
'const function<void (basic_string<char, char_traits<char>, allocator<char> >,
basic_string<char, char_traits<char>, allocator<char> > &, vector<RowData> &)>')

I know if a place the function in the same file, then i can skip the func as parameter, but i am still very curious and stubborn to know how to work this out, as i will call the timer_start_custom in different file and pass in different functions

A: Your problem is that you are capturing lastline and dict by-value and then passing them to the func which expect non-const references. You probably need to capture like this instead:
std::thread([func, interval, filename, &lastline, &dict] {
...
});

However you should be especially careful when capturing by-reference to make sure that those object are still alive when they are used in lambda, especially given that you are calling it in a separate thread. This also creates a possibility of a data race, so if you are going to access lastline and dict from several threads you need to make sure to use proper synchronization mechanisms such as std::mutex.

A: Capturing variables by value makes them implicitly const in the body of the lambda, which is why passing them to func as non-cost references fails to compile.
You can therefore either do what r3mus n0x recommends in their answer, or pass them to func by value or as const ref.  I think I prefer r3mus n0x's solution as it involves fewer temporaries, provided that the variables referred to don't go out of scope while the thread is executing..


text:
Q: MySQL, WHERE to contain separate table I've managed to get the first part of my query working fine, it's the final part with the date check that is throwing me.
SELECT * FROM users WHERE available LIKE 'Yes' AND users.id NOT IN (SELECT player_id FROM match_request WHERE club_id LIKE '1000000003') AND (clubs.match_date >= CURRENT_DATE() WHERE clubs.id LIKE '1000000003')

It's this part that I can't work out:
(clubs.match_date >= CURRENT_DATE() WHERE clubs.id LIKE '1000000003')

I get the error message

"#1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'WHERE clubs.id LIKE '1000000003') LIMIT 0, 25' at line 1"

But I don't know how to fix this.

A: Replace  where with and
SELECT *
FROM users
WHERE available LIKE 'Yes'
AND users.id NOT IN
(
   SELECT player_id
   FROM match_request
   WHERE club_id LIKE '1000000003'
)
AND clubs.match_date >= CURRENT_DATE()
AND clubs.id LIKE '1000000003'
^^^-----here

and you need to join the clubs table if you  refer to any columns of that table


text:
Q: Get the avaliable XPaths of an Html page? I've taken and adapted this code of how to retrieve the XPath expressions of an XML document.
I Would like to do the same but using an html page to retrieve its avaliable XPaths ( maybe an HtmlDocument? ), is this possibly?
Note: I can accept a native solution or else using HtmlAgilityPack library.
This is the XML method:
''' <summary>
''' Gets all the XPath expressions of an XML Document.
''' </summary>
''' <param name="Document">Indicates the XML document.</param>
''' <returns>List(Of System.String).</returns>
Public Function GetXPaths(ByVal Document As Xml.XmlDocument) As List(Of String)

    Dim XPathList As New List(Of String)

    Dim XPath As String = String.Empty

    For Each Child As Xml.XmlNode In Document.ChildNodes

        If Child.NodeType = Xml.XmlNodeType.Element Then
            GetXPaths(Child, XPathList, XPath)
        End If

    Next ' child

    Return XPathList

End Function

''' <summary>
''' Gets all the XPath expressions of an XML Node.
''' </summary>
''' <param name="Node">Indicates the XML node.</param>
''' <param name="XPathList">Indicates a ByReffered XPath list as a <see cref="List(Of String)"/>.</param>
''' <param name="XPath">Indicates the current XPath.</param>
Private Sub GetXPaths(ByVal Node As Xml.XmlNode,
                      ByRef XPathList As List(Of String),
                      Optional ByVal XPath As String = Nothing)

    XPath &= "/" & Node.Name

    If Not XPathList.Contains(XPath) Then
        XPathList.Add(XPath)
    End If

    For Each Child As Xml.XmlNode In Node.ChildNodes

        If Child.NodeType = Xml.XmlNodeType.Element Then
            GetXPaths(Child, XPathList, XPath)
        End If

    Next ' child

End Sub

A: As far as I can see, HtmlAgilityPack has a very similar class structures to XmlDocument. So I believe you can easiliy adapt current solution to cope with HtmlDocument, something like this :
Public Function GetXPaths(ByVal Document As HtmlDocument) As List(Of String)
    Dim XPathList As New List(Of String)
    Dim XPath As String = String.Empty
    For Each Child As HtmlNode In Document.DocumentNode.ChildNodes
        If Child.NodeType = HtmlNodeType.Element Then
            GetXPaths(Child, XPathList, XPath)
        End If
    Next ' child'
    Return XPathList
End Function

Private Sub GetXPaths(ByVal Node As HtmlNode,
                  ByRef XPathList As List(Of String),
                  Optional ByVal XPath As String = Nothing)
    XPath &= "/" & Node.Name
    If Not XPathList.Contains(XPath) Then
        XPathList.Add(XPath)
    End If
    For Each Child As HtmlNode In Node.ChildNodes
        If Child.NodeType = HtmlNodeType.Element Then
            GetXPaths(Child, XPathList, XPath)
        End If
    Next ' child'
End Sub

Worked fine when tested using HTML that is XML compliant. But I can't guarantee about how far this will work against malformed HTML documents.


text:
Q: Последовательность от a до zzz Как перебрать последовательность букв в цикле? каждую последовательность нужно иметь возможность получить, зная номер позиции.
1=a
2=b
...
z=26
aa=27
ab=28
ac=29
...
и так до zzz
Что-то вроде системы счисления, но без цифр.

A: Оно похоже на просто систему счисления, но беда в том, что в ней нет нуля...
Вобщем, проще чем приведенное у меня что-то с утра не получается. Приходится учитывать, что a - это не нуль...
string az(unsigned int num)
{
    string s("");
    --num;               // Для отсчета с 0
    s += 'a' + num%26;   // Чередование последней буквы
    if (num >= 26)       // Есть вторая буква
    {
        num -= 26;
        s += 'a' + num/26%26;
    }
    if (num >= 26*26)    // Есть третья буква
    {
        num -= 26*26;
        s += 'a' + num/(26*26);
    }
    reverse(s.begin(),s.end());
    return s;
}

int main(int argc, const char * argv[])
{
    for(unsigned int n = 1; n <= 18278; ++n)
        cout << setw(5) << n << "  " << az(n) << endl;
}

Update
Все, написал в общем виде, кратенько и красиво :)
string az(unsigned int num)
{
    string s("");
    for(unsigned int cnt = 1; num >= cnt; cnt *= 26)
        s = char('a' + (num-=cnt)/cnt%26) + s;
    return s;
}

Update 2
Только для @AnT :)
string div26(const string& d, unsigned int& r)
{
    string q;
    r = 0;
    if (d.length() == 0) return q;
    bool wroted = false;
    for(size_t i = 0; i < d.length(); ++i)
    {
        r = r*10 + (d[i]-'0');
        unsigned int v = r/26;
        r %= 26;
        if (!wroted && v == 0) continue;
        q += char('0' + v);
        wroted = true;
    }
    return q;
}

void dec(string& n)
{
    if (n.length() == 0) return;
    if (n.length() == 1 && n[0] == '0') return;
    for(int i = n.length()-1; i >= 0; --i)
    {
        if (n[i] >= '1') { --n[i]; break; }
        n[i] += 9;
    }
    size_t nz = n.find_first_not_of("0");
    if (nz == string::npos) n = "";
    else n = n.substr(nz);
}

string az(const string& number)
{
    string res;
    for(string n = number; n.length();)
    {
        dec(n);
        unsigned int r;
        n = div26(n,r);
        res = char('a' + r) + res;
    }
    return res;
}

Проверяйте. Строка номер гугол: hxrtplbmwaiwcqlzpmglpziaegsdivmbvlnssusbjtbcgywaycqnhxztqwwikxvrsptazpp

A: В вашей системе счисления, условно выражаясь, есть ведущие нули, но нет "внутренних" нулей. Ведущие нули присутствуют только в начале "времени жизни" разряда, т.е. как только разряд стал ненулевым, он уже никогда не станет нулевым.
Это позволяет нам использовать классический алгоритм перевода путем итеративного деления с остатком на основание системы счисления, не забывая при этом, что каждый разряд начинает свою жизнь в особом - "пустом"/"нулевом" - состоянии. Это отражается в том, что перед выполнением деления с остатком, надо вычесть из переводимого значения единицу. В это правило, кстати, естественным образом вписывается соглашение о том, что значению 0 соответствует пустая строка.
За исключением этого предварительного вычитания единицы, классический "школьный" алгоритм перевода остается неизменным
std::string convert_ascii(unsigned v, unsigned b)
{
  std::string s;

  for (; v > 0; v /= b)
  {
    --v; // предварительное вычитание единицы
    s = (char) ('a' + v % b) + s;
  }

  return s;
}

Вот и все.
В вашем случае b = 26. Например, convert_ascii(12345678, 26) дает нам zzjut, а convert_ascii(322973, 26) - rita.

A: Решение так сказать в лоб.
Это конечно не c++ и не delphi(это java), но идея в принципе думаю понятна.
public class Main {
    public static void main(String[] args) {
        int n = 26;
        int iterator = 0;
        int L = n + n * n + n * n * n; // общая длина массива
        String[] code = new String[L + 1]; // сам массив
        for (int i = 97; i <= 122; i++) { // заполняем для первой буквы
            iterator++;
            code[iterator] = String.valueOf((char) i);
        }
        for (int i = 97; i <= 122; i++) {// заполняем для второй буквы
            for (int j = 97; j <= 122; j++) {
                iterator++;
                code[iterator] =(char) i +"" + (char) j;
            }
        }
        for (int i = 97; i <= 122; i++) {// заполняем для третей буквы
            for (int j = 97; j <= 122; j++) {
                for (int k = 97; k <= 122; k++) {
                    iterator++;
                    code[iterator] = ""+(char) i + (char) j + (char) k;
                }
            }
        }
        Scanner scanner=new Scanner(System.in);
        System.out.println(code[scanner.nextInt()]); // выводим на консоль нужный символ
    }
}

Вывод всё как надо:
    1
    a
    26
    z
    1000
    all
    27
    aa


text:
Q: Extracting .currentCellRow fields from SAP to Excel I have been using vba with SAP for a while now and have never run into this particular issue.
Usually, when script recording in SAP, I click on a field and am left with some string of code with a .setfocus as the end. I replace this with .text in order to extract the data in that cell.
I have run into a menu that ends in .currentCellRow= # and thus if I change it, it loses its position and has no idea what field I am talking about.
Is there any way that I can adjust this to pull data from these fields?
Here is an example of a field I scripted
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").currentCellRow = 4

A: .getcellvalue(4,"name of column")
see too: https://answers.sap.com/questions/300278/reading-grid-cells-sap-gui-scripting-vbs.html
Regards,
ScriptMan


text:
Q: How can I transform a graded colored map into a percentage matrix (convert pixel color into a percentage based on a palette)? I'd like to convert this graded colored map into a matrix in which to each pixel a percentage of orange is assigned. In particular, taking the color palette of orange at the right of image.
I'd like to assign 100% to the brightest orange at the top and 0% to the black at the bottom. Hence, I'd like to assign to each pixel a percentage, based on the color of that single pixel in relation to the palette.
Finally, my goal consists of averaging these percentages in order to get a sort of mean percentage of orange. For the latter step, I shouldn't have any issue... but I've no idea how to face the former problem.
I am looking for a solution either in R, Matlab or Mathematica

A: Here's an idea that I had. Suppose you have an image with arbitrary colors; let's solve for a transformation that reduces your color from 3-dimensional space to a single dimension by running an optimizer. The cost function is derived from the error when the original colors are attempted to be recovered by the lossy color transformation.
See the image below for my result, scaled to 100% at the brightest pixel and 0% at the darkest.
img = imread('zpiaD.png');
opt = optimset('Display', 'Iter');

itf = fminsearch(@(itf) min_colormap(img, itf) , zeros(1,3), opt);
[~, rimg] = min_colormap(img, itf);

subplot(2,1,1), imshow(rimg), title 'single color dimension'
subplot(2,1,2)
rimg = double(rimg);
imagesc(100 * (rimg - min(min(rimg))) / (max(max(rimg)) - min(min(rimg)))),
colorbar, title 'scaled'

function [res, timg] = min_colormap(img, itf)
  pimg = double(reshape(img, size(img,1)*size(img,2), size(img,3)));
  timg = transpose(itf * pimg');
  res = sum(((timg * itf) - pimg).^2, 'all');
  timg = cast(reshape(timg, size(img,1), size(img,2)), 'uint8');
end


text:
Q: Javascript appending; What is considered best practice? Can anyone explain what is considered the best practice in appending in javascript?
var element = document.createElement('p');
element.innerHTML = 'This is appended' ;
var div = document.getElementById('div');
div.appendChild(element);

or
var div = document.getElementById('div');
div.innerHTML = '
This is appended
';

I see a lot of people doing it like this in jQuery:
$('#div').append('
This is appended
');

But i've always done it like this:
var element = document.createElement('p');
element.innerHTML = 'This is appended' ;
$('#div').append(element);

Thank you in advance

A: if you're using jQuery, absolutely nothing wrong with:
$('#div').append('
This is appended
');
Its less code and less steps.

A: IMO, when you're working with a DOM, treat it like a DOM instead of a string.
In other words, don't use markup to create elements or text nodes. Use DOM creation methods.
document.getElementById('div')
        .appendChild(document.createElement('p'))
        .appendChild(document.createTextNode('This is appended'));

Microsoft's .innerHTML invention can be tempting, and perhaps useful in a pinch, but I usually avoid it.
You can reduce the verbosity of the methods above with helpers.

A: I typically build an element using jQuery.
var paragraph = $("
", {
  className : "someClass",
  text : "this is appended"
})

div.append(paragraph)

I believe that this approach is preferred to directly injecting HTML because it's less intrusive on the DOM.