text:
Q: Python Virtual environment [Some of the python libraries is getting installed out of virtual environment directory] Scenario:
We are creating virtual environment and installing all the requirement.txt files but few files are getting created outside the directory.
Use case:
We want to zip this environment and want to use it for spark driver and executors
Problem:
Since few files are getting installed out of virtual environment directory, hence spark is failing with module not found exception or lib*.so file not available.

A: To solve this I applied certain steps:
Written a blog:
https://kshitij-kuls.com/2019/08/04/setting-up-virtual-environment-for-pyspark/
Before we proceed it's require to understand the basic structure of python:
├── bin
│   ├── activate
│   ├── activate.csh
│   ├── activate.fish
│   ├── activate_this.py
│   ├── easy_install
│   ├── easy_install-3.6
│   ├── pip
│   ├── pip3
│   ├── pip3.6
│   ├── python
│   ├── python-config
│   ├── python3 -> python
│   ├── python3.6 -> python
│   └── wheel
├── include
│   └── python3.6m -> /usr/include/python3.6m
├── lib
│   └── python3.6
|       ├── site-packages
│       ├── lib-dynload -> /usr/lib/python3.6/lib-dynload [Dynamic Library]

Environment Variables:
PYSPARK_PYTHON : Points to the executable python file: bin/python
LD_LIBRARY_PATH : Points to the dynamic library path: lib/python3.6/lib-dynload [All .so* files]
PYTHONPATH : Points to the installed packages within virtual environment as well as the dynamic library path : lib/python3.6/site-packages<CPS>lib/python3.6/lib-dynload [All .py files]
PYTHONHOME : Points to the python library path: lib/python3.6/site-packages
Steps to build Virtual environment:
Install python in the machine of desired version.
Create Virtual Env
virtualenv env -p /usr/local/bin/python3
Activate Virtual Env
source env/bin/activate
Install requirements
pip install numpy

Now here is the trick, you can see this
line
├── lib-dynload -> /usr/lib/python3.6/lib-dynload
it's a symbolic link and pointing to the local machine path and hence even if you just zip this virtual environment folder then these dependencies would be missing on the cluster.
So, it's required to copy all the .so* files from /usr/lib/python3.6/lib-dynload, /usr/lib64/*.so.*, etc... to lib/python3.6/lib-dynload
Copy all the .py files from /usr/lib/python3.6/lib-dynload, /usr/lib64/*.so.*, etc... to lib/python3.6/site-packages.
Run it from the home dir of virtual environment in our case it's env/
Prepare zip
zip -rq ../venv.zip *
Upload the zip to the /udf folder for tdss: /tookitaki/tdss/udf/

Environmental variable setup
For driver: spark.yarn.appMasterEnv.[Environment variable]
For executor: spark.executorEnv.[Environment variable]
PYSPARK_PYTHON
pyspark.spark.yarn.appMasterEnv.PYSPARK_PYTHON = venv/bin/python
pyspark.spark.executorEnv.PYSPARK_PYTHON = venv/bin/python
PYTHONHOME
pyspark.spark.yarn.appMasterEnv.PYTHONHOME = venv/lib64/python3.6/site-packages
pyspark.spark.executorEnv.PYTHONHOME = venv/lib64/python3.6/site-packages
LD_LIBRARY_PATH
pyspark.spark.yarn.appMasterEnv.LD_LIBRARY_PATH = venv/lib64/python3.6/lib-dynload
pyspark.spark.executorEnv.LD_LIBRARY_PATH = venv/lib64/python3.6/lib-dynload
PYTHONPATH
This need to included in YARN-ENV-ENTRIES, it's not getting set from the spark configs.
PYTHONPATH = {{PWD}}/__venv__.zip<CPS>{{PWD}}/__py4j-0.10.7-src__.zip<CPS>venv/lib64/python3.6/site-packages<CPS>venv/lib64/python3.6/lib-dynload<CPS>
To run python
cd venv
export PYTHONPATH=lib64/python3.6/site-packages:lib64/python3.6/lib-dynload/
export LD_LIBRARY_PATH=lib64/python3.6/lib-dynload
source bin/activate


text:
Q: How do I convert raw camera data into a Bitmap on Android I obtain raw camera data rawData of type byte[], format RGBA, size 640x480, 4 bytes per pixel, from a library function. And I need to convert it to a Bitmap and display in an ImageView on the screen.
What I do is the following:
byte[] JPEGData = convertToJpeg(rawData, 640, 480, 80);
Bitmap bitmap = BitmapFactory.decodeByteArray(JPEGData , 0, JPEGData .length);
imageView.setImageBitmap(bitmap);

where convertToJpeg() function is:
    public static byte[] convertToJpeg(byte[] buffer, int w, int h, int quality) {
        YuvImage yuv_image = new YuvImage(buffer, ImageFormat.NV21, w, h, null);

        Rect rect = new Rect(0, 0, w, h);
        ByteArrayOutputStream output_stream = new ByteArrayOutputStream();
        yuv_image.compressToJpeg(rect, quality, output_stream);

        Bitmap sourceBmp = BitmapFactory.decodeByteArray(output_stream.toByteArray(), 0, output_stream.size());
        Bitmap destBmp = Bitmap.createScaledBitmap(sourceBmp, (int) (w * 0.75), (int) (h * 0.75), true);

        ByteArrayOutputStream pictureStream = new ByteArrayOutputStream();
        destBmp.compress(CompressFormat.JPEG, quality, pictureStream);
        byte[] pictureByteArray = pictureStream.toByteArray();

        return pictureByteArray;
    }

After decodeByteArray() call I have bitmap.getConfig() == ARGB_8888.
However, what I see on the screen is some chaotic picture, with some blurry green shapes of what's been in the original picture.
What's wrong with it?

A: The solution has turned out to be simple. And no need to convert to JPEG.
Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(rawData));

A: ByteBuffer().rewind to reset the buffer position to 0 than the "buffer not large enough for pixels" solved

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node.js - How to create a unique id with mongoose db I am working with Twitter authentication and want to store the twitter id as unique key in mongodb. However i see multiple entries with the same id. Here's my schema and code
Schema:
var TwitterSchema = new Schema({
    accessToken: String,
    accessTokenSecret: String,
    name: String,
    twitterId: { type: String, required: true, index: { unique: true, sparse: true } }
});

Code:
        mongoose.connect('mongodb://localhost/twd')
        mongoose.model('Post', TwitterSchema);
        var Post = mongoose.model('Post');

        var post = new Post();
        post.accessToken = accessToken
        post.accessTokenSecret = accessTokenSecret
        post.name = twitterUserData.name
        post.twitterId = twitterUserData.id

        post.save(function(err){
            if (err){
                throw err;
                promise.fail(err);
             }
            console.log('saved');
            mongoose.disconnect();
        });

        promise.fulfill(post);

DB shell output
> db.posts.find();
{ "twitterId" : "21475255", "name" : "MMMK", "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU243j8aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf6155203990e000001") }
{ "twitterId" : "21475255", "name" : "MMMK, "accessTokenSecret" : "ZYhiXMWfXvSr1aaCB93hgU2438aapP0ALdSFlWEE", "accessToken" : "22475255-9YvKMceUInUIxcEtKAK0oMRRG2ZZxn5c52vnwPw", "_id" : ObjectId("4feddf7b5905a1a10e000001") }

A: My guess is either the index isn't being created in MongoDB, or the index with the same name already exits. If it already exists, mongoose will use ensureIndex to create it, but that won't override/redefine it if it already exists. Use the mongo js shell to see if it exists, then try dropping it, restarting mongod, and running your node.js code again.
http://www.mongodb.org/display/DOCS/Indexes#Indexes-CreationOptions


text:
Q: Very wide UITextField in a UIScroller moves to right initially All,
I have a wide UITextField with a wide Canvas (UIView) together in a scroller and Stack. The structure is as follows:
UIScrollView (scrolls both horizontally and vertically)
    UIStackView (vertical)
        UITextField
        UIView (the canvas that displays all sorts of visual elements)

The UIView is 2000 pixels wide, as is the UITextField. They are both supposed to scroll together - hence them both living in the stack inside the scroller.
When I click in the UITextField to begin editing, whether it is empty or already has text, it zooms off to the far right end.
I have used something like this to try and control the position:
    public void MoveCursorToVisibleIfRequired()
        {
            //  Pixel position of cursor
            CGPoint cursorPosition = NoteTitle.GetCaretRectForPosition(NoteTitle.SelectedTextRange.Start).Location;
            //  Is it currently visible in the scroll view (with at least 20 px?)
            var scrollPos = ContentScrollView.ContentOffset;
            var scrollWidth = ContentScrollView.Frame.Width;
            if (cursorPosition.X+20 < scrollPos.X || cursorPosition.X > scrollPos.X + scrollWidth - 20)
            {
                //  Lets move it into the middle of the text region (if possible)
                cursorPosition.X -= (int)(ContentScrollView.Frame.Width / 2);
                //  Make sure we are not going too far
                if (cursorPosition.X < 0)
                    cursorPosition.X = 0;
                ContentScrollView.SetContentOffset(cursorPosition, true);
            }
        }

When the cursor position gets too close to the left or right of the visible portion of the UITextView, the cursor is moved to the middle by moving the scroller. That works well, and I have attached it to:

*

*EditingChanged

*EditingDidBegin (for when you click in the text field)

*Cursor movement (by adding an observer to changes in "selectedTextRange")

As I type, the textfield periodically animates/moves the cursor to the middle.
Weirdly, the UIScrollView (and therefore the UITextField and UIView) is zipping off to the far right when I click in the UITextField to give it focus, and also when the UIViewController loads and I give the UITextField first responder status.
I am positive that my MoveCursorToVisibleIfRequired function is not misbehaving somehow because I have breakpointed it to check values, and this behaviour pre-dated that function.
Any thoughts why a scroller containing a very wide text field and UIView might zoom off to the far right on getting first responder status?
Thx.

A: Here is a workaround. It doesn't resolve the question of WHY a UITextField getting focus causes the containing scroller to zoom off to the right... but it does make things work.
a) Embed the UITextField in a UIView. So the hierarchy becomes this:
UIScrollView (scrolls both horizontally and vertically)
    UIStackView (vertical)
        UIView
            UITextField
        UIView (the canvas that displays all sorts of visual elements)

b) Make the UITextField a dynamic size - so it resizes based on the contained text.
c) Ensure its parent UIView full width (2000 px wide).
Now clicking in the UITextField does not cause crazy scrolling. However because the UITextField is small - there is a lot of white space to its right (the parent UIView).
d) Add a Tap gesture recogniser on the parent UIView that sets First Responder to the UITextField. This replicates the functionality of clicking anywhere in a text field to get focus.
    var vw = NoteTitle.Superview;
    var tap = new UITapGestureRecognizer((gest) =>
            {
                if (gest.State == UIGestureRecognizerState.Ended)
                    NoteTitle.BecomeFirstResponder();
            });
    vw.AddGestureRecognizer(tap);


text:
Q: AdventureWorks Sample DB Could someone please help me with this. I would like to install the AWDB sample database to use with SharePoint 2010 on my Win7 dev system.
So SQL 2008 Express.
I have tried to download various things from codeplex, basically because I don't know the difference between the types. I have tried to look this up online in some blog posts but none of what I find/follow seem to work.
I think this is where I need to download what I need  here, but I am not sure what I need exactly. At this point I am just trying to get the db in SQL right now, and I am maybe novice with sql at that point, but really just want to start experimenting with BCS in SP2010 anyway.
Any takers helping a rookie? Always appreciated! Thanks guys!

A: AdventureWorks2008R2-Full Database Backup.zip would be fine.
Then in SQL Express use:
restore database [database_name] from disk = 'backup path'
  with move 'AdventureWorks2008R2_Data' to '<database_data_file_path>\<filename>.mdf',
       move 'AdventureWorks2008R2_Log' to '<database_log_file_path>\<filename>.ldf'


text:
Q: Problems about protocol and drawing in SwiftUI I want to define a Symbol protocol and write three different structs, Rectangle, Diamond and Oval. The first two are OK, but Oval returns UIBezierPath instead of Path. What should I do
//
//  Symbol.swift
//  Set
//
//  Created by world on 2022/11/27.
//

import SwiftUI

protocol Symbol: Shape {
    var numberOfSymbols: SetGame.Card.Number { get }
    func drawing(_ path: Path, center: CGPoint, width: CGFloat, height: CGFloat) -> Path
}

extension Symbol {
    func path(in rect: CGRect) -> Path {
        let widthOfRect = rect.maxX - rect.minX
        let heightOfRect = rect.maxY - rect.minY
        let widthOfSymbol = widthOfRect
        let heightOfSymbol = widthOfSymbol / 2
        var path = Path()
        switch numberOfSymbols {
        case .one:
            path = drawing(path, center: CGPoint(x: rect.midX, y: rect.midY), width: widthOfSymbol, height: heightOfSymbol)
        case .two:
            path = drawing(path, center: CGPoint(x: rect.midX, y: heightOfRect * 1/3), width: widthOfSymbol, height: heightOfSymbol)
            path = drawing(path, center: CGPoint(x: rect.midX, y: heightOfRect * 2/3), width: widthOfSymbol, height: heightOfSymbol)
        case .three:
            path = drawing(path, center: CGPoint(x: rect.midX, y: heightOfRect * 1/4), width: widthOfSymbol, height: heightOfSymbol)
            path = drawing(path, center: CGPoint(x: rect.midX, y: heightOfRect * 2/4), width: widthOfSymbol, height: heightOfSymbol)
            path = drawing(path, center: CGPoint(x: rect.midX, y: heightOfRect * 3/4), width: widthOfSymbol, height: heightOfSymbol)
        }
        return path
    }
}

This is the diamond part that has been implemented
result: Diamond Image
//
//  Diamond.swift
//  Set
//
//  Created by world on 2022/11/27.
//

import SwiftUI

struct Diamond: Symbol {
    var numberOfSymbols: SetGame.Card.Number

    func drawing(_ path: Path, center: CGPoint, width: CGFloat, height: CGFloat) -> Path {
        var path = path
        let rightPoint = CGPoint(x: center.x + width/2, y: center.y)
        path.move(to: rightPoint)
        let bottomPoint = CGPoint(x: center.x, y: center.y + height/2)
        let leftPoint = CGPoint(x: center.x - width/2 , y: center.y)
        let topPoint = CGPoint(x: center.x, y: center.y - height/2)
        path.addLine(to: bottomPoint)
        path.addLine(to: leftPoint)
        path.addLine(to: topPoint)
        path.addLine(to: rightPoint)
        return path
    }
}

I haven't implemented the oval part yet
//
//  Oval.swift
//  Set
//
//  Created by world on 2022/11/27.
//

import SwiftUI

struct Oval: Symbol {
    var numberOfSymbols: SetGame.Card.Number

    func drawing(_ path: Path, center: CGPoint, width: CGFloat, height: CGFloat) -> Path {
        var path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: height), cornerRadius: 0)
// ...
    }
}

Perhaps this can be solved by function overloading


text:
Q: Listener Placement Adhering to the Traditional (non-mediator) MVC Pattern I'm implementing a program within Swing, and I've read Nirmal's implementation of this pattern in Swing, which seems to show a rather elegant handling of the whole "separation of responsibilities" concept.
However, as I'm developing a more complicated program than the one posted by Nirml, which consists of a single JFrame container, I look for guidance as how to implement MVC properly.
My program will be consisting of sub-containers and such. I am curious as to how the Controller is supposed to implement the logic behind defining and assigining all the listeners of the View.. or if the controller defining the listeners for every single View component is even practical?
It would seem that I would need a method in the View's top-level container to allow the Controller to invoke the view to add a Listener to the component in question? and so I would need a chain of methods, each passing down the listener from the top-level container, to the immediate container holding the component.. culminating with the container invoking addActionListener() on it.
Is this the proper way to handle listeners in MVC?
Is defining all listeners of every component in the View by the Controller mandatory in MVC, or a useful practice? This would also imply that I create methods in the top-level container(View) to give the Controller a way to assign listeners to every single component in sub-containers?

A: Okay, first things first, Swing implements a form of the MVC already, albeit in the form of VC-M.  This means that you shouldn't try and constrain Swing to a pure MVC directly, as you'll be very disappointed and spend a lot of time trying to make hacks where they shouldn't be.
Instead, you can wrap a MVC around Swing, allowing it to work around the API instead.
To my mind, a controller doesn't need to know, nor should it care, how the view or model are implemented, but it should only care how it can work with them (I've had too many developers get hold of UI components and do things to/with them that they shouldn't have, and broken the API when we've changed the implementation. It's best to hide that kind of detail)
In this vein, you can think of a view as self contained entity - it has controls and it does stuff independent of the controller. The controller doesn't care about the implementation specifics. What it does care about is getting information and been told when some event, described by the contract, has occurred.  It shouldn't care about HOW it was generated.
For example, say you have a login view.  The controller only wants to know the user name and password that the user entered and when it should validate that information.
Let's say you implement the view/controller to expose the JTextField and JPasswordFields to start with, but later on, your users want the user name selection to be restricted to a specific list (possibly provided by the model). Now you have implementation details stuck in your controller which are no longer applicable and you have to manually change or create a new MVC for this new use case.
What if, instead, you simply stated that the view has a getter for the user name and password and some kind event listener which would tell the controller when the user wanted the credentials verified?  Well now, you'd only need to provide a new view, no need to modify the controller.  The controller won't care HOW these values are generated.
As to the greater aspect of your question.

My program will be consisting of sub-containers and such. I am curious
  as to how the Controller is supposed to implement the logic behind
  defining and assigning all the listeners of the View.. or if the
  controller defining the listeners for every single View component is
  even practical?
It would seem that I would need a method in the View's top-level
  container to allow the Controller to invoke the view to add a Listener
  to the component in question? and so I would need a chain of methods,
  each passing down the listener from the top-level container, to the
  immediate container holding the component.. culminating with the
  container invoking addActionListener() on it.
Is this the proper way to handle listeners in MVC?

The general answer is, no, it's not the proper way.
Each sub view would become its own MVC, with it focusing on its own requirements. The parent MVC might use events or other functionality provided by the child MVC's to make updates or even modify the states of other child MVCs.
The important thing to remember here, is a view can act as a controller for other views, although, you might choose to have a series of controllers which the view would be allowed to manage.
Imagine something like a "wizard". It has a bunch of steps which collects various information from the user, each step needs to be valid before it can move on to the next step.
Now, you might be tempted to integrate navigation into this directly, but a better idea would be to separate the navigation details as its own MVC.
The wizard would, when asked, present a step to the user, the user would fill in the information, possibly triggering events.  These events would then allow the navigation MVC to decide if the user can move to the next step or the previous step.
The two MVC's would be controlled by a third "master" MVC which would help manage the states (listening for events from the wizard and updating the state of the navigation)
Let's try an example with a question that gets asked way to much around here, a quiz!
A quiz has questions, each question has a prompt, a correct answer, a series of possible answers and we also want to store the resulting answer from the user.
The Quiz API
So, below we have the basic outline of the quiz MVC, we have a question, which is managed by a model, there is a controller and a view and series of observers (listeners)
The Contracts (interfaces)
public interface Question {
    public String getPrompt();
    public String getCorrectAnswer();
    public String getUserAnswer();
    public String[] getOptions();
    public boolean isCorrect();

}

/**
* This is a deliberate choice to separate the update functionality
* No one but the model should ever actually -apply- the answer to the
* question
*/
public interface MutableQuestion extends Question {
    public void setUserAnswer(String userAnswer);
}

