Q:

PyGtk text buffer using to much memory want to clean it but then iter dont work

So I am just learning how to code and Im using pygtk to make a gui for a irc bot that im working on. The bot as some fun commands and stuf, but what im really here for is that I print the chat messages into a textbuffer and it makes memory go up, wich really isnt a problem unless you have a huge ammount of messages or want this to be on all the time. But with this problems in mind I wanted the bot to when he reached like 500 messages in the textbuffer(or 500 lines) he would delete the first 250 from the text buffer so that it would keep the memory usage down and still plenty of messages to read to whoever was using the gui.
My problem is that I dont really know how to do this, if I use iters they will become useless when delete the 250 lines because i've changed the textbuffer, and I also tried to use marks but it does look like I know how to use them...
HALP PLOX! xD
Code can be found here. The textbuffer is located inside run.py and is named chatbuffer.

A:

Solved it Kappa
I use this for deletion:
if chatbuffer.get_line_count() > 10:
    chatbuffer.delete(chatbuffer.get_iter_at_line(0), chatbuffer.get_iter_at_line(251))

And instead of defining inters like:
end_inter = chatbuffer.get_end_inter()

I just straigth up use:
chatbuffer.get_end_inter()

Like this:
chatbuffer.insert(chatbuffer.get_end_iter(), user + " > " + message + "\n")

EDIT: WELL IM DUMB I created a whole another questin because of an error that I encouuntered after this because I tested this with 10 lines and deleting 5 and forgot to change it to 500 on the final code. gtk-error **: gtk_text_btree_previous_line ran out of lines aborting


Q:

Long/multiple SQL queries vs Serialization

I'm trying to improve the performance of my web app where a page does a long query to pull data from different tables on a database. It pulls invoice data with multiple item lines, invoice status, and with each line having additional properties from another table.
Is serialization worth considering for improvement? The tables are related and in normalized form.

A:

I’d first do some profiling on the queries just to make sure that they are running as efficiently as they can – simply adding an index in the correct place may solve the problem.
If the queries are fine then I would look at data caching in ASP.NET. The following link is a good article on this: http://aspnet.4guysfromrolla.com/articles/100902-1.aspx


Q:

How to perform math on each value of multi-dimensional array using the sum of its column data?