public interface QuizModel {
    public void addQuizObserver(QuizModelObserver observer);
    public void removeQuizObserver(QuizModelObserver observer);
    public Question getNextQuestion();
    public Question getCurrentQuestion();
    public int size();
    public int getScore();
    public void setUserAnswerFor(Question question, String answer);
}

public interface QuizModelObserver {
    public void didStartQuiz(QuizModel quiz);
    public void didCompleteQuiz(QuizModel quiz);
    public void questionWasAnswered(QuizModel model, Question question);
}

public interface QuizView extends View {
    public void setQuestion(Question question);
    public boolean hasAnswer();
    public String getUserAnswer();
    public void addQuizObserver(QuizViewObserver observer);
    public void removeQuizObserver(QuizViewObserver observer);
}

public interface QuizViewObserver {
    public void userDidChangeAnswer(QuizView view);
}

public interface QuizController {
    public QuizModel getModel(); // This is the model
    public QuizView getView();
    public void askNextQuestion();
}

I, personally, work to the principle of "code to interface (not implementation)", I've also deliberately gone overboard with the idea to demonstrate the point.
If you look closely, you will note that neither the view or model actually have any relationship to each other. This is all controlled via, the controller
One of the things I've done here is to provide the controller with a askNextQuestion, because the controller doesn't know when that should occur (you might think about using the userDidChangeAnswer, but that would mean that the user only gets a single attempt to answer the question, kind of mean)
The implementation
Now, normally, I like to have some abstract implementations laying around to fill out the "common" functionality, I've forgone that for the most part and gone directly to the default implementation, this done mostly for demonstration purposes.
public class DefaultQuestion implements MutableQuestion {

    private final String prompt;
    private final String correctAnswer;
    private String userAnswer;
    private final String[] options;

    public DefaultQuestion(String prompt, String correctAnswer, String... options) {
        this.prompt = prompt;
        this.correctAnswer = correctAnswer;
        this.options = options;
    }

    @Override
    public String getPrompt() {
        return prompt;
    }

    @Override
    public String getCorrectAnswer() {
        return correctAnswer;
    }