I have a collection of "answers" (multi-dimensional array) which is extracted from a database.  I need to perform a calculation on each value so that I can show the results on a graph.
Here is some sample input:
$array = [
    'A1' => [1 => 1, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
    'A2' => [1 => 1, 2 => 1, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
    'A3' => [1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0]
];

I want to calculate a percentage value from the multidimensional array using this kind of logic:
[A1] => Array( ([1]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )
[A2] => Array( ([1]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )
[A3] => Array( ([3]*100/sum([1]+[1]+[1]), [2]*100/sum([2]+[2]+[2]),..... )

How can I do this?
My desired output:
[
  'A1' => [1 => 50, 2 => 0,   3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
  'A2' => [1 => 50, 2 => 100, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0],
  'A3' => [1 => 0,  2 => 0,   3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0, 9 => 0, 10 => 0]
]

A:

Ahh, I see what you're trying to do now.
Try this
$totals = array();

// First get our totals.
foreach ($mainArray as $subKey => $subArray) {
    foreach ($subArray as $k => $v) {
        // Add the column to our total.
        $totals[$k] = isset($totals[$k]) ? $totals[$k] + $v : $v;
    }
}

$answers = array();
// Then build our answers.
foreach ($mainArray as $subKey => $subArray) {
    $answers[$subKey] = array();
    foreach ($subArray as $k => $v) {
        $answers[$subKey][$k] = ($v * 100) / $totals[$k];
    }
}

print_r($answers);


Q:

Remembering a 90's childrens book about disease, female protagonist with a mutant sheep?

During the year 2001 I read a children's horror novel, whose title I have forgotten. I would really like to read it again as an adult, I think about this book all the time! Unfortunately it has been difficult to track down, as I can remember 6 things about this book:

It was most likely set in Australia, though I could be wrong.
It had a greenish cover, possibly with a slightly horrific picture of a zombie sheep. Again, I could be wrong.
The female main character's father gets remarried, and her male friend (her step brother?) gets infected with an illness.
Later on they find her late mother's crashed school bus, and get chased by a sheep which is infected with the illness, and it shies away from her dead mum's trainer, because the mould growing on it is the cure.
The boy and girl are attacked later on by plants infected with the disease, which stop their car and drink the fuel from their tank
They later take shelter in a sewer and find the boy's father, who also has the disease but has controlled it somehow with this mould stuff.

If anyone recognises any of this please reply- even if it is only to say that you read it too!

A:

This is the series "Wicked" by Paul Jennings and Morris Gleitzman, two wonderful Australian authors.

The Slobberers
Battering rams
Croaked
Dead ringer
Creeper
Till death us do part

They are published as one book, but I first met them written as one story, spread across 6 short books.  It's been a while since I read them, but from the titles, Battering Rams has the carnivorous sheep, and Creeper has the infected plants.
Here's a link to the book on Paul Jenning's website.


Q:

Why does web2py display disabled input html when I use the checkbox widget?

I am learning web2py but am having some trouble. I have a one-to-many relationship as defined here:
db.define_table('dog',
    Field('name', requires=IS_NOT_EMPTY()))
db.define_table('person',
    Field('name', requires=IS_NOT_EMPTY()),
    Field('dogs', 'list:reference dog'))

db.person.dogs.widget=SQLFORM.widgets.checkboxes.widget

Where a dog has one owner, but an owner can have multiple dogs.
In my controller, I create a form which has a textfield for the person's name, and a list of dogs represented as checkboxes.
The controller code for the form creation is simply:
form = SQLFORM(db.person)   # rendered with {{=form}} in views

This works, but at the end of the list of checkboxes there is an odd text input which is marked as disabled:

<input class="hidden" disabled="disabled" name="dogs" type="text" />

This isn't actually hidden, just greyed out.
I looked at the web2py source, and the checkbox widget is located in web2py.gluon.sqlhtml, but I'm having a hard time interpreting why it's appending this disabled input to the checkbox list.
Can anyone clarify why this disabled input is there or how to properly create this form without this problem?

A:

Anthony's comment was correct: I had forgotten to load the css file.


Q:

Error-1054 Unknown column 'column name' in 'field-list'

When I create one trigger of before insert for prevent wrong input then trigger has created but after insert values in that table then it create error like Error-1054 Unknown column 'column-name' in 'field-list'. I want to create trigger for prevent wrong input from users then how is it possible that insert values in table after creating trigger. Code shown as below of trigger
CREATE DEFINER=`root`@`localhost` TRIGGER `mobile_no` BEFORE INSERT ON `invoiceform_clients` FOR EACH ROW
BEGIN
if length(clientPhonenumber)=10 THEN
 insert into invoiceform_clients(clientPhonenumber) values(clientPhonenumber);
ELSE
 SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT= 'Mobile NO. must be in 10 digit';
end if;
END;

A:

You don't need to repeat the insert statement inside the trigger body - just validate the column value and throw the signal if it's wrong. If the trigger code exits normally, the original INSERT which fired the trigger will succeed as well.
You should also be testing NEW.clientPhonenumber instead of just clientPhonenumber - this specifies that you want to check the field in the record as it will exist after the INSERT completes.
The trigger should look something like this:
CREATE DEFINER=`root`@`localhost` TRIGGER `mobile_no`
  BEFORE INSERT ON `invoiceform_clients`
  FOR EACH ROW
BEGIN
  IF length(NEW.clientPhonenumber) != 10 THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT= 'Mobile NO. must be in 10 digit';
  END IF;
END;


Q:

Drawing an HSV color wheel in Qt C++

So I am trying to create a simple color wheel in Qt C++ using QPainter and QQuickPaintedItem, however I can't seem to figure what I am doing wrong. I subclassed a QQuickPaintedItem and then in the QQuickPaintedItem::paint function I wrote a simple function like below.
#ifndef COLORWHEEL_H
#define COLORWHEEL_H

#include <QQuickPaintedItem>
#include <QPainter>
#include <QtMath>

class ColorWheel : public QQuickPaintedItem
{
public:
    ColorWheel()
    {
    }

    void paint(QPainter *painter) override
    {
        QPen pen;
        pen.setWidth(1);
        for(int w = 0; w <= width(); w++){

            for(int h = 0; h <= height(); h++){

                // coordinate transformation so that the origin is at the centre of the item
                // also y values should increase as you go up and decrease as you go down
                int a = w - width()/2;
                int b = height()/2 - h;

                Polar p = cartesianToPolar(a, b);

                // only paint pixels inside the circle
                if(p.radius <= width()/2){
                    qreal hue = p.angle/(2*M_PI) ;
                    qreal sat = p.radius/width()/2;

                    QColor color;
                    color.setHsvF(hue, sat, 1.0);
                    pen.setColor(color);

                    painter->setPen(pen);
                    painter->drawPoint(QPoint(w,h));
                }
            }
        }
    }
private:
    struct Polar{
        qreal radius;
        qreal angle;
    };

    Polar cartesianToPolar(qreal x, qreal y)
    {
        qreal theta = qAtan(y/x);

        if(theta < 0){
            theta += (2* M_PI);
        }
        qreal r = qSqrt((x*x) + (y*y));
        Polar p;
        p.angle = theta;
        p.radius = r;

        return p;
    }
};

#endif // COLORWHEEL_H

Then using qmlRegisterType<ColorWheel>("Color", 1, 0, "ColorWheel"); I simply wrote a simple qml file:
import QtQuick 2.12
import QtQuick.Window 2.12
import Color 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    ColorWheel {
        width: 720
        height: 720
    }
}

This doesn't work as expected (the colors in the wheel are incorrect).
A similar question has been asked here but it involves PyQt (I suppose the logic should be the same).

A:

I solved the problem. The issue was mathematical as didn't remember that one cannot infer the quadrant of an angle simply by its tangent. Instead one should you use the atan2 function which always return a positive angle when transforming cartesian coordinates.


Q:

Storyboard Zoom In/Out Keyboard Shortcut

What shortcut key combination can I use in Xcode to zoom in and out? Yes, I know this is a silly question but a Google search didn't give me any result. Even the Xcode keyboard shortcuts didn't give me much info. Maybe I must ask for a better updated keyboard shortcut doc for Xcode 4.5

A:

You can also double click with mouse on empty area of storyboard. First time will zoom out, second time - zoom in. Sometimes it's easier than use difficult hotkey.

A:

Try this
Zoom Out = shift+command+alt+{
Zoom In = shift+command+alt+}
This worked for me!

A:

From Mouse or Trackpad -> Right Click will show you options. Hope this will help


Q:

Which question is grammatically correct?

I'm not a native speaker, which of these is grammatically correct?

"How many amounts of information?"
"How many pieces of information?"
"How many information?"
"How much information?"

I think the 2nd and 4th ones are correct and the others aren't, am I correct?
I do understand that many is used with countable nouns and much is used to uncountable nouns.
And I also understand that the word "information" is an uncoutable noun in British English.
What confuses me is an exercise for school:

How much information do you need? (use how many)

One of my friends said it'd be like the first example but I don't think so.

A:

Think of information as if it were honey, the sweet substance bees produce, not the synonym for "nice person" or "sweetheart". Also think of it in its flowing state, not crystallized.
How many honey does the recipe call for? ungrammatical
How much honey does the recipe call for? grammatical
How many informations on your web browsing habits does Google collect? ungrammatical
How much information on your web browsing habits does Google collect? grammatical
An amount is an unspecified quantity.  For that reason we cannot ask How many amounts...? because nobody knows the size of the amount. And when you add amounts together, they simply become a larger amount. An amount has no size until it is modified, for example "a small amount" or "a large amount", and even then the size is relative and vague.


Q:

Drag and drop function is not working in chromedriver using selenium webdriver and Node js for Test automation

Is there a way where I can make drag and drop to in selenium using Node.js? I am using the function shown below but it does not seem to work.
driver.actions().dragAndDrop(source,destination).perform())

A:

First of all, you forgot the build() method.
Second of all, inspect the html code and find if your drag&drop is into Iframe tag.
If it is, then you need to switch to that Iframe.
So:
driver.switchTo().frame(driver.findElement(By.xpath("PutYourXpathIframe")));

Actions a = new Actions(driver);
WebElement source = driver.findElement(By.id("PutYourSourceId"));
WebElement target = driver.findElement(By.id("PutyourTargerId"));
a.dragAndDrop(source,target).build().perform();

In the end you may want to switch back to default content:
driver.switchTo().defaultContent();


Q:

Convert system dynamic disk w/o data-loss windows server 2003

Does anybody know how to convert dynamic system disk to basic in Windows server 2003 without data-loss and if possible without using third-party tools? Is that possible?
I was thinking of making a mirror copy of this disk onto Basic disk and then simply exchanging these disks and changing boot.ini.
Oh, this is virtual server on VMware.
Thanks in advance.

A:

I've had success with this in the past as outlined in the following post:
http://www.wilderssecurity.com/showthread.php?t=191006
I would test it out on a test drive first just in case.


Q:

What does “ leadups and outs” mean in following content?

What does "leadups and outs" mean in this quote?

The best way to approach learning how to play "Flight of the Bumblebee" is to work on memorizing bits of it at a time. A lot of the piece is essentially a main theme with leadups and outs of that theme, chromatically.
Steve Booke in Guitar World

A:

lead–up
noun \ˈlēˌdəp\
:  something that leads up to or prepares the way for something
  else
the race will serve as a lead-up to the classic — Sydney (Australia) Bulletin
Merriam-Webster Unabridged Dictionary


Q:

Enlarge an image from zero to full size on image load

I'm placing images of a bubble randomly and I want to simulate the effect of making the bubble by enlarging the image from zero to full size. I'm using CSS transform:scale(); but I want to trigger the animation when the image loads.

A:

You can add a class to the image when it finishes loading, and specify proper transition and transform rules in CSS.

$("img").load(function() {
  $(this).addClass("loaded");
});
img {
  transition: transform 1s;
  transform: scaleX(0) scaleY(0);
}
img.loaded {
  transform: scaleX(1) scaleY(1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://lorempixel.com/600/600/">


Q:

How to perform multiple actions on the same element using jquery

how do I include both drag and resize on a single element.
<head>
<style type="text/css">
  #header { width: 200px; height: 100px; background: blue; }
</style>
<script>
  $(document).ready(function() {
    $("#header").draggable().resizable();
  });
</script>
</head>
<body style="font-size:100%;font-weight:bold;font-style:times" >

    <div id="header">

      <label> Header <input type="text" value="headerBox" /> </label>
      <input type="button" value="submit" id="headerSubmit" name="submit" />
      <input type="reset" value="reset"/>

    </div>

    </body>
    </html>

A:

both draggable and resizable supports chaining mode so you can simplify your code in one line
$(document).ready(function() {

    $("#header").draggable().resizable();
 });

see demo here.... DEMO
refer this tutorial for more information .....Draggable and resizable


Q:

How to convert dataurl back to image and display on canvas

I have 3 canvases. I crop a region from canvas1 and display it on canvas 2  . Then I want to convert canvas 2 image to a URL and to see if can convert that URL back to a image. I want it to be displayed in canvas c4.Any help is appreciated.
// image is drawn here , I want this image to be converted to a dataURL
//then back to image and display it in canvas c4
var c2 =  document.getElementById("area_c2");

 var ctx = c.getContext("2d");
 var ctx2 = c2.getContext("2d");
 image_src.width = c2.width;
 image_src.height = c2.height;

ctx2.drawImage(image_src, 0, 0,image_src.width, image_src.height);

 var c4 =  document.getElementById("area_c4");
 var ctx4 = c4.getContext("2d");

 var dataURL = c2.toDataURL();

 var myImg = new Image;

 myImg.src = dataURL;

 myImg.width = c4.width;
 myImg.height = c4.height;

 ctx4.drawImage(myImg, 0, 0, image_src.width, image_src.height); //Image //is not displayed here , I want the image to take the size of the canvas

  <canvas  id ="area_c2" style="width:300px;height:300px;border:3px solid
  black;z-index:1"  >
  </canvas>

 <canvas id ="area_c4" style="width:300px;height:300px;border:3px solid
   black;z-index:1;background:red">
 </canvas>

A:

The reason your solution did not work is because you did not wait for the onload event. Before the onload event the image will not render.
To convert a canvas to a data URL is simple, use the .toDataURL(); method of the canvas element.
Then to convert the data URL back to an canvas image, you would first have to create an Image element and set its source as the dataURL. After getting the image onload event you can draw the image onto the canvas. This could be accomplished as shown:
Assuming the data URL is in a variable called dataURL, the canvas context is in a variable called ctx.
var img = new Image;
img.onload = () => { ctx.drawImage(img, 0, 0); };
img.src = dataURL;

The final solution would go like this:
var cdata2 = c2.toDataURL();
var cimg2 = new Image;
cimg2.onload = () => { ctx4.drawImage(cimg2, 0, 0, c4.width, c4.height); };

PS: You don't have to scale the image object by specifying the width and height, the canvas will do that when you specify the destination width and height.


Q:

Swift - UIImagePickerController - how to use it?

I am trying hard to understand how this works, but it's pretty hard for me. =)
I have 1 view, there is one button and one small ImageView area for preview.
The button triggers imagepickercontroller, and the UIView will display picked image.
There is no error but the image doesn't show in the UIImageView area.
var imagePicker = UIImagePickerController()
@IBOutlet var imagePreview : UIImageView

@IBAction func AddImageButton(sender : AnyObject) {
    imagePicker.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
    imagePicker.delegate = self
    self.presentModalViewController(imagePicker, animated: true)

}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary!) {
    var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
    imagePreview.image  = tempImage

    self.dismissModalViewControllerAnimated(true)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController!) {

    self.dismissModalViewControllerAnimated(true)
}

A:

You're grabbing a UIImage named UIImagePickerControllerOriginalImage and there exists no such image. You're meant to grab the UIImage with the key UIImagePickerControllerOriginalImage from the editingInfo dictionary:
let tempImage = editingInfo[UIImagePickerControllerOriginalImage] as! UIImage

A:

import MobileCoreServices

class SecondViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

   @IBOutlet var img:UIImageView!=nil

   override func viewDidLoad() {
        super.viewDidLoad()
   }

   override func didReceiveMemoryWarning()
   {
       super.didReceiveMemoryWarning()

   }

   @IBAction func buttonTapped(AnyObject)
   {
     if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            println("Button capture")
            var imag = UIImagePickerController()
            imag.delegate = self
            imag.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            //imag.mediaTypes = [kUTTypeImage];
            imag.allowsEditing = false
            self.presentViewController(imag, animated: true, completion: nil)
        }
   }

   func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
        let selectedImage : UIImage = image
       //var tempImage:UIImage = editingInfo[UIImagePickerControllerOriginalImage] as UIImage
        img.image=selectedImage
        self.dismissViewControllerAnimated(true, completion: nil)
   }
 }

A:

Details

Xcode 11.4.1 (11E503a), Swift 5.2

More
How to build own photo picker
Solution
import UIKit
import AVFoundation
import Photos

protocol ImagePickerDelegate: class {
    func imagePicker(_ imagePicker: ImagePicker, grantedAccess: Bool,
                     to sourceType: UIImagePickerController.SourceType)
    func imagePicker(_ imagePicker: ImagePicker, didSelect image: UIImage)
    func cancelButtonDidClick(on imageView: ImagePicker)
}

class ImagePicker: NSObject {

    private weak var controller: UIImagePickerController?
    weak var delegate: ImagePickerDelegate? = nil

    func dismiss() { controller?.dismiss(animated: true, completion: nil) }
    func present(parent viewController: UIViewController, sourceType: UIImagePickerController.SourceType) {
        let controller = UIImagePickerController()
        controller.delegate = self
        controller.sourceType = sourceType
        self.controller = controller
        DispatchQueue.main.async {
            viewController.present(controller, animated: true, completion: nil)
        }
    }
}

// MARK: Get access to camera or photo library

extension ImagePicker {

    private func showAlert(targetName: String, completion: ((Bool) -> Void)?) {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            let alertVC = UIAlertController(title: "Access to the \(targetName)",
                                            message: "Please provide access to your \(targetName)",
                                            preferredStyle: .alert)
            alertVC.addAction(UIAlertAction(title: "Settings", style: .default, handler: { action in
                guard   let settingsUrl = URL(string: UIApplication.openSettingsURLString),
                        UIApplication.shared.canOpenURL(settingsUrl) else { completion?(false); return }
                UIApplication.shared.open(settingsUrl, options: [:]) { [weak self] _ in
                    self?.showAlert(targetName: targetName, completion: completion)
                }
            }))
            alertVC.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completion?(false) }))
            UIApplication.shared.windows.filter { $0.isKeyWindow }.first?
                .rootViewController?.present(alertVC, animated: true, completion: nil)
        }
    }

    func cameraAsscessRequest() {
        if delegate == nil { return }
        let source = UIImagePickerController.SourceType.camera
        if AVCaptureDevice.authorizationStatus(for: .video) ==  .authorized {
            delegate?.imagePicker(self, grantedAccess: true, to: source)
        } else {
            AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
                guard let self = self else { return }
                if granted {
                    self.delegate?.imagePicker(self, grantedAccess: granted, to: source)
                } else {
                    self.showAlert(targetName: "camera") { self.delegate?.imagePicker(self, grantedAccess: $0, to: source) }
                }
            }
        }
    }

    func photoGalleryAsscessRequest() {
        PHPhotoLibrary.requestAuthorization { [weak self] result in
            guard let self = self else { return }
            let source = UIImagePickerController.SourceType.photoLibrary
            if result == .authorized {
                DispatchQueue.main.async { [weak self] in
                    guard let self = self else { return }
                    self.delegate?.imagePicker(self, grantedAccess: result == .authorized, to: source)
                }
            } else {
                self.showAlert(targetName: "photo gallery") { self.delegate?.imagePicker(self, grantedAccess: $0, to: source) }
            }
        }
    }
}