    @Override
    public String getUserAnswer() {
        return userAnswer;
    }

    @Override
    public String[] getOptions() {
        List<String> list = new ArrayList<>(Arrays.asList(options));
        Collections.shuffle(list);
        return list.toArray(new String[list.size()]);
    }

    public void setUserAnswer(String userAnswer) {
        this.userAnswer = userAnswer;
    }

    @Override
    public boolean isCorrect() {
        return getCorrectAnswer().equals(getUserAnswer());
    }

}

public abstract class AbstractQuizModel implements QuizModel {

    private List<QuizModelObserver> observers;

    public AbstractQuizModel() {
        observers = new ArrayList<>(25);
    }

    @Override
    public void addQuizObserver(QuizModelObserver observer) {
        observers.add(observer);
    }

    @Override
    public void removeQuizObserver(QuizModelObserver observer) {
        observers.remove(observer);
    }

    protected void fireDidStartQuiz() {
        for (QuizModelObserver observer : observers) {
            observer.didStartQuiz(this);
        }
    }

    protected void fireDidCompleteQuiz() {
        for (QuizModelObserver observer : observers) {
            observer.didCompleteQuiz(this);
        }
    }

    protected void fireQuestionWasAnswered(Question question) {
        for (QuizModelObserver observer : observers) {
            observer.questionWasAnswered(this, question);
        }
    }

}

public class DefaultQuizModel extends AbstractQuizModel {

    private List<MutableQuestion> questions;
    private Iterator<MutableQuestion> iterator;

    private MutableQuestion currentQuestion;
    private boolean completed;

    private int score;

    public DefaultQuizModel() {
        questions = new ArrayList<>(50);
    }

    public void add(MutableQuestion question) {
        questions.add(question);
    }

    public void remove(MutableQuestion question) {
        questions.remove(question);
    }

    @Override
    public Question getNextQuestion() {
        if (!completed && iterator == null) {
            iterator = questions.iterator();
            fireDidStartQuiz();
        }
        if (iterator.hasNext()) {
            currentQuestion = iterator.next();
        } else {
            completed = true;
            iterator = null;
            currentQuestion = null;
            fireDidCompleteQuiz();
        }
        return currentQuestion;
    }

    @Override
    public Question getCurrentQuestion() {
        return currentQuestion;
    }

    @Override
    public int size() {
        return questions.size();
    }

    @Override
    public int getScore() {
        return score;
    }

    @Override
    public void setUserAnswerFor(Question question, String answer) {
        if (question instanceof MutableQuestion) {
            ((MutableQuestion) question).setUserAnswer(answer);
            if (question.isCorrect()) {
                score++;
            }
            fireQuestionWasAnswered(question);
        }
    }

}

public class DefaultQuizController implements QuizController {

    private QuizModel model;
    private QuizView view;

    public DefaultQuizController(QuizModel model, QuizView view) {
        this.model = model;
        this.view = view;
    }

    @Override
    public QuizModel getModel() {
        return model;
    }

    @Override
    public QuizView getView() {
        return view;
    }

    @Override
    public void askNextQuestion() {
        Question question = getModel().getCurrentQuestion();
        if (question != null) {
            String answer = getView().getUserAnswer();
            getModel().setUserAnswerFor(question, answer);
        }
        question = getModel().getNextQuestion();
        getView().setQuestion(question);
    }

}

public class DefaultQuizViewPane extends JPanel implements QuizView {

    private final JLabel question;
    private final JPanel optionsPane;
    private final ButtonGroup bg;

    private final List<JRadioButton> options;
    private String userAnswer;

    private final List<QuizViewObserver> observers;

    private final AnswerActionListener answerActionListener;

    private final GridBagConstraints optionsGbc;

    protected DefaultQuizViewPane() {

        setBorder(new EmptyBorder(4, 4, 4, 4));

        question = new JLabel();
        optionsPane = new JPanel(new GridBagLayout());
        optionsPane.setBorder(new EmptyBorder(4, 4, 4, 4));

        answerActionListener = new AnswerActionListener();

        optionsGbc = new GridBagConstraints();
        optionsGbc.gridwidth = GridBagConstraints.REMAINDER;
        optionsGbc.weightx = 1;
        optionsGbc.anchor = GridBagConstraints.WEST;

        options = new ArrayList<>(25);

        bg = new ButtonGroup();

        observers = new ArrayList<>(25);

        setLayout(new BorderLayout());

        add(question, BorderLayout.NORTH);
        add(optionsPane);

    }

    protected void reset() {
        question.setText(null);
        for (JRadioButton rb : options) {
            rb.removeActionListener(answerActionListener);
            bg.remove(rb);
            optionsPane.remove(rb);
        }
        options.clear();
    }

    @Override
    public void setQuestion(Question question) {
        reset();
        if (question != null) {
            this.question.setText(question.getPrompt());

            for (String option : question.getOptions()) {
                JRadioButton rb = makeRadioButtonFor(option);
                options.add(rb);
                optionsPane.add(rb, optionsGbc);
            }
            optionsPane.revalidate();
            revalidate();
            repaint();
        }
    }

    @Override
    public void addQuizObserver(QuizViewObserver observer) {
        observers.add(observer);
    }

    @Override
    public void removeQuizObserver(QuizViewObserver observer) {
        observers.remove(observer);
    }

    protected void fireUserDidChangeAnswer() {
        for (QuizViewObserver observer : observers) {
            observer.userDidChangeAnswer(this);
        }
    }

    protected JRadioButton makeRadioButtonFor(String option) {
        JRadioButton btn = new JRadioButton(option);
        btn.addActionListener(answerActionListener);
        bg.add(btn);

        return btn;
    }

    @Override
    public boolean hasAnswer() {
        return userAnswer != null;
    }

    @Override
    public String getUserAnswer() {
        return userAnswer;
    }

    @Override
    public JComponent getViewComponent() {
        return this;
    }

    protected class AnswerActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            userAnswer = e.getActionCommand();
            fireUserDidChangeAnswer();
        }

    }

}

Really nothing fancy here.  About the only thing of significant interest here is how the controller is managing the events between the model and the view
The Navigation API
The navigation API is pretty basic. It allows you to control if the user can actually navigate to the next or previous element (if the actions should be made available to the user) as well as disable either of the actions at any time
(Again, I've focused on a simple design, realistically, it would be nice to have some control over modifying the state of the model to change in which directions the navigation can work, but I've left this out on purpose to keep it simple)
The Contracts (interfaces)
public enum NavigationDirection {
    NEXT, PREVIOUS;
}

public interface NavigationModel {
    public boolean canNavigate(NavigationDirection direction);

    public void addObserver(NavigationModelObserver observer);
    public void removeObserver(NavigationModelObserver observer);

    public void next();
    public void previous();

}

public interface NavigationModelObserver {
    public void next(NavigationModel view);
    public void previous(NavigationModel view);
}

public interface NavigationController {
    public NavigationView getView();
    public NavigationModel getModel();

    public void setDirectionEnabled(NavigationDirection navigationDirection, boolean b);
}

public interface NavigationView extends View {

    public void setNavigatable(NavigationDirection direction, boolean navigtable);
    public void setDirectionEnabled(NavigationDirection direction, boolean enabled);

    public void addObserver(NavigationViewObserver observer);
    public void removeObserver(NavigationViewObserver observer);
}

public interface NavigationViewObserver {
    public void next(NavigationView view);
    public void previous(NavigationView view);
}

The implementation
public static class DefaultNavigationModel implements NavigationModel {

    private Set<NavigationDirection> navigatableDirections;
    private List<NavigationModelObserver> observers;

    public DefaultNavigationModel() {
        this(true, true);
    }

    public DefaultNavigationModel(boolean canNavigateNext, boolean canNavigatePrevious) {
        navigatableDirections = new HashSet<>(2);
        observers = new ArrayList<>(25);
        setCanNavigate(NavigationDirection.NEXT, canNavigateNext);
        setCanNavigate(NavigationDirection.PREVIOUS, canNavigatePrevious);
    }

    public void setCanNavigate(NavigationDirection direction, boolean canNavigate) {
        if (canNavigate) {
            navigatableDirections.add(direction);
        } else {
            navigatableDirections.remove(direction);
        }
    }

    @Override
    public boolean canNavigate(NavigationDirection direction) {
        return navigatableDirections.contains(direction);
    }

    @Override
    public void addObserver(NavigationModelObserver observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(NavigationModelObserver observer) {
        observers.remove(observer);
    }

    protected   void fireMoveNext() {
        for (NavigationModelObserver observer : observers) {
            observer.next(this);
        }
    }

    protected   void fireMovePrevious() {
        for (NavigationModelObserver observer : observers) {
            observer.previous(this);
        }
    }

    @Override
    public void next() {
        fireMoveNext();
    }

    @Override
    public void previous() {
        fireMovePrevious();
    }

}

public static class DefaultNavigationController implements NavigationController {

    private final NavigationModel model;
    private final NavigationView view;

    public DefaultNavigationController(NavigationModel model, NavigationView view) {
        this.model = model;
        this.view = view;

        view.setNavigatable(NavigationDirection.NEXT, model.canNavigate(NavigationDirection.NEXT));
        view.setNavigatable(NavigationDirection.PREVIOUS, model.canNavigate(NavigationDirection.PREVIOUS));

        view.addObserver(new NavigationViewObserver() {
            @Override
            public void next(NavigationView view) {
                if (getModel().canNavigate(NavigationDirection.NEXT)) {
                    getModel().next();
                }
            }

            @Override
            public void previous(NavigationView view) {
                if (getModel().canNavigate(NavigationDirection.PREVIOUS)) {
                    getModel().previous();
                }
            }
        });
    }

    @Override
    public NavigationView getView() {
        return view;
    }

    @Override
    public NavigationModel getModel() {
        return model;
    }

    @Override
    public void setDirectionEnabled(NavigationDirection navigationDirection, boolean enabled) {
        getView().setDirectionEnabled(navigationDirection, enabled);
    }

}

public static class DefaultNavigationViewPane extends JPanel implements NavigationView {

    private final List<NavigationViewObserver> observers;

    private final JButton btnNext;
    private final JButton btnPrevious;

    public DefaultNavigationViewPane() {
        btnNext = new JButton("Next >");
        btnNext.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fireMoveNext();
            }
        });
        btnPrevious = new JButton("< Previous");
        btnPrevious.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fireMovePrevious();
            }
        });
        setLayout(new FlowLayout(FlowLayout.RIGHT));

        add(btnPrevious);
        add(btnNext);

        observers = new ArrayList<>();
    }

    @Override
    public void addObserver(NavigationViewObserver observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(NavigationViewObserver observer) {
        observers.remove(observer);
    }

    protected void fireMoveNext() {
        for (NavigationViewObserver observer : observers) {
            observer.next(this);
        }
    }

    protected void fireMovePrevious() {
        for (NavigationViewObserver observer : observers) {
            observer.previous(this);
        }
    }

    @Override
    public JComponent getViewComponent() {
        return this;
    }

    @Override
    public void setNavigatable(NavigationDirection direction, boolean navigtable) {
        switch (direction) {
            case NEXT:
                btnNext.setVisible(navigtable);
                break;
            case PREVIOUS:
                btnPrevious.setVisible(navigtable);
                break;
        }
    }

    @Override
    public void setDirectionEnabled(NavigationDirection direction, boolean enabled) {
        switch (direction) {
            case NEXT:
                btnNext.setEnabled(enabled);
                break;
            case PREVIOUS:
                btnPrevious.setEnabled(enabled);
                break;
        }
    }

}