// MARK: UINavigationControllerDelegate

extension ImagePicker: UINavigationControllerDelegate { }

// MARK: UIImagePickerControllerDelegate

extension ImagePicker: UIImagePickerControllerDelegate {

    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[.editedImage] as? UIImage {
            delegate?.imagePicker(self, didSelect: image)
            return
        }

        if let image = info[.originalImage] as? UIImage {
            delegate?.imagePicker(self, didSelect: image)
        } else {
            print("Other source")
        }
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        delegate?.cancelButtonDidClick(on: self)
    }
}

Full Usage

Info.plist

 <key>NSPhotoLibraryUsageDescription</key>
 <string>bla-bla-bla</string>
 <key>NSCameraUsageDescription</key>
 <string>bla-bla-bla</string>

ViewController (do not forget to paste solution code)

import UIKit

class ViewController: UIViewController {

    private weak var imageView: UIImageView!
    private lazy var imagePicker: ImagePicker = {
        let imagePicker = ImagePicker()
        imagePicker.delegate = self
        return imagePicker
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "camera", style: .plain, target: self,
                                                           action: #selector(cameraButtonTapped))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "photo", style: .plain, target: self,
                                                           action: #selector(photoButtonTapped))

        let imageView = UIImageView(frame: CGRect(x: 40, y: 80, width: 200, height: 200))
        imageView.backgroundColor = .lightGray
        view.addSubview(imageView)
        self.imageView = imageView
    }

    @objc func photoButtonTapped(_ sender: UIButton) { imagePicker.photoGalleryAsscessRequest() }
    @objc func cameraButtonTapped(_ sender: UIButton) { imagePicker.cameraAsscessRequest() }
}

// MARK: ImagePickerDelegate

extension ViewController: ImagePickerDelegate {

    func imagePicker(_ imagePicker: ImagePicker, didSelect image: UIImage) {
        imageView.image = image
        imagePicker.dismiss()
    }

    func cancelButtonDidClick(on imageView: ImagePicker) { imagePicker.dismiss() }
    func imagePicker(_ imagePicker: ImagePicker, grantedAccess: Bool,
                     to sourceType: UIImagePickerController.SourceType) {
        guard grantedAccess else { return }
        imagePicker.present(parent: self, sourceType: sourceType)
    }
}

Images


Q:

When does getting submatrix of an numpy array returns view but not copy?

I'm trying to get a submatrix of a numpy 2D array, and modify it. Sometimes I get a copy, which modification to it does not affect the original array:
In [650]: d=np.random.rand(5,5)

In [651]: may_share_memory(d, d[[0,1],:][:,[2,3]])
Out[651]: False

In [652]: d[[0,1],:][:,[2,3]]=2