The Quiz Master
Now, these are two distinct APIs, they have nothing in common, so, we need some kind of controller to bridge them
The contracts (the interfaces)
public interface QuizMasterController {
    public QuizController getQuizController();
    public NavigationController getNavigationController();
    public QuizMasterView getView();
}

public interface QuizMasterView extends View {
    public NavigationController getNavigationController();
    public QuizController getQuizController();
    public void showScoreView(int score, int size);
    public void showQuestionAndAnswerView();
}

Okay, so you're probably asking yourself the obvious question, where's the model?  Well, it doesn't need one, it's just a bridge between the navigation and quiz APIs, it doesn't manage any data of it's own...
The implementations
public class DefaultQuizMasterController implements QuizMasterController {

    private QuizController quizController;
    private NavigationController navController;

    private QuizMasterView view;

    public DefaultQuizMasterController(QuizController quizController, NavigationController navController) {
        this.quizController = quizController;
        this.navController = navController;

        view = new DefaultQuizMasterViewPane(quizController, navController);

        // Setup the initial state
        quizController.askNextQuestion();

        navController.getModel().addObserver(new NavigationModelObserver() {
            @Override
            public void next(NavigationModel view) {
                getQuizController().askNextQuestion();
                getNavigationController().setDirectionEnabled(NavigationDirection.NEXT, false);
            }

            @Override
            public void previous(NavigationModel view) {
                // NOOP
            }
        });

        quizController.getView().addQuizObserver(new QuizViewObserver() {
            @Override
            public void userDidChangeAnswer(WizeQuiz.QuizView view) {
                getNavigationController().setDirectionEnabled(NavigationDirection.NEXT, true);
            }
        });

        quizController.getModel().addQuizObserver(new QuizModelObserver() {
            @Override
            public void didStartQuiz(QuizModel quiz) {
                getView().showQuestionAndAnswerView();
            }

            @Override
            public void didCompleteQuiz(QuizModel quiz) {
                getView().showScoreView(quiz.getScore(), quiz.size());
                getNavigationController().setDirectionEnabled(NavigationDirection.NEXT, false);
            }

            @Override
            public void questionWasAnswered(QuizModel model, Question question) {
            }
        });

        navController.setDirectionEnabled(NavigationDirection.NEXT, false);
    }

    @Override
    public QuizController getQuizController() {
        return quizController;
    }

    @Override
    public NavigationController getNavigationController() {
        return navController;
    }

    @Override
    public QuizMasterView getView() {
        return view;
    }

}

public class DefaultQuizMasterViewPane extends JPanel implements QuizMasterView {

    private QuizController quizController;
    private NavigationController navController;

    private QuestionAndAnswerView qaView;
    private ScoreView scoreView;

    private CardLayout cardLayout;

    public DefaultQuizMasterViewPane(QuizController quizController, NavigationController navController) {
        this.quizController = quizController;
        this.navController = navController;

        quizController.getModel().addQuizObserver(new QuizModelObserver() {
            @Override
            public void didStartQuiz(QuizModel quiz) {
            }

            @Override
            public void didCompleteQuiz(QuizModel quiz) {
            }

            @Override
            public void questionWasAnswered(QuizModel model, Question question) {
                qaView.updateScore();
            }
        });

        scoreView = new ScoreView();
        qaView = new QuestionAndAnswerView();

        qaView.updateScore();

        cardLayout = new CardLayout();
        setLayout(cardLayout);

        add(qaView, "view.qa");
        add(scoreView, "view.score");
    }

    @Override
    public JComponent getViewComponent() {
        return this;
    }

    @Override
    public NavigationController getNavigationController() {
        return navController;
    }

    @Override
    public QuizController getQuizController() {
        return quizController;
    }

    @Override
    public void showScoreView(int score, int size) {
        scoreView.updateScore();
        cardLayout.show(this, "view.score");
    }

    @Override
    public void showQuestionAndAnswerView() {
        cardLayout.show(this, "view.qa");
    }

    protected class QuestionAndAnswerView extends JPanel {

        private JLabel score;

        public QuestionAndAnswerView() {

            setLayout(new BorderLayout());

            add(getQuizController().getView().getViewComponent());

            JPanel south = new JPanel(new BorderLayout());
            south.add(getNavigationController().getView().getViewComponent(), BorderLayout.SOUTH);

            score = new JLabel();
            score.setHorizontalAlignment(JLabel.RIGHT);
            south.add(score, BorderLayout.NORTH);

            add(south, BorderLayout.SOUTH);
        }

        protected void updateScore() {
            score.setText(getQuizController().getModel().getScore() + "/" + getQuizController().getModel().size());
        }

    }

    protected class ScoreView extends JPanel {

        private JLabel score;

        public ScoreView() {

            setLayout(new GridBagLayout());
            score = new JLabel("You scored:");
            add(score);

        }

        protected void updateScore() {
            score.setText("You scored: " + getQuizController().getModel().getScore() + "/" + getQuizController().getModel().size());
        }

    }
}

Now, the implementation is interesting, it actually has two "states" or "views", the "question and answer" view and the "score view".  This, again, is deliberate, because I really didn't want ANOTHER MVC.  The Q&A view is already managing two MVCs any way :P
Basically, what this does is monitors the quiz API for when the user changes the answer to a question, it then tells the navigation API that it can move to the next question.  It monitors the start and completed events as well, presenting the required view for those states.
It is also monitoring the navigation API for navigation events.  In this example, we can only move in a single direction and even if the navigation API was configured to do otherwise, the quiz API does not provide that functionality
Put it together
Now, I've chosen to deliberately build each section separately, conceivably, you could have the QuizMasterController build the Navigation API itself, as it knows that the quiz API only allows for forward navigation, equally we could change the navigation API to allow those states to be modified via the model or the model changed, these are all viable solutions, I've just gone for a direct example.
NavigationModel navigationModel = new DefaultNavigationModel(true, false);
NavigationView navigationView = new DefaultNavigationViewPane();
NavigationController navigationController = new NavWiz.DefaultNavigationController(navigationModel, navigationView);

DefaultQuizModel quizModel = new DefaultQuizModel();
quizModel.add(new DefaultQuestion(
                "Which pop duo was the first western band to play in The Peoples Republic of China?",
                "Wham",
                "Wham", "Simon and Garfunkel", "Chas and Dave", "Right Said Fred"));
quizModel.add(new DefaultQuestion(
                "Timber selected from how many fully grown oak trees were needed to build a large 3 decker Royal Navy battle ship in the 18th century?",
                "3,500",
                "50", "500", "1,500", "3,500"));
quizModel.add(new DefaultQuestion(
                "Speed skating originated in which country?",
                "Netherlands",
                "Russia", "Netherlands", "Canada", "Norway"));
quizModel.add(new DefaultQuestion(
                "Off the coast of which country did the Amoco Cadiz sink?",
                "France",
                "South Africa", "France", "USA", "Spain"));
quizModel.add(new DefaultQuestion(
                "The song 'An Englishman in New York' was about which man?",
                "Quentin Crisp",
                "Quentin Crisp", "Sting", "John Lennon", "Gordon Sumner"));
QuizView quizView = new DefaultQuizViewPane();
QuizController quizController = new DefaultQuizController(quizModel, quizView);