In [653]: d
Out[653]:
array([[ 0.0648922 ,  0.41408311,  0.88024646,  0.22471181,  0.81811439],
       [ 0.32154096,  0.88349028,  0.30755883,  0.55301128,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

while sometimes it seems I get a view, although may_share_memory also returns False:
In [662]: d[np.ix_([0,1],[2,3])]=1

In [663]: d
Out[663]:
array([[ 0.0648922 ,  0.41408311,  1.        ,  1.        ,  0.81811439],
       [ 0.32154096,  0.88349028,  1.        ,  1.        ,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

In [664]: may_share_memory(d, d[np.ix_([0,1],[2,3])])
Out[664]: False

What more strange is, if assign that 'view' to a variable, it becomes a 'copy' (again, modification does not affect the original array):
In [658]: d2=d[np.ix_([0,1],[2,3])]

In [659]: may_share_memory(d,d2)
Out[659]: False

In [660]: d2+=1

In [661]: d
Out[661]:
array([[ 0.0648922 ,  0.41408311,  0.88024646,  0.22471181,  0.81811439],
       [ 0.32154096,  0.88349028,  0.30755883,  0.55301128,  0.61138144],
       [ 0.18398833,  0.40208368,  0.69888324,  0.93197147,  0.43538379],
       [ 0.55633382,  0.80531999,  0.71486132,  0.4186339 ,  0.76487239],
       [ 0.81193408,  0.4951559 ,  0.97713937,  0.33904998,  0.27660239]])

A:

I agree; this is strange. Yet there is a logic to it.
Note that a sliced assignment is a special overloaded method in python. A sliced assignment doesn't create the view and then write to it; it writes to the array directly. You cant create a view to an ndarray of a[[2,0,1]], because you cant express this view as a strided array, which is the fundamental interface all numpy functions demand. But you can directly consume the indices and act on them. Arguably, for consistency, such a sliced assignment should make a modification to a copy; but where is the point in that, if you don't bind the newly created array to a new name?
It is somewhat awkward in python in general that assignment and sliced assignments are completely different beasts, which do completely different things. That is also what is at the root of this. sliced assignment and slicing on the right hand side call different functions, and are conceptually somewhat distinct. may_share_memory refers to the behavior of right hand side slicing, not sliced assignments.

A:

What you're seeing is the difference between "fancy" indexing and normal indexing.
Also, for clarity, d[np.ix_([0,1],[2,3])] = 1 is not a view, it's an assignment. See @EelcoHoogendoorn's answer for more explanation in that regard.  The root of your confusion seems to be with __setitem__ vs __getitem__, which Eelco addresses, but I thought I'd add a few numpy-specific clarifications.
Any time you index with a sequence of coordinates (np.ix_ returns an array of indicies), it's "fancy" indexing and will always return a copy.
Anything you can do with slicing with always return a view.
For example:
In [1]: import numpy as np

In [2]: x = np.arange(10)

In [3]: y = x[3:5]

In [4]: z = x[[3, 4]]

In [5]: z[0] = 100

In [5]: x
Out[5]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [6]: y[0] = 100

In [7]: x
Out[7]: array([  0,   1,   2, 100,   4,   5,   6,   7,   8,   9])

The reason for this is that numpy arrays have to be semi-contiguous in memory (more precisely, they have to be able to be described by an offset, strides, and shape).
Any type of slicing can be described this way (even something like x[:, 3:100:5, None]).
An arbitrary sequence of coordinates (e.g. x[[1, 4, 5, 100]]) cannot be.
Therefore, numpy always returns a view if slicing is used and a copy if "fancy indexing" (a.k.a. using a sequence of indicies or a boolean mask) is used.
Assignments (e.g. x[blah] = y), however, will always modify a numpy array in-place.


Q:

Красиво и эффективно проанализировать массив

Моя задача в принципе решена, но мне не нравится каким способом.
Есть массив длины > 0 (пусть там будут разные числа int для простоты, не сортированы). Метод должен вернуть true, если в массиве присутствуют только 2 группы чисел и размеры этих групп равны либо отличаются на 1. Примеры, возвращающие true: [3,3,5,5] - 2 группы: 3 и 5 - все по 2шт; или [8,8,8,8,2,2,2] - 2 группы: 8-4шт и 2-3шт.
Пример для false: [1,2,3,1,3] - больше чем 2 группы чисел
Без стримов! Остальное можно - стандартные средства джавы.
Пока решение мое такое:
public boolean satisfiedBy(int[] mainCards) {
    Map<Integer, Integer> rankFrequencies = new TreeMap<>();

    for (int rank : mainCards) {
        Integer count = rankFrequencies.get(rank);
        if (count == null)
            count = 0;
        rankFrequencies.put(rank, count + 1);

        // check if there is no more than 2 groups
        if (rankFrequencies.size() > 2)
            return false;
    }

    if (rankFrequencies.size() != 2)
        return false;

    // check if two groups's sizes differs no more than by 1
    Object[] entries = rankFrequencies.entrySet().toArray();
    if (Math.abs(((Map.Entry<Integer, Integer>) entries[0]).getValue() - ((Entry<Integer, Integer>) entries[1]).getValue()) > 1)
        return false;

    return true;
}

Не нравится Object[] entries = rankFrequencies.entrySet().toArray();
и его приведение к нужному типу:
if (Math.abs(((Map.Entry<Integer, Integer>) entries[0]).getValue() - ((Entry<Integer, Integer>) entries[1]).getValue()) > 1)

A:

Мне кажется, что наиболее производительный способ выглядит так:

обозначим за array[0] первый элемент массива
находим любой элемент x, не равный array[0]
проверяем, что каждый элемент массива равен либо x, либо array[0]
считаем число вхождений элементов x и array[0]
проверяем, что они различаются не более чем на один

Вариант с одним проходом по массиву (проверка на Ideone):
public static boolean satisfiedBy(int[] array) {
    Integer anotherValue = null;
    int numberOccurrencesOfFirstElement = 0;
    for (int value : array) {
        if (value == array[0]) {
            ++numberOccurrencesOfFirstElement;
        } else if (anotherValue != null && anotherValue != value) {
            return false;
        } else {
            anotherValue = value;
        }
    }
    return anotherValue != null && Math.abs(array.length - numberOccurrencesOfFirstElement * 2) <= 1;
}

Чуть более читаемый вариант с двумя проходами по массиву (проверка на Ideone):
public static boolean satisfiedBy(int[] array) {
    int element0 = array[0];
    Integer element1 = null;

    for (int value : array)
        if (value != element0)
            element1 = value;
    if (element1 == null)
        return false;

    int count0 = 0;
    int count1 = 0;
    for (int value : array) {
        count0 += value == element0 ? 1 : 0;
        count1 += value == element1 ? 1 : 0;
    }

    return count0 + count1 == array.length && Math.abs(count0 - count1) <= 1;
}

A:

Давно с джавой не работал, потому эдакий java-псевдокод
Map<Int, Int> out = new HashMap<>();

for (int value : array) {
    out.put(value, out.get(value) == null ? 1 : out.get(value) + 1);
    if( out.size() > 2 ) return false;
}

return Math.abs((out.get(out.keySet.toArray[0]) - out.get(out.keySet.toArray[1]))) < 2;

UPD Сначала написал ответ, а потом внимательно вопрос прочитал. :) Как видите, решение практически полностью совпадает, за исключением некоторых нюансов. Решил не удалять, потому как вдруг чем-то да поможет код улучшить


Q:

Help! I've forgotten my phone's lock pattern!

I have an Android phone with a pattern lock screen, which if you've never seen one allows you to unlock your phone using a pattern drawn on the screen over a 3x3 grid of dots.
So for example, if we number the dots as follows:
1 2 3
4 5 6
7 8 9

then valid lock patterns may be created by drawing lines connecting 1 > 2 > 3 > 4, or 1 > 5 > 9 > 8 > 7.
Note, there are a few rules restricting what constitutes a valid unlock pattern:

Any given dot can only be used once (however you can cross back over a previously used dot, if you can connect to another unused dot on the other side)

Eg. 1 > 2 > 3 is valid, 2 > 1 > 2 is invalid, but 2 > 1 > 3 is valid (goes back over the 2, but doesn't re-include it in the actual code)

If your line crosses directly over a previously unused dot, it is automatically included in the code

Eg. Attempting to create a code of 1 > 3 > 4 would automatically become 1 > 2 > 3 > 4

What I remember about my specific lock pattern:

It used all 9 dots
The line representing the pattern has reflective symmetry
It is different to my previous pattern which also followed rules 1 & 2
My previous pattern looked like an alphanumeric character

What is current my lock pattern? What was my previous lock pattern?
For the purposes of this puzzle, we'll ignore the fact that there will be multiple "correct" answers achieved by simply rotating by multiples of 90 degrees. In other words a pattern of 1 > 2 > 3 will be considered identical to 3 > 6 > 9.
Edit: Given that Len found two valid solutions below, and neither was my intended solution, I've added an extension puzzle with an additional rule.

A:

Added 4th solution.
I think your previous pattern was:

 M which is also called impossible 3 ends shown below - 854693217

And you current pattern is one of:

 - a type of star left below - 857342619
 - or a geometric pattern center below - 851962473
 - or a modified M right below - 254693817

A:

 So your previous pattern looked like an alphanumeric character, used all 9 dots and was symmetrical. Alphanumeric characters: ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890. Out of these there are some asymmetric: FGJLNPQRSZ245679. That leaves us with: ABCDEHIKMOTUVWXY138.
 Now let's throw out the ones that can't fit using all 9 dots: ACDHIKOTUVXY1. This leaves us with: BEMW38. Because you will always have an "opening" in your pattern, we can throw out B and 8, so only possible answers are: EMW3. But E, M and W and 3 are actually same pattern, just turned 90 degrees, so your old pattern looked like E, so most probably that Impossible 3-Ends: 854693217

So now we should find your current pattern:

 Because we only know that it is symmetric and uses all 9 dots we can assume the following pattern to be your current one: gonna find it out soon and update my answer


Q:

Passing data into database with PHP

I am new to programming.
Today, I started learning some mysqli so I can make a login form for my "practising site", but I have a problem. If you check down the code you will understand what I want to do.
So any help? Because this doesn't work. It doesn't pass the data I enter in the form. And, is that a correct way to do it and if no which way is more professional? Thanks in advance.
<form action = "<?php $_PHP_SELF ?>" method ="POST">
 Username: <input type ="text" name = "username"/> </br>
 Password: <input type ="password" name = "password"/> </br>
 Email: <input type = "text" name = "email"/> </br>
 <input type = "button" value = "Submit"/>
</form>

<?php

ini_set('display_errors', '1');

   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $dbname = 'dbtesting';
   $username = $_POST["username"];
   $password = $_POST['passsword'];
   $email = $_POST['email'];

   $query = "INSERT INTO mywebpageusers (username, password, email)
             VALUES ('$username', '$password', '$email')";

   $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

   if($conn->connect_error > 0)
   {
    die ('Could not connect to database [' . $conn->connect_error . ']');
   }
   echo 'Connected succesfully!!';

  $conn->query($query);

?>

A:

You have some errors:

Forgot the function "echo"
$_PHP_SELF is not a PHP variable, it should be $_SERVER['PHP_SELF'], it's better if you use $_SERVER['SCRIPT_NAME'].
Wrong submit button's type: type="submit"
"$conn->connect_error" is a string, when you compared with 0, it will become 0 => (0 > 0) will return false, so the function "die" never execute
 <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method ="POST">
 Username: <input type ="text" name = "username"/> </br>
 Password: <input type ="password" name = "password"/> </br>
 Email: <input type = "text" name = "email"/> </br>
 <input type = "submit" value = "Submit"/>
</form>

<?php

ini_set('display_errors', '1');

   $dbhost = 'localhost';
   $dbuser = 'root';
   $dbpass = '';
   $dbname = 'dbtesting';
   $username = $_POST['username'];
   $password = $_POST['passsword'];
   $email = $_POST['email'];

   $query = "INSERT INTO mywebpageusers (username, password, email)
             VALUES ('$username', '$password', '$email')";

   $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
   var_dump($conn->connect_error); //You can debug variables by var_dump function
   if ($conn->connect_error) {
       die('Could not connect to database ['.$conn->connect_error.']');
   }
   echo 'Connected succesfully!!';

  $conn->query($query);

?>

Hope this help. This code is enough for practise.


Q:

Using javascript to get the values of multiple fields and add them to a table

I'm creating a script that takes the values of the fields and places them into a table for verification.  The thing is though, the user is able to add multiple fields(up to 5) and each field has its own id.  So, when a user inputs the values I want my script to take all the values from that field(even if they've added) and pass them into the table.  How would I go about doing this?
User adds one 'set', clicks add chart

User adds another 'set'(up to 5).

When the user has added all the 'sets' he/she wants, They appear in the Jeppeson Charts section.

I need to get these values

Jeppeson Charts

    <fieldset>
        Airport Identifier
        <input type="text" name="air_id_1" id="air_id_1" />
    </fieldset>
    <fieldset>
        Chart Identifier
        <input type="text" name="chart_id_1" id="chart_id_1" />
    </fieldset>
    <fieldset>
        Chart Description
        <input type="text" name="chart_desc_1" id="chart_desc_1" />
    </fieldset>

Allows the user to add up to 5 different charts.
var jep_num = 1;
    $("#add_chart").on("vclick", function(ev){
        jep_num += 1;
        if(jep_num <= 5){
            $("#charts").append("<fieldset><input type='text' name='air_id_" +jep_num +"' id='air_id_" +jep_num +"' /></fieldset><fieldset style='margin-left: 0.45%'><input type='text' name='chart_id_" +jep_num +"' id='chart_id_" +jep_num +"' /></fieldset><fieldset style='margin-left: 0.4%'><input type='text' name='chart_desc_" +jep_num +"' id='chart_desc_" +jep_num +"' /></fieldset>").trigger("create");
        }
        ev.preventDefault();
    })

Table where the charts need to be added

JEPPESON CHARTS

I hope I made sense with my rambling.  If not, let me know and I'll try to clarify.  I also know how to do this using MySQL and PHP, and I was hoping to avoid doing so with this particular feature.  But, if I need to I will.

A:

You should add a class to each field and the added ones too. Also you need to wrap all three related fieldset in one div.

Jeppeson Charts

        <fieldset>
            Airport Identifier
            <input class="air-input" type="text" name="air_id_1" id="air_id_1" />
        </fieldset>
        <fieldset>
            Chart Identifier
            <input class="chart-input" type="text" name="chart_id_1" id="chart_id_1" />
        </fieldset>
        <fieldset>
            Chart Description
            <input class="chart-desc-input" type="text" name="chart_desc_1" id="chart_desc_1" />
        </fieldset>

Then you can go through all of your sets one by one and get the values like that and then do what you want with them:
$('.charts-fieldset').each(function () {
    var air = $('.air-input', $(this)).val();
    var chart = $('.chart-input', $(this)).val();
    var chartDesc = $('.chart-desc-input', $(this)).val();
});


Q:

Sorting and Searching DataTables after refreshing table

BACKGROUND:
I have a small jquery app that contains widgets. There are 2 types of widgets in this app and they are counter widgets and grid widgets. For grid widgets i am utilizing dataTables.
My app basically connects to a server and recieves various information such as widget names and values for the counter and grid widgets. So based on the information received i dynamically create pages for each widget. Things are working fine at the moment but i am facing a little problem.
Problem
The issue i have right now is to do with my grid widgets which utilize dataTables api.From my server I receive the grid information in this format.
**//EXAMPLE INPUT
/*
<?xml version="1.0" encoding="UTF-8"?>
<rows>

        <column width="55" type="ro" align="left" sort="str">Player</column>
        <column width="55" type="ro" align="left" sort="str">State</column>
        <column width="55" type="ro" align="left" sort="str">Points</column>

     <row id="1">
        <cell>Lebron King James</cell>
        <cell>Best Mode</cell>
        <cell>45</cell>
     </row>
</rows>
*/**

I then parse this and insert it in the tables. The problem is i am doing a update every 3 seconds since the data for grid gets updated in real time . So when i do a update my search filter and sorting is reset.
So for example below if i am sorting by highest points
PLAYER         POINTS
KING JAMES     45
DERRICK ROSE   30

UPDATE HAPPENS AND MY SORTING WILL GET REST TO THIS

PLAYER         POINTS
DERRICK ROSE    30
KING JAMES      45

MY HTML CODE

    <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org" />
    <title>
      NBA Fanatico
    </title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="themes/tdMobile.min.css" type="text/css" />
    <link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" type="text/css" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="cssfinal/style.css" />

    <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />

                Basketball Fanatico

          <form method="get">

              <input type="text" name="username" placeholder="Username" />

              <input type="password" name="password" id="txtId" placeholder="Password" />

              LOGIN

          </form>

          Basketball Fanatico

WELCOME!

Use the menu on the left to navigate

            and configure the various options.

          Navigation

        <input id="chkSort" type="checkbox" checked="true" />Allow sorting

        LOG OUT

MY JS
var widgetNames = new Array();
var widgetId = new Array();
var pageId = ''

$(document).on("pagecreate", function () {
    $("body > [data-role='panel']").panel().enhanceWithin();
});

$(document).on('pagecreate', '#page1', function () {
    $("#log").on('click', function () {
        $.ajax({
            url: "script.login",
            type: "GET",
            data: {
                'page': 'create_user',
                'access': 'user',
                'username': $("input[name='username']").val(),
                'password': $("input[name='password']").val()
            },
            dataType: "text",
            success: function (html) {
                widgetNames = new Array();
                widgetId = new Array();
                var res = html.match(/insertNewChild(.*);/g);
                //Get each widget name and ID and assign to values in an array
                for (var i = 0; i < res.length; i++) {
                    //alert(res[i]);
                    var temp = res[i].split(',');
                    if (temp.length >= 3) {
                        widgetNames[i] = (temp[2].replace('");', '')).replace('"', '');
                        widgetId[i] = temp[1].replace("'", "").replace("'", "").replace(/ /g, '');
                    }
                }
                var AllWidgets = ''
                var testwidget = new Array();
                //Loop through the html returned and get the data relevant to each widget... save in temp array
                var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
                for (var i = 0; i < tempWidgetContent.length; i++) {
                    var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{') + 1);
                    testwidget[i] = widgetContent.replace("site +", "");
                    //replace the code for a grids...
                    if (testwidget[i].indexOf('grid') > 0) {
                        testwidget[i] = CreateGridUpdateFunction(testwidget[i], i);
                    }
                }

                var widgetPart = new Array();
                //Assume we have widget names, ids, and loading data in 3 arrays
                //Loop through and create the necessary page.
                for (var i = 0; i < widgetNames.length; i++) {
                    if (testwidget[i].indexOf('hi') > -1) {
                        //Header FOR grid Widget Page
                        var pageHeaderPart = "

Basketball Fanatico

";
                    } else {
                        //Header For Counter Widget Page
                        var pageHeaderPart = "

Basketball Fanatico

";
                    }

                    //Footer for all Widget Pages
                    var pageFooterPart = "

";

                    if (testwidget[i].indexOf('hi') > -1) {
                        //Grid Page widget title
                        var check = "

" + widgetNames[i] + "";
                    }

                    //Counter Page widget title
                    var check = "

" + widgetNames[i] + "
";

                    if (testwidget[i].indexOf('counterValue') > 0) {
                        //Counter Content (actual value of the counter widget)
                        widgetPart[i] = '

';

                    }
                    if (testwidget[i].indexOf('hi') > -1) {
                        //Grid content(actual values for the grid widget)
                        widgetPart[i] = '

';
                    } else {

                        //Miscalenous content(these are counter widgets that will contain text messages for now just putting "i dont know what i am")
                        widgetPart[i] = '
I dont know what I am
';
                    }

                    AllWidgets += '' + widgetNames[i] + '';
                    var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
                    makePage.appendTo($.mobile.pageContainer);
                }
                $('#items').prepend(AllWidgets).trigger('create');

                //Widget Update Function
                function UpdateActivePage() {
                    //get active page
                    pageId = $(":mobile-pagecontainer").pagecontainer('getActivePage').prop("id");
                    //figure out index
                    var idx;
                    for (var i = 0; i < widgetId.length; i++) {
                        if (widgetId[i] == pageId) {
                            idx = i;
                            break;
                        }
                    }

                    eval(testwidget[idx]);
                    $("#widgetContainer_" + pageId).html(counterValue);

                    $('#grid_' + idx).dataTable({
                        "bPaginate": false,
                        "bFilter": true,
                        "bAutoWidth": false,
                        "oLanguage": {
                            "sSearch": ""
                        }
                    });
                    $('.dataTables_filter input').attr("placeholder", "Search");
                    $('.dataTables_filter').css('float', 'none');
                    $('.dataTables_filter').css('padding-right', '0px');
                    $("#example_filter").detach().prependTo('#header1');
                }

                function CreateGridUpdateFunction(oldUpdatefunction, thisWidgetID) {
                    var updateLines = oldUpdatefunction.split("\n");
                    var updateFunctionCode = "";
                    for (var i = 0; i < updateLines.length; i++) {
                        if (updateLines[i].indexOf(" var url = ") > 0) {
                            //alert(updateLines[i]);
                            //    updateFunctionCode = " try { ";
                            var updateURL = updateLines[i];
                            if (updateURL.indexOf("&windowWidth=") > 0) {
                                updateURL = updateURL.substr(0, updateURL.lastIndexOf("&windowWidth=")) + "';";
                                //console.log(updateURL);
                            }
                            updateFunctionCode += updateURL;
                            updateFunctionCode += "   var loader = dhtmlxAjax.getSync(url);";
                            updateFunctionCode += "   if(loader.xmlDoc.responseText.length > 0){";
                            updateFunctionCode += "     counterValue = createTableStringFromXML(loader.xmlDoc.responseText," + thisWidgetID + ");";
                            updateFunctionCode += "   }   ";
                        }
                    }
                    return "var counterValue = \"hi\"; " + updateFunctionCode;
                }

                $(":mobile-pagecontainer").on("pagechange", function () {
                    UpdateActivePage();
                })

                setInterval(UpdateActivePage, 3000);
            }
        });
    });
});

 //Returns a bool indicated if the (space trimmed) string starts with needle.
function startsWith(searchString, searchVal) {
    var search = searchString.trim();
    return search.indexOf(searchVal) >= 0;
}

function createTableStringFromXML(serverXML, thisWidgetID) {
    //EXAMPLE INPUT
    /*
        <?xml version="1.0" encoding="UTF-8"?>
        <rows>

                <column width="55" type="ro" align="left" sort="str">Player</column>
                <column width="55" type="ro" align="left" sort="str">State</column>
                <column width="55" type="ro" align="left" sort="str">Points</column>

            <row id="1">
                <cell>Lebron James</cell>
                <cell>Injured</cell>
                <cell>25 </cell>
            </row>
        </rows>
    */
    console.log(serverXML);
    //PARSE THE ABOVE XML STRING to required FORMAT
    var xmlLines = serverXML.split("\n");
    var returnTable = "";

    for (var i = 0; i < xmlLines.length; i++) {
        if (startsWith(xmlLines[i], "<rows")) {
            returnTable += "
";
        } else if (startsWith(xmlLines[i], "</rows>")) {
            returnTable += "

";
        } else if (startsWith(xmlLines[i], "")) {
            returnTable += "

";
        } else if (startsWith(xmlLines[i], "")) {
            returnTable += "

";
        } else if (startsWith(xmlLines[i], "<column")) {
            returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + "	";
        } else if (startsWith(xmlLines[i], "<row")) {
            returnTable += "
";
        } else if (startsWith(xmlLines[i], "</row")) {
            returnTable += "
";
        } else if (startsWith(xmlLines[i], "<cell")) {
            returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + "	";
        }
        console.log(returnTable);
    }
    return returnTable;
}

Please advice on how to fix this i have been stuck on this for one week now almost i am sorry if this question is bad as i am only few months new to js and html and web development in general. I apologize for my poor English also.
UPDATED CODE BY EZ
See comments that start with //EZ:
                function UpdateActivePage() {
                    //get active page
                    pageId = $(":mobile-pagecontainer").pagecontainer('getActivePage').prop("id");
                    //figure out index
                    var idx;
                    for (var i = 0; i < widgetId.length; i++) {
                        if (widgetId[i] == pageId) {
                            idx = i;
                            break;
                        }
                    }
                    eval(testwidget[idx]);

                    if (counterValue == false) {
                        //EZ: no need to recreate datatable
                        return;
                    } else {
                        $("#widgetContainer_" + pageId).html(counterValue);

                        $('#grid_' + idx).dataTable({
                            "bPaginate": false,
                            "bFilter": true,
                            "bAutoWidth": false,
                            "oLanguage": {
                                "sSearch": ""
                            }
                        });
                        $('.dataTables_filter input').attr("placeholder", "Search");
                        $('.dataTables_filter').css('float', 'none');
                        $('.dataTables_filter').css('padding-right', '0px');
                        $("#example_filter").detach().prependTo('#header1');
                    }
                }

function createTableStringFromXML(serverXML, thisWidgetID) {
    //EXAMPLE INPUT
    /*
        <?xml version="1.0" encoding="UTF-8"?>
        <rows>

                <column width="55" type="ro" align="left" sort="str">Player</column>
                <column width="55" type="ro" align="left" sort="str">State</column>
                <column width="55" type="ro" align="left" sort="str">Points</column>

            <row id="1">
                <cell>Lebron James</cell>
                <cell>Injured</cell>
                <cell>25 </cell>
            </row>
        </rows>
    */
    console.log(serverXML);
    //PARSE THE ABOVE XML STRING to required FORMAT
    var xmlLines = serverXML.split("\n");
    var returnTable = "";

    //EZ: See if table already exists
    if ( $("#grid_" + thisWidgetID).length > 0){
        //EZ: update table using the datatables API...

        //EZ: then return false
        return false;
    } else {

        for (var i = 0; i < xmlLines.length; i++) {
            if (startsWith(xmlLines[i], "<rows")) {
                returnTable += "
";
            } else if (startsWith(xmlLines[i], "</rows>")) {
                returnTable += "

";
            } else if (startsWith(xmlLines[i], "")) {
                returnTable += "

";
            } else if (startsWith(xmlLines[i], "")) {
                returnTable += "

";
            } else if (startsWith(xmlLines[i], "<column")) {
                returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + "	";
            } else if (startsWith(xmlLines[i], "<row")) {
                returnTable += "
";
            } else if (startsWith(xmlLines[i], "</row")) {
                returnTable += "
";
            } else if (startsWith(xmlLines[i], "<cell")) {
                returnTable += "" + xmlLines[i].match(/>(.*?)</i)[1] + "	";
            }
            console.log(returnTable);
        }
    }
    return returnTable;
}

A:

Datatables has a rich api (http://datatables.net/api) that provides for adding, deleting, and updating rows while keeping the sorting. In your case, the new data might require deleting rows that are no longer in the XML, updating existing rows, and adding new rows that are in the XML but not in the table.
Probably the easiest thing would be to call fnClearTable to remove all current rows and use fnAddData to add all the rows in the XML:
var oTable = $('#example').dataTable();
oTable.fnClearTable();

$xml.find("row").each(function(index){
    var $cells = $(this).find("cell");
    var c1 = $cells.eq(0).text();
    var c2 = $cells.eq(1).text();
    var c3 = $cells.eq(2).text();

    oTable.fnAddData( [c1, c2, c3]);
});

DEMO


Q:

Minimize or collapse a bootstrap 2.3.2 modal dialog?

Are there a way to add a minimize feature to bootstrap modal dialogs?

          ×

          Close
          Save changes

I'm using it like a static draggable dialog:
   $('#testModal').modal({backdrop:false})
   $('#testModal').draggable({handle: ".modal-header"});

Maybe I'm using a wrong widget for that, but what else?
By minimize I mean that, minimize or collapse the dialog like a little
window widget.
Jquery-ui dialogs have a feature like that: http://jsbin.com/ehagoy/154
Why a -1?

A:

Maybe something like:
$(".modal-header").click(function(){
    $(".modal-body").slideToggle();
  });

Could help you..
if you want a button for that, only change .modal-header for the button id:
$("#mybutton").click(function(){
    $(".modal-body").slideToggle();
  });


Q:

Combine multiple values into one cell in Postgres

I have a data set that can multiple rows with the same claim no. and different names:
   claim_id           name
    112               John Smith
    112               Tom Harris
    113               Randy Dugar

If the claim id is the same, then I need all the names to be in one row separated by a comma:
    claim_no          name
    112               John Smith, Tom Harris
    113               Randy Dugar

I've created something similar in T-SQL, but am new to Postgres.  I've tried something like the following, but I just get an error:
   with firstrun as(
   select distinct kia.claim_id as claim_id,  c.first_name ||' '
   ||c.last_name as name
   from kia
   inner join
   claims c
   on kia.claim_id = c.claim_id

   )

   select distinct claim_id, substring((Select ',' || ' '|| fr.name as   text()]
   from firstrun fr
   for xml path('')), 2, 500)

A:

The string_agg aggregate function will do all the heavy lifting for you:
SELECT   claim_id, STRING_AGG(name, ', ')
FROM     claims
GROUP BY claim_id


Q:

Vertically center parent div on page

I know vertical alignment is tricky and there are plenty of questions about it on stackoverflow... I have been trying to figure this out for a few hours, with no success, so decided to ask it (apologies if it is a duplicate)
I have created a login page for my website.
There are 2 main divs in the body, one for logo and one for login content. The login content, has 2 sections, one for email and password and one for social media login.

 My Logo goes here

Is there a way to always vertically center the login div? I want the logo to stay on the top, but the login div be vertically centered. I know I can assign a height to the div and center it's content, but I don't know how to determine the height as the screen size will change...
this is how it looks like, as you see there is a big gap at the bottom.

A:

You can try flex like this :

body {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  text-align:center;
}

.logo {
  border: 1px solid red;
  min-height: 30px;
}

.login {
  flex: 1;
  border: 1px solid red;
  display: flex;
  flex-wrap: wrap;
  align-content: center;
}

#loginForm,
#SocialLoginForm {
  min-height: 45px;
  border: 1px solid green;
  flex: 0 0 100%;
}

    My Logo goes here

Login content

 social login content


Q:

Functional Requirements for the ultimate web development framework?

With the wide variety of web development frameworks that are available, there always seems to be a perpetual incentive to "try something new".  Hence, some of us find ourselves trading one framework for another, never being entirely satisfied with the end results.  Granted there will always be niches where a given web framework will serve perfectly.  But, there are many who have settled on using C++, Java or C# for building, say, desktop applications.  The same isn't quite true when it comes to web development applications.  Joel Spolsky touches on this in link text.
Let's say if I were to build such a framework: what would the functional requirements be?  The goal here is to list concrete functional expectations (defined succinctly for the sake of a stackoverflow posting, of course).  The best answer will be chosen based on its number of votes.
Just to get everyone started, the following would is a partial list of requirements.  Note, these items were intentionally left somewhat abstract with the intent that folks can derive more concrete items from them:

OOP Consistency: Seamless data exchange and native object representation between server-side and client-side modules:  That is, given a function on the client-side:  clientFoo() and a function on the server-side: serverFoo() one should be able to pass an object obj of any type T without requiring any marshalling:
define clientFoo() {
    T obj = createObject()
    serverFoo(obj)
}

OR

define serverFoo() {
    T obj = createObject()
    clientFoo(obj)
}

This adds the requirement that native object representations must be the same on both the client and server side, including all composition, inter-class coupling, and encapsulation semantics.  Basically, it should be entirely irrelevant whether a given class or a given instance resides on the client-side or the server-side.

Functional Consistency: Seamless functional and thread execution:  One should be able to create a function on the client/server side and pass it over the boundary for execution.  This includes uniform support for multi-threading (which should work consistently on both the client and server sides).

Multiple Application Session Interoperability:  A perfect example here is inter-application "cut and paste" (as mentioned in the article pointed out above).  I am not talking about trivial copying of text within the browser to another browser instance (or tab).  What if one wants to paste say, a contact object in MySocialApp to YetAnotherSocialApp?  This kind of inter-application data exchange is important.
Consistent cross-Browser compatible UI: creating AJAX "dialog boxes", progress indicators, tabs, etc should all be achievable using an API that is as seamless with the rest of the framework as the client/server integration discussed above.  Oh, and yes, it has to work the same on all browsers (with browser distinctions being completely invisible to the developer).

A:

Personally, I think the next great web development framework will be "functional" in nature, i.e. it will use a functional language, and all of the views, controllers and such will be functional equivalents.  We've already moved in this direction with Linq.
See Beating the Averages by Paul Graham, in which he describes how he was able to outsmart his competitors by building his web applications in Lisp: http://www.paulgraham.com/avg.html


Q:

How to remove unwanted file from git

I have pushed a branch without noticing the changes made under the branch. There is  a file named \ in my remote branch. I have used git rm \ .. But no luck.Please help me to remove the file.
Thanks

A:

The backslash is very likely to be used as an escape character by your shell. To pass an actual backslash to the command line of a program, most shells allow you to escape it itself or use quotes to tell the shell not to interpret it specially.
git rm \\
git rm '\'


Q:

Pull out numbers from a mixture of numbers + string of words

I need to pull out specific numbers from a text file that has a combination of numbers and text strings. The text file looks like this:
# General info User: b_stone, time: Sat Oct 21 16:10:03 2017 # Temperature C # Counters sec=60, Monitor=2.28666e+07, bstop=5.63852e+06, I0=7.33642e+06, I1=0, ch5=0, ch6=0, ch7=0, TEMP=-1, ICRxT=1, OCRxT=1, ROI1=1, ROI2=1, ROI3=1, ROI4=1, ROI5=1, ROI6=1, ccd1=0 # Motors goniy=40.7889, samplez=150, phi=-15.2418, th=0, detx=20.75, dety=4.7, detz=200, platz=0, m8=0, m9=0, m10=0, m11=0, dethorz=-5.10603, detvert=-31.6, detzold=879.936, m15=0, t1v=0, b1v=0, l1h=0, r1h=0, t2v=1.15812, b2v=-1.00813, l2h=1.24, r2h=-0.94, gshorz=4.50913, gsvert=0, stagey=-967.21, stagex=-102.567, bsvert=0, bshorz=0.24, samplex=-8, sampley=2.22, bpm=10090, monbend=330, monslit=9.29845, monang=-12, m0pitch=4.24658, m0vert=1.3622, m0bend=19.4294, m39=189.405, tablev1=39.7621, tablev2=59.9162, thor=1.09867, tableya=1.2001, bsv=24.3409, bsh=2.005, stagex1=1.95228, stagey1=3.07772, h1gap=0, h1tran=0, v1gap=0, v1tran=0, h2gap=0.3, h2tran=-1.09, v2gap=0.15, v2tran=1.0831, table=49.8391, tablep=0.01167, tempset=25

What I'd like to do is to look at "Monitor=2.28666e+07" (see the second line in the big string of texts) and just pull out "2.28666".
I knew how to do this in matlab, but I don't know how to convert the code to python.
This is the matlab code that used to work
%Extract the monitor value from .txt file generated
k=sprintf('txt_files/MnO2_20170515_2_05151339_%04d.txt',i);
filetext=fileread(k);
numbers = str2double(regexp(filetext, '(?<=Monitor=[^0-9]*)[0-9]*\.?[0-9]+', 'match'));
MV = numbers; %Monitor value, I scale up the MV by 10^6
%save monitor values into vector m
m(i)=MV;

I want to do the same thing in python, and expect the output to be 2.28666.

A:

Python provided for you re as a standard regex lib, you can try this code for your problem.
>>>import re
>>>s = 'General info User: b_stone, time: Sat Oct 21 16:10:03 2017 # Temperature C # Counters sec=60, Monitor=2.28666e+07, bstop=5.63852e+06, I0=7.33642e+06, I1=0, ch5=0, ch6=0, ch7=0, TEMP=-1, ICRxT=1, OCRxT=1, ROI1=1, ROI2=1, ROI3=1, ROI4=1, ROI5=1, ROI6=1, ccd1=0 # Motors goniy=40.7889, samplez=150, phi=-15.2418, th=0, detx=20.75, dety=4.7, detz=200, platz=0, m8=0, m9=0, m10=0, m11=0, dethorz=-5.10603, detvert=-31.6, detzold=879.936, m15=0, t1v=0, b1v=0, l1h=0, r1h=0, t2v=1.15812, b2v=-1.00813, l2h=1.24, r2h=-0.94, gshorz=4.50913, gsvert=0, stagey=-967.21, stagex=-102.567, bsvert=0, bshorz=0.24, samplex=-8, sampley=2.22, bpm=10090, monbend=330, monslit=9.29845, monang=-12, m0pitch=4.24658, m0vert=1.3622, m0bend=19.4294, m39=189.405, tablev1=39.7621, tablev2=59.9162, thor=1.09867, tableya=1.2001, bsv=24.3409, bsh=2.005, stagex1=1.95228, stagey1=3.07772, h1gap=0, h1tran=0, v1gap=0, v1tran=0, h2gap=0.3, h2tran=-1.09, v2gap=0.15, v2tran=1.0831, table=49.8391, tablep=0.01167, tempset=25'
>>>a = re.findall(r'Monitor=(\d.\d+)', s)
>>>a
['2.28666']
>>>a[0]
'2.28666'


Q:

php: Create array with ojects or how to get rid off extra quotes symbols

I store some data in file, that looks like this
{"name":"name1","uuid":"uuid1"}
{"name":"name2","uuid":"uuid2"}

than with php I convert it to JSON with next code
$file = "someData.json";
$content = explode("\r\n", file_get_contents($file));

$output = array( 'someData' => array_values( array_filter($content) ) );

$output = json_encode($output);
echo $output;

in output i get object
[ " {"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"} " ]

instead of array with objects
[{"name":"name1","uuid":"uuid1"},{"name":"name2","uuid":"uuid2"}]

What is the best solution to get array with objects or just o delete those first and last quote sybols?

A:

thanks for helping. I'm not so good in php but even after getting rid of errors in your examples I make other decision. Now I echo pure JSON without any decoding/encoding in such primitive way:
$file = "file.json";
$content = file_get_contents($file);
$content = rtrim($content, ",\r\n");

$output = '
        {
            "someData": ['.$someData.']
        }
        ';


Q:

Parse a file using ANTLR4

I have a Lexer and a Parser called y86 Lexer and Parser which work as far as I know. But I have a file with y86 commands and I want to parse them using Java. So far I have code as follows.
y86Lexer y86 = null;
CommonTokenStream tokenStream = null;
y86Parser y86p = null;

try
{
    y86 = new y86Lexer(CharStreams.fromFileName("C:\\Users\\saigbomian\\Documents"
            + "\\LearnANTLR\\src\\sum.ys"));
    tokenStream = new CommonTokenStream(y86);
    y86p = new y86Parser(tokenStream);

}
catch (IOException e)
{
    log.error("Error occured while reading from file");
    e.printStackTrace();
}

I'm not sure how to do the parsing. I have seen people use something like y86Parser.CompilationUnitContext but I can seem to find that class. I have tried printing from the Listeners antlr creates but I don't know how to trigger these listeners

A:

For each rule ruleName in your grammar, the y86Parser class will contain a class named RuleNameContext and a method named ruleName(), which will parse the input according to that rule and return an instance of the RuleNameContext class containing the parse tree. You can then use listeners or visitors to walk that parse tree.
So if you don't have a compilationUnit method or a CompilationUnitContext class, your grammar probably just doesn't have a rule named compilationUnit. Instead you should pick a rule that you do have and call the method corresponding to that rule.


Q:

Codeigniter like search in several tables

Hello stackoverflow community.
I want to make automatic search, based on article title, to show last news about it. These news can be in one or several tables, we dont know for use. Here it is my code:
$search = 'any article title';
$Linkearray = array('title' => $search);
$Linkearray2 = array('text' => $search);
$this->db->or_like($Linkearray);
$this->db->or_like($Linkearray2);
$this->db->from('table1', 'table2');
$query = $this->db->get();

Then i try to show results on page by next code:
foreach ($query->result_array() as $row):
echo $row['title'];
endforeach;

The problem is, that it shows search results only from table1.
If i rewrite a line of code into:
$this->db->from('table1, table2');

I get an error 1052. If anyone has an idea how to solve it, please share it :)
Thanks in advance!

A:

And, here is solution:
$search = 'some word';
$Linkearray = array('table1.title' => $search,'table2.text' => $search);
$Linkearray2 = array('table2.title' => $search,'table2.text' => $search);
$this->db->or_like($Linkearray);
$this->db->or_like($Linkearray2);
$this->db->from('table1,table2');
$query = $this->db->get();

foreach ($query->result_array() as $row):
echo $row['title'];
endforeach;

This way - you will avoid 1052 error, and script will return data from both tables. Query generated in this case is:
SELECT *
FROM (`table1`, `table2`)
WHERE `table1`.`title` LIKE '%strokes%'
   OR `table2`.`text` LIKE '%strokes%'
   OR `table2`.`title` LIKE '%strokes%'
   OR `table2`.`text` LIKE '%strokes%'

However, it will return some duplicated results... Better query, or php manipulation of results... to get desired output.


Q:

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

I am trying to make a face tracker that combines Haar Cascade Classification with Lucas Kanade good feature detection. However, I keep getting an error that I cannot figure out what it means nor how to solve it.
Can anyone help me here?
Error:
line 110, in <module>
cv2.imshow('frame',img)
error: /build/buildd/opencv-2.4.8+dfsg1/modules/highgui/src/window.cpp:269:
error: (-215)size.width>0 && size.height>0 in function imshow

Code:
from matplotlib import pyplot as plt
import numpy as np

import cv2

face_classifier = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

# params for ShiTomasi corner detection
feature_params = dict( maxCorners = 200,
                       qualityLevel = 0.01,
                       minDistance = 10,
                       blockSize = 7 )

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors
color = np.random.randint(0,255,(100,3))

# Take first frame and find corners in it
ret, old_frame = cap.read()

cv2.imshow('Old_Frame', old_frame)
cv2.waitKey(0)
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
restart = True
#while restart == True:
face = face_classifier.detectMultiScale(old_gray, 1.2, 4)

if len(face) == 0:
    print "This is empty"

for (x,y,w,h) in face:
    focused_face = old_frame[y: y+h, x: x+w]

cv2.imshow('Old_Frame', old_frame)

face_gray = cv2.cvtColor(old_frame,cv2.COLOR_BGR2GRAY)

gray = cv2.cvtColor(focused_face,cv2.COLOR_BGR2GRAY)

corners_t = cv2.goodFeaturesToTrack(gray, mask = None, **feature_params)
corners = np.int0(corners_t)

print corners

for i in corners:
    ix,iy = i.ravel()
    cv2.circle(focused_face,(ix,iy),3,255,-1)
    cv2.circle(old_frame,(x+ix,y+iy),3,255,-1)

plt.imshow(old_frame),plt.show()

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

while(1):
    ret,frame = cap.read()
    frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # calculate optical flow
    p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, corners_t, None, **lk_params)

    # Select good points
    good_new = p1[st==1]
    good_old = corners_t[st==1]

    # draw the tracks
    print "COLORING TIME!"
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        print i
        print color[i]
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)
        if i == 99:
            break
    img = cv2.add(frame,mask)

    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)

cv2.destroyAllWindows()
cap.release()

A:

This error message

error: (-215)size.width>0 && size.height>0 in function imshow

simply  means that imshow() is not getting video frame from input-device.
 You can try using
cap = cv2.VideoCapture(1)

instead of
cap = cv2.VideoCapture(0)

& see if the problem still persists.

A:

I have the same problem, fix the ret in capture video
import numpy as np
import cv2

# Capture video from file
cap = cv2.VideoCapture('video1.avi')

while True:

    ret, frame = cap.read()

    if ret == True:

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cv2.imshow('frame',gray)

        if cv2.waitKey(30) & 0xFF == ord('q'):
            break

    else:
        break

cap.release()
cv2.destroyAllWindows()

A:

I had this problem.
Solution: Update the path of the image.
If the path contains (for example: \n or \t or \a) it adds to the corruption. Therefore, change every back-slash "" with front-slash "/" and it will not make create error but fix the issue of reading path.
Also double check the file path/name. any typo in the name or path also gives the same error.


Q:

filtering a list of strings using lambda

I have a list like,
old_list=["a_apple","b_banana","c_cherry"]

and I want to get new list using lambda.
new_list=["apple","banana","cherry"]

I tried but it doesn't work as I expected. here is what I wrote.
new_list=filter(lambda x: x.split("_")[1], old_list)

what is the problem ?

A:

Try this:
Python-2:
In [978]: old_list=["a_apple","b_banana","c_cherry"]

In [980]: new_list = map(lambda x: x.split("_")[1], old_list)

In [981]: new_list
Out[981]: ['apple', 'banana', 'cherry']

Python-3:
In [4]: new_list = list(map(lambda x: x.split("_")[1], old_list))

In [5]: new_list
Out[5]: ['apple', 'banana', 'cherry']


Q:

After Upgraded Android app , Not shown upgraded app in Android Market

I upgraded my app in Android Market but till now not reflected in Android Market. How many hours take to reflect updated app in Android Market.

A:

In India (which I think where you are), it may take any where around two to three hours.


Q:

Ruby Rspec outputs literal escape characters on windows

I'm following the ruby on rails tutorial: http://railstutorial.org/chapters/static-pages#top
I'm up to using rspec. Having installed the win32console gem, it outputs gibberish in the console, i assume it is outputting the ansi colour change codes:
>rspec spec/
?[31mF?[0m?[31mF?[0m

Finished in 0.34376 seconds
?[31m2 examples, 2 failures?[0m

1) PagesController GET 'home' should be successful
    Failure/Error: Unable to find C to read failed line
    ?[31mundefined method `get' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x22294e0>?[0m
?[90m    # ./spec/controllers/pages_controller_spec.rb:7:in `block (3 levels) in <top (required)>'?[0m

2) PagesController GET 'contact' should be successful
    Failure/Error: Unable to find C to read failed line
    ?[31mundefined method `get' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_2:0x2173d28>?[0m
?[90m    # ./spec/controllers/pages_controller_spec.rb:14:in `block (3 levels) in <top (required)>'?[0m

Any tips how to fix this?

A:

Ansicon works a treat!
http://adoxa.110mb.com/ansicon/index.html
Download, extract it somewhere, and do:
ansicon -i

Then close/reopen the command prompt. Sweet!


Q:

R barplot straight horizontal line

My code is below
data <-read.csv("Results_15Jan2015.csv")
PartNo <- data$PartNo
TotalTime <- data$TOTAL_TIME

mp <- barplot(height = TotalTime, main = "Plot of Total Time for different Part Numbers", xlab =   "Different Part Numbers", ylab = "Total Time (sec)", xlim = c(1,42), ylim = c(0,max(TotalTime)+30),
    col = rainbow(nrow(data)))
text(mp, par("usr")[3], labels = PartNo, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=.9)
abline(h=mean(TotalTime))

specify_decimal <- function(x, k) format(round(x, k), nsmall=k)
text(7.5,mean(TotalTime)+25, paste("Average =",specify_decimal(mean(TotalTime),3)))

2 Questions:
a) Why is my horizontal line not drawn all the way to the right of the plot? How to draw the horizontal line all the way to the right?
b) I have a total of 42 observations, see http://imgur.com/97qHaUq
   but the total number of bars shown is only 37, why? See http://imgur.com/dGj3WOt
I need to display all 42 bars in a single plot. how do I do that? thanks

A:

As MrGrumble said, dropping the xlim argument should solve both of your problems (the line and missing bars). It might not be straightforward what this argument does in barplot function, as you don't give x explicitly. See in this example:
x <-seq(15)

barplot(x,xlim=c(1,15))

abline(h=6)

Gives a graphic with issues similar to those you are having, whereas
x <-seq(15)

barplot(x)

abline(h=6)

Behaves "as expected"


Q:

Full text search with SPARQL queries in Amazon Neptune

Most SPARQL endpoints have some extensions allowing for full-text search. Can I do full-text searches with the Amazon Neptune SPARQL endpoint?

A:

As of October 2018, full text search is not supported out of the box in Neptune (Gremlin and SPARQL). I would recommend opening a support case with Neptune to get more info around when to expect this feature.

A:

Neptune integration with Elasticsearch has been release with version 1.0.2.1:

https://docs.aws.amazon.com/neptune/latest/userguide/engine-releases-1.0.2.1.html

Please refer to this answer for a more detailed explaination or check the official documentation.


Q:

Pandas: How to fill missing period/datetime values in a multiindex time series?

I have a multiindex dataframe where one of the indexes is a Period or DateTime. It has some missing values like the one below:
dt = pd.DataFrame(zip(['x']*4+['y']*4,
                      range(8),
                      list(pd.period_range('2020-08-02T00:00:00', '2020-08-02T03:00:00', freq='H'))*2)
                  ,columns=['a', 'b', 'd']).set_index(['a', 'd'])
dt = dt.drop([('x',pd.Period('2020-08-02 01:00', 'H')),
              ('y',pd.Period('2020-08-02 01:00', 'H'))])
dt

I'd like to fill the missing period values with NaN. The end result would be:

If I had a time series with a simple index, it would be easy: dt.resample('H').first(). How should I do it in this multi-index timeseries?

A:

According to your comment under Henry Yik, I assume that all time series are within the same range, so I guess you can use reindex and create the MultiIndex.from_product like:
dt_ = dt.reindex(pd.MultiIndex.from_product(
                    [dt.index.get_level_values('a').unique(),
                     pd.date_range(dt.index.get_level_values('d').min(),
                                   dt.index.get_level_values('d').max(),
                                   freq='H')],
                     names=dt.index.names))
print(dt_)
                         b
a d
x 2020-08-02 00:00:00  0.0
  2020-08-02 01:00:00  NaN
  2020-08-02 02:00:00  2.0
  2020-08-02 03:00:00  3.0
y 2020-08-02 00:00:00  4.0
  2020-08-02 01:00:00  NaN
  2020-08-02 02:00:00  6.0
  2020-08-02 03:00:00  7.0


Q:

Create Additional Curves Morphing Between 2 Input Curves

I'm wondering if there is a way to create multiple curve objects that morph between two input curve objects.
In the illustration below, the input would be curve 1 and 4. I'd like to automatically create curves 2 and 3. I'd like to be able to create around 30 curves in between the 2 input curves. I'm guessing this would need to be done by python scripting.

A:

This will work only if both initial and final morphing shape have the same number of vertex.
If they don't you can always add a few more to the one with the least vertex, if moving them in place is not too much of a hassle.
Then create one single curve, shape it as desired.
Add two new Shapekeys to it, one Basis and one with the desired final morphing shape.
Now make a few copies of the curve (non-linked clones), and on each one gradually increase the Value for the shapekey.
For an even constant morphing divide the percentage by the number of "snapshots" you plan to have.


Q:

Proxy for ajax calls using rake-pipeline-web-filters

I'm setting up my devel environment for an Ember.js app using rake-pipeline as described here.
During development, my html and javascript are served by webrick (rake-filter magic that I don't quite understand) on http://0.0.0.0:9292 and I have a REST service developed in php served by Apache on http://somename.local
My ajax calls from the client app are getting lost because of the browser's anti-cross-domain-ajax thing. How do I work around this issue?

A:

You can't configure the proxy directly in your Assetfile. You'll have to create a config.ru file and use the rackup command to launch the server.
Here's an example Assetfile:
input "app"
output "public"

And config.ru:
require 'rake-pipeline'
require 'rake-pipeline/middleware'
require "rack/streaming_proxy" # Don't forget to install the rack-streaming-proxy gem.

use Rack::StreamingProxy do |request|
  # Insert your own logic here
  if request.path.start_with?("/api")
    "http://localhost#{request.path.sub("/api", "")}"
  end
end

use Rake::Pipeline::Middleware, 'Assetfile' # This is the path to your Assetfile
run Rack::Directory.new('public') # This should match whatever your Assetfile's output directory is

You'll have to install the rack and rack-streaming-proxy gems.


Q:

Getting rid of a for loop in R

I would like to sample a given vector with different sets of probabilities without a loop. Is there a way to do this?
For example in this code I would like to replace the loop with some sort of apply() structure or anything really ..
a <- c(1,2,3)
p <- matrix(c(.1,.1,.8,.1,.8,.1,.8,.1,.1), nrow=3)
s <- matrix(ncol=5, nrow=3)
for(i in 1:nrow(p)){
s[i,] <- sample(a, size=5, replace=T, prob=p[i,])
}

thanks for the help!

A:

apply on p itself:
t(apply(p, 1, sample, x=a, size=5, replace=TRUE))
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    1    3    3
[2,]    2    2    1    1    2
[3,]    1    1    1    1    1

Edit I had a functional::Curry in here, until flodel pointed out that it wasn't necessary, as apply gives an automatic curry by allowing named arguments via ....


Q:

CSS media queries to hide and show page elements .

I'm kind of new to coding with media queries, and I think I have painted myself into a corner, using too many media queries (and probably in the wrong way).
What I want to do is to hide some page elements when the width of the screen or device is smaller than 481px. So in the screenshot below, you might be able to see the couple of lines of text in the upper right corner.

My problem has to do with the media queries that I've used. I am at wit's end to figure out (1) why the page elements (those two lines of text in the upper right corner) are not disappearing when the page gets smaller than 481px OR (2) why they do not appear in any larger screen/device sizes when I do manage to get the page elements to disappear.
Here is the piece of CSS code that seems to cause some issues:
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px){
   /* Hiding elements for this device * * * * * * * * * * * * * */
   /*
      .poweredBy{
         display: none;
      }
   */
 }

With this code commented out, those two lines of text won't disappear until the window (device?) width is somewhere around 320px.

Here is the entire CSS:
/* Smartphones (portrait and landscape) ----------- */
    @media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
      .poweredBy{
          display: none;
      }
    }

/* Smartphones (landscape) ----------- */
    @media only screen and (min-width : 321px){
      .poweredBy{
          display: none;
      }
    }

/* Smartphones (portrait) ----------- */
    @media only screen and (max-width : 320px) {
        .poweredBy{
             display: none;
        }
    }

/* iPhone 4 ----------- */
    @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {}

    @media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {}

/* iPads (portrait and landscape) ----------- */
    @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {}

/* iPads (landscape) ----------- */
    @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {}

/* iPads (portrait) ----------- */
    @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {}

/* iPad 3 ---------------- */
    @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {}

    @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {}

/* Desktops and laptops ----------- */
    @media only screen and (min-width : 1224px) {}

/* 960px layouts ----------- */
    @media only screen and (min-width : 960px){}

/* Large screens ----------- */
    @media only screen and (min-width : 1824px) {}

I am using GroundworkCSS underneath, but I have added a few media queries myself -- that was most likely not an enlightened act on my behalf. So if anyone could point me in the right direction, I would be most grateful. Thanks.

A:

You have way to many media queries, the most you should have is three one for tablet, tablet landscape and mobile. Typically like this,
CSS
/** Mobile **/
@media only screen and (max-width: 767px), only screen and (max-device-width: 767px) {

}

/** Tablet **/
@media only screen and (min-width : 768px) and (max-width : 1024px) {

}

/** Tablet (landscape) **/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {

}

A:

The css code for portrait and landscape:
@media screen and (orientation:portrait) {
/* Style for portrait mode goes here */
}

@media screen and (orientation:landscape) {
  /* Style for landscape mode goes here */
}

Or, as written by Mitch Layzell,
 you can use this:
@media only screen and (max-width: 767px), only screen and (max-device-width: 767px) {
/** Mobile **/
}

@media only screen and (min-width : 768px) and (max-width : 1024px) {

}

/** Tablet (landscape) **/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/** Tablet **/
}

If you want you can insert "(orientation : landscape)" and "max-width" or "max-width-device" together.


Q:

'Filter by condition' Google Spreadsheet, filter by both included and excluded text

Is it possible to use the filter by condition filter to a the same time show text that contains the word "topic" but not the word "view".
For instance example.com/topic would be shown, but example.com/view/lorem/topic wouldnt be shown. Is that possible to do ?

A:

One solution would be to Filter by condition > Custom formula is :
=AND(SEARCH("topic",A:A),ISERROR(SEARCH("view",A:A)))
I suspect there might be a way of using a REGEXMATCH formula too


Q:

Navigation from a nested div

In my website I've created a layout in which a
 is a menu that lists some links ad a
 that acts as main page in where every link opened is shown.

Page1
Page2

This is the colmplete page and opens link in the targeted div (main) when clicked. The problem happens when I click a link that is positioned in the main
:
ClickMe.

This is not triggered in the same div, but it opens full page, like a target='_top', instead opening itself in the same , maintaining the menu on the left of the page itself. What I've to add in the script to have the links opened in the proper target?
Thanks in advance.

A:

Change .bind( to .live( in your jQuery.
That way it will act on all links, even ones that are added to the DOM after the script has run.  The way it is right now, it will only act on links that are in the DOM at the time the script was run.


Q:

Xcode added folder in blue and related there files are not compiling

From Xcode project right click and Add File to "projectName" there I created a NewFolder "ABCD" name and added to same "ABCD" empty folder to the project its in Blue colour, I expected its in Yellow Color,  What the files which I added inside Blue Colour folder files are not compiling in X-Code all files which  added in Blue Colour folder say file is not found after compiling the code.
Is there any why that default, I added folder are link related to the project?
Its very strange for me this issue, Your feedback is very helpful.

A:

If you simply drag drop a file and choose Create Folder reference, it will add as a blue folder.
Please make sure you select Create Groups from the pop dialogue and make sure u have selected all the targets in Add To Targets section.
Like this

It will be added as yellow

Group-> With groups, Xcode stores in the project a reference to each individual file. This can lead to problems:
Folder references-> Folder references are simpler. You can spot a folder reference because it shows up in blue instead of yellow.


Q:

Drupal webform with sortable report

I want the webform submitted report to be sortable (or filtered), suppose there is the "Country" field in the form with selectlist of Countries,
I must be able to filter the reports with specific value,suppose "USA" or something else.
Thank you.

A:

You could use Views to render a table view of fields (for Country, etc) and set the content filter of that view to pull only submitted webforms.


Q:

New Macbook Pro 2012 Operating System onto new SSD?

A friend has just bought a brand new Macbook Pro with Mountain Lion OS. We are going to install an SSD to replace the standard HD that it shipped with, however, it looks like Apple don't ship with the OS on DVD any more. They have informed him there is a backup of the OS on another partition of the drive that his MBP shipped with.
My question is, bearing in mind this MBP hasn't been used yet - there is nothing to back up, we just want to install his fresh OS on the new SSD drive, what is the best way to go about this?

A:

Macs that shipped with Lion or newer come with a recovery feature which is part of the EFI firmware, so that if the hard drive fails, or you install a new hard drive without OS X, the computer can start recovery directly from the internet over a broadband connection.
To start Recovery, hold down the Command + R keys while booting. The interface is pretty straightforward after that and you should be able to figure it out.
Apple also has as support article on OS X Recovery, and one on which models can support internet recovery through a firmware update.

A:

In addition to internet recovery mentioned by Alain, you can also install the recovery software to an external USB drive from a running Mac OS X installation with a Recovery HD partition.
To do this, you can download an assistant from this support page: http://support.apple.com/kb/DL1433