QuizMasterController quizMasterController = new DefaultQuizMasterController(quizController, navigationController);

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(quizMasterController.getView().getViewComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

And finally we end up with something like...

This is nothing if not rough, but is designed to provide some ideas into how you might accomplish complex, compound MVCs


text:
Q: Extracting combination of multiple columns from pandas dataframe I have the foll. dataframe in pandas:
df

DAY   YEAR    REGION   VALUE
  1   2000     A         12
  2   2000     A         10
  3   2000     A         13
  6   2000     A         15
  1   2001     A         3
  2   2001     A         40
  3   2001     A         83
  4   2001     A         95
  1   2000     B         124
  3   2000     B         102
  5   2000     B         131
  8   2000     B         150
  1   2001     B         30
  5   2001     B         4
  8   2001     B         8
  9   2001     B         12

How can I create a new dataframe which contains unique combinations of YEAR and REGION in result? Result shoul look like this:
YEAR   REGION
2000    A
2001    A
2000    B
2001    B

A: You can sub-select from your df and then call drop_duplicates:
In [16]:
df[['YEAR','REGION']].drop_duplicates()

Out[16]:
    YEAR REGION
0   2000      A
4   2001      A
8   2000      B
12  2001      B


text:
Q: Change Sample Result Save Configuration for Sumary Report with jmeter maven I have a JMX project with a "Sample Result Save Configuration" for "Sumary Report" as reported in the attached picture. And that JMX project is executed with Jmeter Maven plugin.
Now I would handle dynamically the Configuration of report from maven. For example I would unset the option "Save URL" not by Jmeter GUI mode. But I would set it during the execution of project by maven.
How it can be done?
enter image description here
The related XML piece is as follows:
enter image description here


text:
Q: find a file and send some text to it I would like to find a file in folder /opt and send some text to it. I tried the following syntax:
sudo find /opt -name filename-*.conf | xargs -I '{}' echo "text_to_send" > '{}' \;

Unfortunately, after that I find the file named {} which contains the text. I tried using '{}' as well as {},"{}",\{\}, but in the command, but nothing seems to work correctly as a placeholder for the found filename. What is the correct syntax?

A: Try this:
sudo find /opt -name filename-*.conf -exec bash -c 'echo "text_to_send" > {}' \;

The bash -c is necessary in order to put the redirect > in quotes for find -exec.

A: I think > is interpreted in the current shell. The same applies to *, i.e. if you happen to have filename-A.conf (or worse: more matching files) in the current directory then shell globbing will break your command furhter. Also note: your sudo applies to find only, not to xargs.
Try this (with sudo if needed):
find /opt -name 'filename-*.conf' -print0 | xargs -r0 sh -c 'echo "text_to_send" | tee "$0" "$@"' > /dev/null

Warning: tee will overwrite files (like > does, so I guess this is what you want); use tee -a to append.

*

*find -print0 and xargs -0 work even with fancy filenames,

*xargs -r doesn't run if no file is found,

*sh handles the inner pipe,

*$0" "$@" passes all the filenames (postpended by xargs) to the command under sh in a safe way,

*tee handles one or multiple files found,

*the final redirection is to prevent text_to_send from appearing in your terminal.


text:
Q: Entity Framework 6 database first date and time I had a database with few tables. None of the table has date or time datatype column.
Today I created a table in database and tried to update the model and the column with date and time type didn't reflected in my model.
Searched on google and SO, most of them were code first solution.
Can someone please tell me or give me any link which will explain the reason and solution.
I cannot use that column if that is not pulled to the model.
Tried with renaming the column name as well but no luck but when changed the type it is reflecting in the model.


text:
Q: how to keep DRY when moving from ASMX Web Services to WCF Using .NET Framework 3.5 C#, I am in the process of moving from SOAP-based Web Services to JSON-based WCF Services. All my web services derive from a common ServiceBase class with common functionality like session validation, client authentication, database connection, logging etc. and in all my web service method I call a common method on the base class using a single line of code to perform the common tasks
base.InitCallThread()

Q1: What is the best way to do the same or similar in WCF in order to avoid having to write hundreds of lines of repetitive code?
Q2: If I was to support the same interfaces with both SOAP-based Web Services and JSON-based WCF services in parallel, what would be the best way to share the same common functionality? I guess it is possible to share the http session b/w the two?

A: You should refactor your base class code into a separate class. Call that separate class from the base class in your ASMX services; in the WCF service, call it from each individual service, or use one of the WCF extensibility mechanisms to call it centrally.
WCF permits the same service to be exposed on multiple endpoints with different bindings. You can expose the same WCF service with basicHttpBinding for SOAP, at the same time as exposing a webHttpBinding for the JSON.

A: Q1: You can derive from the same ServiceBase class with common functionality as you had before. WCF does not limit you in this matter. It requires only implementing some interface
Q2: You can define multiple bindings through web.config (or programmatic) configuration.


text:
Q: Dynamically added elements for screen-reader : aria-live Vs role-alert I have an application where elements are added to the page dynamically and I want screen readers to read them for different versions of browsers ( IE 8/9/10, FF and Chrome).
What's the difference between the following two: adding a 'role=alert' attribute Vs 'aria-live=assertive'?
$("
Sample message.
").appendTo($existingElement);

$("
Sample message.
").appendTo($existingElement);

A: By default, role='alert' inherits aria-atomic and aria-live with an assertive value, so should behave similarly from a user's perspective. However, not all user agents implement specifications in the same way.
The w3c recommends that you use an appropriate role when available, in preference to a generic aria-live region. This comes with the caveat that user agents have historically shown inconsistent behaviors between the two.
Testing against HTML5 Accessibility's alert test page demonstrates that ChromeVox 1.27.0 supports the technique you showed, while VoiceOver on OS X 10.8.4 with Safari does not.


text:
Q: How do I vertically align a form using bootstrap? I'm trying to make a login page using Bootstrap. So far so good, the problem is the vertical align. I want to make the login form stick to the center of the page, so I tryed reading all the other answered questions and tryed really a lot of different solutions, but to no avail. My code is the following.

.container {
  display: table;
  table-layout: fixed;
}

.form-horizontal {
  width: 500px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link href="site_index.css" type="text/css" rel="stylesheet">

    <form class="form-horizontal">

        Username

          <input type="email" class="form-control" id="username" placeholder="username" size="16">

        Password

          <input type="password" class="form-control" id="password" placeholder="password" size="16">

          <button type="submit" class="btn btn-primary btn-lg btn-block" id="signin_button" value="Sign In">Sign in</button>

    </form>

      Results and page (C) Copyright NerdLuv Inc.

A: It's kind of hack, but I will try to figure how I can place it exactly in the center.
Just tried to wrap the box(.centerit) and move it's location.

.container {
  display: table;
  table-layout: fixed;
}

.form-horizontal {
  width: 500px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

#outer{
  height:800px;
  border:2px solid orange;
}

.centerit{
  border:3px solid purple;
  top:30%;
  position:relative;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <form class="form-horizontal">

      Username

        <input type="email" class="form-control" id="username" placeholder="username" size="16">

      Password

        <input type="password" class="form-control" id="password" placeholder="password" size="16">

        <button type="submit" class="btn btn-primary btn-lg btn-block" id="signin_button" value="Sign In">Sign in</button>

  </form>

    Results and page (C) Copyright NerdLuv Inc.


text:
Q: Missing Layout and Data Frame Buttons in ArcGIS Desktop I have lost the Layout and Data Frame Buttons at the bottom of my map window in ArcGIS Desktop 10.3.1. How can I get them back?

A: Turns out, this is a really simple fix and I found the answer on GeoNet.
In the View menu, select Scroll Bars.

In addition to turning on scroll bars, this turns on the Layout, Data Frame, Refresh and Pause buttons.


text:
Q: why with click on one label tag, two label tags selected? I have a label tag with display equal block. when I click on one label tag, two label tag would show on console.
jQuery Code:
var lbl = $("label")
lbl.on("click", function(e) {
  e.preventDefault();
  var target = $(this);
  console.log(target);
})

HTML Code:

  <input type="checkbox">

  تک

A: That's because of checkbox change event is also fired at the same time, you should prevent default action as well.
The click event is first handled by the label and is then passed on to the checkbox.
However while this prevents event bubbling it also has the undesirable side effect of preventing the checkbox from changing state. So you'll need to prevent default action as well.
lbl.on("click", function(e) {
  //e.stopPropagation(); // you don't need this by the way
  e.preventDefault(); //try adding this
  var target = $(this);
  console.log(target);
})


text:
Q: Size of bit field compared to a char So I know that
struct bit
{
    unsigned char a : 1;
}

will still take up a byte because of padding, my question is this:
struct bit
{
    unsigned char a : 1;
    ...
    unsigned char h : 1;
}

Will this struct take up the same size as a char? And if so, am I better off just using a char instead? I'm asking because I want to use bits as a key, but I'd rather avoid bitwise operations if possible.

A: There is no guarantees of anything when using bit-fields. That struct can have any size and any bit order. In fact unsigned char type for bit-fields is not even supported by the standard! Your code is already relying on non-standard extensions.
Forget about bit-fields, forget about char. You should use uint8_t and bitwise operators if you want predictable, portable code.


text:
Q: Prove that the normalizer of the subgroup is the subgroup is itself
Problem: $P$ is a $p$-Sylow subgroup of $G$. $P \subseteq N_G(P) \subseteq H \subseteq G$. $H$ is a subgroup of $G$. Prove that $N_G(H)=H$ , i.e., Normalizer of $H$ in $G$ is $H$ itself.

$H$ and $G$ will have the same Sylow groups for this given prime p.  I observed a few things like the number of p-Sylow groups not contained in $H$ is a multiple of p and so is the number of p-Sylow groups not contained in $N_H(P)$. I couldn't make much progress. Please help.

A: Let $y\in N_G(H)\implies yHy^{-1}=H\implies yPy^{-1}\subset yHy^{-1}=H\implies P $  and $yPy^{-1}$ are both Sylow-$p$ subgroups of $H$,since any two Sylow $p-$ groups are conjugates hence $ P $  and $yPy^{-1}$  are conjugates in $H$.
Hence $P=x(yPy^{-1})x^{-1}$ for some $x\in H$
$\implies P=(xy)P(xy)^{-1}\implies xy\in N_G(P)\subset H$
Hence $x^{-1}(xy)=y\in H$ as a $H$ is a subgroup [$a,b\in H\implies ab^{-1}\in H$]

A: It's an instance of the so-called Frattini argument:

Let $M$ be a group acting on the set $\Omega$. Suppose the subgroup $H$ acts transitively on $\Omega$. Then for each $\alpha \in \Omega$ we have $M = M_{\alpha} H$.

The proof is immediate: for each $g \in M$ there is $h \in H$ such that $(\alpha^ {g})^{h} = \alpha$, so that $g h \in G_{\alpha}$.
In your case, $\Omega$ is the set of $p$-Sylow subgroups of $M = N_{G}(H)$. Since $P \le H$, and $H \trianglelefteq N_{G}(H)$, by the Sylow theorems $\Omega \subseteq H$ and $H$ acts transitively on $\Omega$.
Now $M_{P} = N_{G}(P)$, so that $M = N_{G}(H) = N_{G}(P) H = H$.


text:
Q: python pandas organizing multidimensional data into an object Having historical data from a stock exchange, with a number of stocks, and a number of a given stock's attributes (open, high, low, close, volume), I end up effectively having 3 dimensions in my data, i.e., time stamp, stock's ticker and the attributes. For a single stock (2D), I'd create one pd.DataFrame, but how should I go (efficiently and generically) about putting such data for many stocks into a single object? Is pd.DataFrame with multi-indexing the best possible solution?

A: I recommend you use a Panel, for example:
>>> from pandas.io.data import DataReader
>>> from pandas import Panel, DataFrame

>>> symbols = ['AAPL', 'GLD', 'SPX', 'MCD']
>>> data = dict((symbol, DataReader(symbol, "yahoo", pause=1)) for symbol in symbols)
>>> panel = Panel(data).swapaxes('items', 'minor')
>>> closing = panel['Close'].dropna()
>>> closing.head()

             AAPL    GLD     MCD     SPX
Date
2010-01-04   214.01  109.80  62.78   1132.99
2010-01-05   214.38  109.70  62.30   1136.52
2010-01-06   210.97  111.51  61.45   1137.14
2010-01-07   210.58  110.82  61.90   1141.69
2010-01-08   211.98  111.37  61.84   1144.98

If you want to see more take a look at this example I made for a course.


text:
Q: Error deleting project in TFS I created a "Test" project that I want to delete, using the following command:
TfsDeleteProject /server:xyz\sqlserver2008 "Test"
Getting this error:
TF30076: The server name or Uniform Resource Identifier (URI) you typed,
xyz\sqlserver2008, cannot be
resolved to a Team Foundation server.
If you type a server name, it must match the name you typed in the
Add Team Foundation Server dialog.  If you type a URI, it must use
the following syntax: http[s]://:
The server instance is valid. (The installation of TFS is app tier and db are on seperate boxes) What might be going on ?
xyz is eht server name, sqlserver2008 is the db instance. For eg. I access the db using sql server management studio client app using xyz\sqlserver2008 as dbname.

A: Specify the full server URI including the http:// and :port. Also look for these error numbers in the MSDN.
Edit: Follow the first link, Andrew posted that's where I got my info from :)


text:
Q: FFT number of input samples I am wondering if I use 10000 samples and do the fft, my results would be much different comparing to when I have exactly the samples equal to n power of 2 or it just affects the speed of doing fft ?
is Matlab doing the zero padding automatically ?
or I should do zero padding ?
further information :
I am using matlab version 2012b, fft function to perform the dft on my samples. I have the time domain data for 10 minutes with sampling rate of 50 KHz. type of my work necessitates me to devide the time domain data in 200 ms windows. and after performing the fft on these 200 ms windows, I make an average over the different window results. 200 ms in 50 Hz frequency system which is sampled by 50Khz means about 10000 samples for each fft operation.
regards, Ali

A: The original Cooley-Tukey form of the FFT was limited to powers of 2. A lot of people are still stuck in that mindset.  Even professors still perpetuate the myth that FFTs need to be 2^K to be fast. The truth is that modern FFT libraries use a mixed radix approach. It allows fast transforms for a size that is an aggregate of small primes.  Usually a number that factorizes over {2,3,5} is quite fast.  If not, zero pad to the next number that is an aggregate of small primes, but not (necessarily) a power of 2.
As an aside, there are tricks that can technically achieve O(n log n) scalability with large primes,  such as Chirp-Z and Rader's Prime algorithm , but they usually have a very large constant in front of them and should be avoided if possible.
Bottom line: Your size 10000 factorizes nicely over {2,3,5}, so it will be fast with most modern FFT implementations (even kissfft ).  When in doubt, benchmark!

A: Matlab's fft is based on the fftw library which compute the result in O(n*log(n)) operations for any n (see http://www.fftw.org/fftw-paper-ieee.pdf), hence you won't obtain a gain in speed by zero padding your data.
Matlab's doesn't do the zero padding automatically, it's up to you to do it or not. Zero padding in the time domain is equivalent to interpolate your data in the frequency domain (see https://dsp.stackexchange.com/a/745/10782).


text:
Q: Copy a System.Drawing.Bitmap into a region of WriteableBitmap I'm currently having some problems in integrating a System.Drawing.Bitmap into a WPF WriteableBitmap.
I want to copy from the Bitmap to position (X,Y) of the WriteableBitmap.
The following code shows how I've tried to do this.
BitmapData Data = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
WriteableBitmap.Lock();

//CopyMemory(WriteableBitmap.BackBuffer, Data.Scan0,  ImageBufferSize);

Int32Rect Rect = new Int32Rect(X, Y, Bitmap.Width, Bitmap.Height);
WriteableBitmap.AddDirtyRect(Rect);
Bitmap.UnlockBits(Data);
Bitmap.Dispose();`

Thanks a lot,
Neokript

A: Use WritableBitmap.WritePixels. This will prevent using unmanaged code.
BitmapData Data = Bitmap.LockBits(new Rectangle(0, 0, Bitmap.Width, Bitmap.Height),
    ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

try
{
    WritableBitmap.WritePixels(
        new Int32Rect(0,0,Bitmap.Width, Bitmap.Height),
        Data.Scan0,
        Data.Stride,
        X, Y);
}
finally
{
    Bitmap.UnlockBits(Data);
}

Bitmap.Dispose();

A: You should lock both BitmapData and WriteableBitmap. If you want to draw the image to a specific (x,y) location, then you should also manage the remaining width and height of image for drawing.
[DllImport("kernel32.dll",EntryPoint ="RtlMoveMemory")]
public static extern void CopyMemory(IntPtr dest, IntPtr source,int Length);

public void DrawImage(Bitmap bitmap)
{
    BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    try
    {
        writeableBitmap.Lock();
        CopyMemory(writeableBitmap.BackBuffer, data.Scan0,
            (writeableBitmap.BackBufferStride * bitmap.Height));
        writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, bitmap.Width, bitmap.Height));
        writeableBitmap.Unlock();
    }
    finally
    {
        bitmap.UnlockBits(data);
        bitmap.Dispose();
    }
}

And in your code:
Bitmap bitmap = new Bitmap("pic.jpg"); // obtain it from anywhere, memory, file, stream ,...

writeableBitmap = new WriteableBitmap(
                        bitmap.Width,
                        bitmap.Height,
                        96,
                        96,
                        PixelFormats.Pbgra32,
                        null);

imageBox.Source = writeableBitmap;

DrawImage(bitmap);

I have managed to render a 1080P clip with 29 fps using this method.


text: Q: google.com crawl errors to non-existent urls Google webmasters tools has a bunch crawl errors (404) for urls to non-existent pages on my site. I never link to these  urls. How can I solve this problem ... it is affecting my adwords campaign? I tried to do a 302 redirect, but that did not work.


text:
Q: CSS animation hover effect I'm looking for some help with a CSS hover effect.
I have a border effect at the bottom of the div horizontal on hover.
How do I set it to working vertical right side of div when hover?

A: You should apply the effect on hover on the right border and in the meantime remove the effect on the bottom, like in the example below:
div:hover {border-right: 1px solid red; border-bottom-style: none;}


text:
Q: rust: error: lifetime of non-lvalue is too short to guarantee its contents can be safely reborrowed I can't figure out what does this error in Rust mean:
error: lifetime of non-lvalue is too short to guarantee its contents can be safely reborrowed

What's a non-lvalue? (I suspect is not a right value).
I want to understand what the errror means and to be able to modify "objects" from a vector of mutable references.
This is a minimum test case to produce the error. I insert in a vector a mutable reference to a struct, and then I try to modify the pointed struct.
struct Point {
    x: uint,
    y: uint
}

fn main() {
    let mut p = Point { x: 0, y: 0};
    p.x += 1; // OK, p owns the point

    let mut v: Vec<&mut Point> = Vec::new();
    v.push(&mut p);

    // p.x += 1 // FAIL (expected), v has borrowed the point

    let p1:&mut Point = *v.get_mut(0);  // ERROR, lifetime of non-lvalue...

    // never reached this line
    // p1.x += 1;
}

A: Let's go over what you're trying to do here:
let p1:&mut Point = *v.get_mut(0);
*v.get_mut(0) returns a mutable reference to first the mutable reference in the vector, then dereferences it. If this compiled, you would end up with two mutable references to the same object: one in the vector, the other in the p1 variable. Rust is rejecting this because it's not safe.
By far the best solution is to make the vector the owner of your Point objects. ie. use a Vec<Point> instead of a Vec<&mut Point.
If you need something more complicated, you can use a RefCell for dynamically checked borrowing:
use std::cell::RefCell;

struct Point {
    x: uint,
    y: uint
}

fn main() {
    let p = RefCell::new(Point { x: 0, y: 0});

    p.borrow_mut().x += 1;

    let mut v: Vec<&RefCell<Point>> = Vec::new();

    v.push(&p);

    let p1 = v.get(0);

    p1.borrow_mut().x += 1;

    p.borrow_mut().x += 1;
}


text:
Q: How to find $\sum_{i=1}^{\infty} 0.5^i \cdot i^2$? I know how to solve how to find $\sum_{i=1}^{\infty} 0.5^i \cdot i$ using
$$
 \sum_{i=1}^{\infty} 0.5^i \cdot i = 0.5 + 0.5^2*2 + 0.5^3*3 + 0.5^4*4 + \ldots \\
    = (0.5 + 0.5^2 + 0.5^3 + 0.5^4 + \ldots) + (0.5^2 + 0.5^3 + \ldots ) + (0.5^3 + \ldots ) + \ldots \\
    = 1 + 0.5 + 0.25 + \ldots = 2
$$
I'm trying to apply the analogous approach for $\sum_{i=1}^{\infty} 0.5^i \cdot i^2$?
I end up with something that looks like
$$
\sum_{i=1}^{\infty} 0.5^i\cdot i^2 =
    = 0.5 + 0.5^2*2^2 + 0.5^3*3^2 + 0.5^4*4^2 + \ldots \\
    = (0.5 + 0.5^2 + 0.5^3 + 0.5^4 + \ldots) + 3(0.5^2 + 0.5^3 + \ldots ) + 5(0.5^3 + \ldots ) + \ldots \\
    = 1 + 3 \cdot \frac{1}{2} + 5\cdot \frac{1}{4} + 7 \cdot \frac{1}{8} + 9 \cdot \frac{1}{16} + \ldots  \\
    = (1 + 0.5 + 0.25 + 0.125 + \ldots) + 2(0.5 + 0.125 + \ldots ) + 2*(0.25 + 0.125 + \ldots) + 2*(0.125 + \ldots) \\
    = 2 + 2 * 1 + 2 * 0.5 + 2 * 0.25 + 2 * 0.125 + \ldots
    = 2 + 2(1 + 0.5 + 0.25 + \ldots) \\
    = 6
$$
This was a bit convoluted and I was wondering if there's a simpler way to arrive at this after having the result for $\sum 0.5^i \cdot i$?


text:
Q: Lebesgue Integrability of $\left(\frac{1}{x}\right) \sin\left(\frac{1}{x}\right)$ Given $f:\mathbb{R}\rightarrow \mathbb{R}$ defined by $f(0)=0$ and $f(x)=\left(\frac{1}{x}\right) \sin\left(\frac{1}{x}\right)$ for $x\in \mathbb{R}-\{0\}$, can someone please give me a rigorous proof explaining whether or not $f$ is Lebesgue integrable on $\mathbb{R}$? There is no problem at large values of $x$, but I am not able to write down clearly the behavior near the origin.

A: For positive integer $n$, using the change of variables $t = 1/x$, $$\int_{1/(\pi(n+1))}^{1/(\pi n)} |f(x)|\; dx = \int_{n\pi}^{(n+1)\pi} \dfrac{|\sin(t)|}{t}\; dt \ge \dfrac{1}{(n+1)\pi} \int_{n\pi}^{(n+1)\pi} |\sin(t)|\; dt = \dfrac{2}{(n+1)\pi}$$
Sum this over positive integers $n$.

A: The Lebesgue integrability of $\frac{1}{x}\sin\frac{1}{x}$ in a right neighbourhood of zero would imply the Lebesgue integrability of $\frac{\sin z}{z}$ over some interval of the form $(a>0,+\infty)$ by the change of variable $z=\frac{1}{x}$. However, $\frac{\sin x}{x}$ is not a Lebesgue integrable function over $(a>0,+\infty)$, despite it being an improperly Riemann integrable function over such set:
$$ g(b)=\int_{a}^{b}\left|\frac{\sin x}{x}\right|\,dx $$
grows like $\frac{2}{\pi}\log\left(\frac{b}{a}\right)$, that is unbounded.


text:
Q: Kubernetes deploy tomcat probleme about liveness and readiness I try to deploy my tomcat on kubernetes but when I run : kubectl create -f deploy-tomcat.yaml I have always the same error :
error from server (need to declare liveness (found 0), need to declare readiness (found 0)

deploy-tomcat.yaml :
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tomcat-deployment
  labels:
    app: tomcat
spec:
  replicas: 1
  selector:
    matchLabels:
      app: tomcat
  template:
    metadata:
      labels:
        app: tomcat
    spec:
      containers:
      - name: tomcat
        image: tomcat-image
        ports:
        - containerPort: 8080

A: I suggest you add a liveness and readinessProbe to your manifest (on containers level), e.g.:
  readinessProbe:
    tcpSocket:
      port: 8080
  livenessProbe:
    tcpSocket:
      port: 8080

Please note, that this is not K8s default behavior to enforce the existence of those probes. I assume it was added to your K8s cluster with a validating admission webhook.


text:
Q: azure clone bug workaround Working on CD pipe line for our web applications on Azure,
Im trying to create a deploy slot with a copy of the production site .
I tried to work with Clone in powershell with this article  :
https://learn.microsoft.com/en-us/azure/app-service/app-service-web-app-cloning
$srcapps = Get-AzureRmWebApp -ResourceGroupName $ResourceGroupname -Name $webappname

$destapp = New-AzureRmWebAppSlot -ResourceGroupName $ResourceGroupname -Name $webappname -Slot SLOTNAME -SourceWebApp $srcapps

But when i execute it i get error:
New-AzureRmWebAppSlot : Parameter ServerFarmId is null or empty.
Googling this error got me to this :
https://github.com/Azure/azure-powershell/issues/3633
Saying :

Attempting to use output object from Get-AzureRmWebApp to direct
  Get-AzureRmWebAppSlot fails due to a typing issue, although both types
  appear to be identical.

Describing exactly my situation
Am i missing something ?
Did any one found a work around for it ?
Any other approaches to create a deploy slot with a copy of the production site ?
thanks !

A: In your command, you should add -AppServicePlan <your plan>.
But I test in my lab, it seems it is possible for you to do this, I suggest you should clone your app firstly, then use  cloned app to create a slot.


text:
Q: How to save the file with different name and not overwriting existing one I need to run a python script repeatedly over different data set. This python script test.py processes the data set, plot and save the result using the command.
plt.savefig('result.png')

How can I ensure that when the same test.py scripts runs on another data set.. the new result.png doesn't overwrite my previous result? Basically before executing plt.savefig('result.png'), I need to check if result.png already exist and if does then rename the result to any other name like
result1.png
result2.png

Otherwise, in the next post processing the file is overwritten.

A: You can use os.path.exists to check whether the file already exists, and if so, append a number. Repeat with the new file name until you find one that does not yet exist.
def unique_file(basename, ext):
    actualname = "%s.%s" % (basename, ext)
    c = itertools.count()
    while os.path.exists(actualname):
        actualname = "%s (%d).%s" % (basename, next(c), ext)
    return actualname

Example-usage:
for i in range(5):
    with open(unique_file("foo", "txt"), "w") as f:
        f.write(str(i))

A: import time
if os.path.exists('result.png'):
    plt.savefig('result_{}.png'.format(int(time.time())))
else:
    plt.savefig('result.png')

A: You can use tempfile.mkstemp available in the standard library
import tempfile
fi, filename = tempfile.mkstemp(prefix='result_', suffix='.png')

Note: fi is an integer. In case you need a file object do
f = os.fdopen(fi, "w")

whereas filename includes the absolute pathname of the created file, e.g.
'/tmp/result_d_3787js.png'

Another solution is to use UUIDs, e.g.
import uuid
filename = 'result_'+str(uuid.uuid4())+'.png'

which produces something like
result_cf29d123-271e-4899-b2f6-d172f157af65.png

Please see the official docs for further info and parameters
on mkstemp and uuid


text:
Q: How do you find table intersections in PostgREST clients? Simple question from a rookie to PostgREST - is there an intersect function for the equivalent below PSQL query?
select a from table1
intersect
select a from table2;

I read through the documentation https://postgrest.org/en/stable/ and didn't see any commands.
If relevant, I'm using Supabase clients for postgREST right now. Thank you!

A: You can create a view and then query the view via PostgREST.


text:
Q: Get-Process to remote computer doesn't work but Invoke-Command does I have a 2 servers running Windows Server 2012 R2. One of them is hosting a virtual machine running Windows 7 32-bit, and I am trying to use the other server to view the currently running processes of the virtual machine.
I had to use Enable-PSRemoting -SkipNetworkProfileCheck for anything to work. I also had to add the computers to each others TrustedHosts lists.
Get-Process -ComputerName VM01

will return a "Couldn't connect to remote machine". However,
Invoke-Command -ComputerName VM01 -ScriptBlock {Get-Process}

works just fine. What is the difference between using Invoke-Command and using the Get-Process with a ComputerName argument? In case it is important, I can also use Enter-PSSession without any problems

A: Get-Process probably uses the DCOM/RPC remoting protocol instead of Windows Remote Management (WinRM), which is what PowerShell Remoting (eg. Invoke-Command) uses. If you have a firewall blocking DCOM/RPC, then I could see how Get-Process with the -ComputerName parameter would fail. With PowerShell Remoting (via WinRM), all you need to do is open up TCP 5985 (HTTP) and TCP 5986 (HTTPS, optional).

A: I ran across this error my self today, the solution in my case (I already had enabled port 5985) the problem occurred because of my firewall blocked port 445 (on the target).
As soon as this port was enabled I was able to use,
Get-Process -ComputerName dc01

and
Get-Service -ComputerName dc01

However I do recommend you read this page:
https://www.grc.com/port_445.htm
as it seems that some security issues may appear upon allowing this port toward the Internet.
My symptoms was exactly as OP descripes...


text:
Q: Visual Studio Code doesn't stage Git merge changes Using Git as a source control provider in Visual Studio Code I have an issue whenever I try to merge a conflict file with remote repository keeping my current version.
The steps are the following:

*

*A file has been modified on remote repository and I modify the same file on the
local repository

*When I try to push my changes to the server I recieve (correctly) an error
message (no-fast-forward) and I must perform a pull to update my local
repository

*When pulling, the editor warn me about the conflict on the file, giving me four
option (Accept Current Change, Accept Incoming Change, Accept Both Changes,
Compare Changes)

*I accept the current change (my local version) and save the file. When I try to
stage the change the file is not added to the section STAGED CHANGES but it
disappears. Git remain in a "merging" status and I can't do anything (a push
gives me the same error of the first push and a pull gives me an error like I
didn't resolved the conflict; in fact in the .git folder I still have the
MERGE_HEAD file)

If I Accept the Incoming Change, Accept Both Changes or add additional chars to my previous version (to change the version I tried to commit before) everything works fine. I think that when I choose "Accept Current Change" and try to stage merge changes the editor (or Git?) doesn't add the file to the STAGED CHANGES because it's identical to the version previously committed, and doesn't update the git status, that remains stuck in merge conflict.
The workaround of adding additional chars to the previous version when merging works fine, but I need to know if it's a bug or I'm missing some steps when merging.
Please don't reply me with command line workaround (like git merge --abort), I'm looking for a UI friendly solution (not all of my team mates are confident with command line). Thanks in advance.

A: This was a bug in Visual Studio Code which has been fixed in commit 578d7381da3e9d559e9326375b67429a5de3027d and was shipped in November 2020 with version 1.52.0 of VS Code.


text:
Q: backbone.bootstrapModal separate events Can I separate the callback events in a backbone.BootstrapModal?
Saying for example that i want the cancel button to act like a logout button, the ok one will be the login while the close (right hand side, at the top) just close the modal?
I've been searching for this but i wasn't able to find anything...
This is the documentation but I didn't find anything usefull regarding what i need
https://github.com/powmedia/backbone.bootstrap-modal
Basically it needs to call a function on close and another, different, on cancel...
Any ideas on how I could achieve this?
Thanks in advance

A: Nevermind, at the end I decided to hide the default cancel button and create a custom one with the event I wanted trigger by this new one.
Thanks anyway


text:
Q: AlertManager maximum duration of Silence Is there a maximum duration of silence in Alert manager? My requirement is to silence alerts coming from a specific site for a long time. When the field technicians approve the requests only then we should expire the silence and enable alerts. So, is there anyway we can setup a silences on alerts forever instead of selecting a duration?
Thanks,
Arnav

A: In the openapi silence definition silence are defined for a begin/end time not by duration. I expect the duration in the interface is for UI only.
The format is a date-time as defined in RFC3339. So, in theory, you should be able to set an end-time to 9999-12-31T23:59:59.999.
The maximum duration will just depend on when you set it. In practice, it won't make a difference: if you fancy using a 100 year duration because it easier to type, it will be like forever.


text:
Q: What's the difference between a figure, a number and a digit? A dictionary says:
Figure: a symbol for a number
Digit: a word, letter, symbol, or figure representing a number.
Number: a mathematical unit used to count or express an amount, quantity.
I don't see a big difference between a figure and a digit. What is it?

A: You're using a select subset of many definitions for figure, number, and digit.
A digit is a single numeral (0-9), like the digit 5 in the number 5, or the digit 5 in the number 2507.
A number can have one or more digits, like 7 or 2507 or 2,507.38.
A figure can be a shape, a diagram, or a number; if used to describe a number, it can be composed of a single digit or of multiple digits.

A: A figure is something that is drawn, which might be digit.
A figure can also be a number or amount, for example in this dialogue:

We will need to pay them off.
What figure do you have in mind?
I suggest 10,000 should be enough.

A digit is a single number in the range 0 to 9. It is the same word for fingers/thumbs and toes, of which we have 10 each.
Sometimes digit and figure can be used interchangeably.

10,000 is a five figure sum.

In computer parlance, each of those figures is referred to as a digit.

A number is an arithmetical quantity, which is written using digits and other symbols, such as a sign and a decimal point.


text:
Q: Help parsing a page with python I would like to parse a webpage to can get the url of the video download. I use python and firebug but I cant get the url link.
Example:
The url where I have to get the video link is:
hxxp://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtml"
The video is
hxxp://www.rtve.es/resources/TE_SSAC011/flv/8/2/1264426362028.flv
Could you help me please?
Many thanks and sorry for my english!

A: Use BeautifulSoup or lxml.

A: import re
from urllib2 import urlopen
text = urlopen('http://www.rtve.es/mediateca/videos/20100125/saber-comer---salsa-verde-judiones-25-01-10/676590.shtm').read()
reg = re.compile(r'http://www\.rtv.*flv')
reg.findall(text)

Normallly you can use this one. But there is no your link inside.

A: @OP, those videos are generated by javascript. For this topic, see here. Or search google for references.


text:
Q: Изменение максимальной длины значений столбца SAL Ребята! Подскажите пожалуйста! В Oracle я новичок!! Измените максимальную длину значений столбца SAL до 9 знаков (из них 2 после запятой) в таблице EMP_NEW.
Всем спасибо!)

A: alter table EMP_NEW modify SAL number(7,2);


text:
Q: Flutter Firebase notification is not displayed in onMessageOpenedApp and onBackgroundMessage I have an application Flutter and I use firebase messaging. On most smartphones the message is received normally in all states (onMessage, onMessageOpenedApp, onBackgroundMessage). But on some smartphones, notification doesn't come (onMessageOpenedApp, onBackgroundMessage), I've tried some tips and it didn't work for me. My last attempt was this, top-level function :
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print(
      "Background message: ${message.notification.title}, ${message.notification.body}");
}

void main() {
  FirebaseMessaging.onMessageOpenedApp.listen(_firebaseMessagingBackgroundHandler);
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(InitApp());
}

I'm using:
  firebase_core : ^1.6.0
  firebase_messaging : ^10.0.6

Please I need tips on what else I can try to do.


text:
Q: input username check unique immediately with django rest framework I want to realize like this: if I input any character in username input tag I can check the username if unique in server.
I know I can do like this: use javascript + debounce, after user input characters stop 0.5 second, then I send username to server(I can create single view to handle this solution), and if find duplication, I can hint some error near it.
But in fact, I am not only handle the username, I want to handle all of config form, I want to every form's field can be test before send whole form data to server like this.
There may be 100 fields, I dont' want to write a view for every field, so does django-rest-framework support some function? or is there any package suuport it, or somebody have any idea for it??
in fact, I use reactjs, but I don't think it have any relationship with this problem

A: No, there's no such thing. You'll have to write your own. A non rest entry point that would take a POST including field name and field value and check the unicity in the DB.


text:
Q: Why am I getting, "Cannot implicitly convert type 'void' to 'object'" with this code (EPPlus)? I was using this code to populate a cell in a spreadsheet using EPPlus:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
    footerMonth1Cell.Value = monthsTruncatedYears[0];
    footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
    footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}

It was working fine, I thought, but a user complained that it was producing "green triangles" in the cells. "monthsTruncatedYears" is a generic list of string.
So I added this helper function:
public static void SetValueIntOrStr(this ExcelRangeBase range, object value)
{
    string strVal = value.ToString();
    if (!String.IsNullOrEmpty(strVal))
    {
        double dVal;
        int iVal;

        if (double.TryParse(strVal, out dVal))
            range.Value = dVal;
        else if (Int32.TryParse(strVal, out iVal))
            range.Value = iVal;
        else
            range.Value = strVal;
    }
    else
        range.Value = null;
}

...which I got from here, and then tried to refactor the original code to call that helper function like so:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
    footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
    footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
    footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}

However, it won't compile, telling me, "Cannot implicitly convert type 'void' to 'object'"
Since the second arg passed to SetValueIntOrStr(), namely "value", is of type object, I assume that is the problem. So why does the compiler apparently view monthsTruncatedYears[0] as being void? In the legacy code I assigned it as the value to the cell, and it wasn't void at that time, so...?!?
I tried casting the second arg to object like so:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueIntOrStr(footerMonth1Cell, object(monthsTruncatedYears[0]));

...but that won't compute, either, with "Invalid expression term 'object'"
...and this similar attempt:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueDoubleOrIntOrStr(footerMonth1Cell, monthsTruncatedYears[0] as object);

...elicits, "Cannot implicitly convert type 'void' to 'object'"
Note that the helper method is actually misnamed in the borrowed code; instead of "SetValueIntOrStr" it should be "SetValueDoubleOrIntOrStr"

A: The problem is the line
footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);

SetValueIntOrStr does not return any value (void) and therefore cannot be used to assign a value to the footerMonth1Cell.Value.
This would be valid code because the Value property is already changed inside the function:
SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);


text:
Q: How to initiazlize firebase puse notifications in NativeScript Angular app I am creating an app with nativescript + Angular + Firebase push notifications using this plugin: nativescript-plugin-firebase.
According to their documentation firebase.init should be called OnInit but then after app is reloaded in development i got an error that "Token is already intialized"
Question is how to check if token is already intialized.
I can check by using this code but it is kind of hacky:
const initializedToken = await messaging.getCurrentPushToken();

if (initializedToken) {
    return;
}

Also i wonder if developemnt app restart = app reopen on real device?
Thanks

A: I haven't used Nativescript but with my Angular knowledge, I can tell you that Place your firebase.init() method in the app.component.ts file because it is the first component and is always eagerly loaded once the app starts. and then you can use firebase's methods to verify of its initialized or not.


text:
Q: How can I run a console project from within a WPF project I currently have a WPF project that has a button.
When you click on the button I intend on having a Console application launch. The console application is a project within the same application.
I am unclear how to properly run the console application as when i try the code below nothing happens(for now the code below is running automatically, without needing to click the button).
public void OpenTheConsoleApp() {
        TheConsoleApp.Program test = new TheConsoleApp.Program();
    }

The console app is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TheConsoleApp
{
public class Program
{
    public static void Main(string[] args)
    {

        Console.WriteLine("Hello World!");

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    public static void Test() {
        Console.WriteLine("Hello World!");

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

}
I need to open the console app by clicking a button on my WPF app.

A: You can't start a "project". You need to create an executable (.exe) to start. Build the console app and start the .exe in the output folder using Process.Start:
Process.Start(@"c:\your_project_dir\bin\Debug\ConsoleApp.exe");


text:
Q: black screen when connecting to xrdp server I have installed archLinux on rapberry-pi, and everything is just working fine, till i have came across setting up remote dektop. am trying to access xrdp server using remmina
client from another linux distro, but all i can get is black screen with mouse pointer, I have tried almost all solutions that i can find over Internet forums but none of them has resolved my issue I have also gone through this issue  but that also doesn't work for me. I have installed xrdp, tigerVNC, vino using (AUR)yaourt , also am using XFCE desktop , as it lightwieght and runs smooth on rapberry.

status of vncserver.service by running .
vncserver.service - Remote desktop service (VNC)    Loaded: loaded
  (/usr/lib/systemd/system/vncserver.service; disabled; vendor p
  Active: inactive (dead)

also output of /var/log/xrdp.log

[20161126-14:37:07] [INFO ] An established connection closed to
  endpoint: NULL:NULL - socket: 11 [20161126-14:37:08] [INFO ] An
  established connection closed to endpoint: NULL:NULL - socket: 11
  [20161126-14:37:09] [INFO ] An established connection closed to
  endpoint: NULL:NULL - socket: 11 [20161126-14:37:10] [ERROR] Failure
  to connect to sesman: 127.0.0.1 port: 3350 [20161126-14:37:10] [INFO ]
  An established connection closed to endpoint: NULL:NULL - socket: 11
  [20161126-14:37:10] [DEBUG] returnvalue from xrdp_mm_connect 1

am not sure if the above mentioned info is enough but that's all  I had at the moment, so let me know guys if anyone have solution to this issue!


text:
Q: Read Java Internet Connections settings - jdk1.4 Is there a way of getting internet connection settings (proxy information) being used by java to connect to the internet?
With Java 1.5 you can use the ProxySelector introduced then, is there any way of doing it in jdk1.4?
I tried getting these seeting using the following code snippet, but returning nulls even though i have set my proxy.
String javaVersion = System.getProperty("java.version");
String ip = null;
String port = null;
String noProxyHosts = null;

if (javaVersion.startsWith("1.4")) {
    ip = System.getProperty("proxyHost");
    port = System.getProperty("proxyPort");
    noProxyHosts = System.getProperty("http.nonProxyHosts");
} else {
    ip = System.getProperty("deployment.proxy.http.host");
    port = System.getProperty("deployment.proxy.http.port");
    noProxyHosts = System.getProperty("deployment.proxy.override.hosts");
}

A brief background; I have a webstart Java application that spawns an internal web browser which needs these setting to get going.

A: I found this code sample on the Java forums:
  sun.plugin.net.proxy.ProxyInfo pi = sun.plugin.net.proxy.PluginProxyManager.getProxyInfo(url);
  String host = pi.getProxy();
  int port = pi.getPort();

You need to add plugin.jar to your classpath to use this code.  I found it in /jre/lib.
The URL to the forum post is: http://forums.sun.com/thread.jspa?threadID=364342&forumID=30


text:
Q: Docker raspberry pi cloning private bitbucket git repo on build-time I am trying to build OTA(over the air) update mechanism with docker and watchtower. I am newbie at linux and Docker. I think I will use the technic shown here. which I think bitbucket ssh key stored in the host(rpi) and with this technic I will copy that keys in to container.  What I am wondering is; because of my rpi devices will be at hands of my customers.

*

*Have I understand the concept right by "bitbucket ssh key stored in the host(rpi) and with this technic I will copy that keys in to container."

*if 1. is will happen that way. is my ssh key secure? which it will be stored in each device I will deliver the customers.

A: The SSH private key will need to be on each rpi, and the corresponding public key will need to be added to the Bitbucket repo(s).
If the private key is compromised - which is possible, if you're distributing it everywhere - then the potential damage will depend on where you've put the public key. You can mitigate that potential damage with a couple of things:

*

*Only use this keypair for this specific purpose.

*Add the public key as an "access key" on just the repo(s) that need it. Access keys are read-only in Bitbucket, so if/when the private key is compromised then the attacker will be able to read (but not modify) the code.

*If you don't have a lot of customers who'll be using this specific thing, consider creating a different key for each one (so you can revoke access for specific customers or devices as you need to). This could get complicated to maintain, though.


text:
Q: Maven Dependency for com.install4j.install4j-runtime I am using below maven dependency for com.install4j.install4j-runtime
<dependency>
     <groupId>com.install4j</groupId>
     <artifactId>install4j-runtime</artifactId>
     <version>6.0.4</version>
</dependency>

Version is not valid.
Can any one help me is resolving the dependency?

A: You have to add the repository:
<repository>
   <id>ej-technologies</id>
   <url>http://maven.ej-technologies.com/repository</url>
</repository>

to your POM.


text:
Q: KOPS api ELB launches with master instances out-of-service I have a weird thing going on with KOPS.
after launching to a new VPC, I can't seem to get kubectl configured to the created cluster (no such host).
Looking into route53 record (api.dev.mydomain.co) I can see it pointing to an ELB appropriately.
quick ELB inspection showed that all registered instances are out-of-service.
Can't SSH to master instances (no public ip), not even through a bastion (ssh with private-key asked for passphrase which I didn't know -> access denied).
I tried several different network overlays, as well as an older kops version, nothing worked.
Thoughts or ideas? Am I missing something or a misconfigured my AWS account? That did use to work before on a different account.
kops create cluster \
  --cloud aws \
  --node-count 2 \
  --master-count 1 \
  --zones us-east-1a,us-east-1b,us-east-1c,us-east-1d,us-east-1e,us-east-1f \
  --master-zones us-east-1a \
  --dns-zone mydomain.co \
  --node-size m4.large \
  --master-size m4.large \
  --topology private \
  --networking canal \
  --image kope.io/k8s-1.8-debian-jessie-amd64-hvm-ebs-2017-12-02 \
  --name dev.mydomain.co

A: Master nodes could be out of service if they are not able to reach internet or resolve dns. I would check first if "DHCP Options Sets" and "Internet Gateway" are properly configured for VPC.
Regarding "passphrase" for private ssh key, it should be the same as you used when were generating the key with "ssh-keygen" command.
https://github.com/kubernetes/kops/blob/master/docs/security.md
SSH public key can be specified with the --ssh-public-key option, and it defaults to ~/.ssh/id_rsa.pub