text:
Q: php - valid regEx expression in ereg_replace makes nothing I'm using PHP 5.2.17. I want to remove some surplus data from a JSON string and I've thought I can use some replace function to do so. Specifically I'm using ereg_replace with the next expression:
'^.*?(?=\"created_at)'

Which I've validated at http://www.regexpal.com. I've pasted my JSON string in there and the match is right. However, when I make the call:
$tweets = eregi_replace('^.*?(?=\"created_at)', $temp, 'something');

and then I echo the $tweets variable, there's output. No errors in console neither. Apache error log, however, complains about an error called REG_BADRPT. There's a comment in the php docs of eregi_replace suggesting this can be due to I need to escape special characters, but I've already escaped the " character. And I've tried to escape others but no different behavior.
Where could the problem be then?

A: I don't think that ereg supports lookarounds.  preg_replace exists in php 5.2, so you should really use that instead.  It will work with your expression with delimiters.
$tweets = preg_replace('@^.*?(?=\"created_at)@i', 'something', $temp);

A: As other people have pointed out, ereg functions are deprecated, so use preg_replace. You also have to encapsulate your regex string in slashes (/). You can put your regex flags after your last slash.


text:
Q: libgdx gwt install error eclipse I'm trying to make a libgdx Android project work (= build) on Eclipse. It's the project from the book "Libgdx Game Development" : I just opened the GDX set up GUI and created a project named "demo".
I get two errors about GWT in the "Problems" Tab, in the demo-html project :

*

*The project was not built since its build path is incomplete. Cannot find the class file for com.google.gwt.core.client.EntryPoint. Fix the build path then try building this project

2.The type com.google.gwt.core.client.EntryPoint cannot be resolved. It is indirectly referenced from required .class files
I have GWT Designer for GPE, Google Plugin for Eclipse and SDKS installed in the plug-in tab (from the Help > Install new Software), so I have no idea why it doesn't work.
All the questions that had those error messages were resolved by downloading the plug-ins I quoted, but in my case, they are downloaded and installed (can't re-install them since it tells me it is already installed) and I hit also already checked for updates.
Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android ajax loader I'm trying to do a ajax loader but it's not working in Android 1.5, this version doesn't support gif files.
Any sugestion? Thanks.

A: I resolved the problem using CSS3.
Pre-loader Animation in CSS3
Demo

A: Google is working on it...Apparently. but no luck, even on latest Android platforms


text:
Q: How can I create a large matrix without running into hangs or recursion errors? I'm trying to create a probability matrix, starting by creating a 100,000 by 100,000 identity matrix. However, when I try to create this using:
IdentityMatrix[100000]

The interpreter just stops without an error message or prompt, and the variables turn blue. Why does this happen and How can I get around it?

A: This happens because you asked Mathematica to allocate this amount of memory (unless told otherwise, Mathematica tries to allocate a packed array of 64 bit integers):
UnitConvert[100000^2 Quantity[64, "Bits"], "Gigabytes"]

Quantity[80, "Gigabytes"]

Might be a bit too much for your system.
Better use
IdentityMatrix[100000, SparseArray]

In general, I suggest to get in touch with SparseArray in order to learn how to construct sparse matrices efficiently.


text:
Q: Checkbox always "on" when sending to php I have this checkbox in my html
<input name="cb" class="cmn-toggle cmn-toggle-round" type="checkbox">

What I understood about how checkbox worked, was that when "checked" if you isset the input then it would "exist", and if wasn't "checked" wouldn't, so I did this:
if(isset($_REQUEST['cb'])){
   //do something
}else{
  //do something else
}

The problem is that when sending the form, it always exist, doesn't matter if checked or not, I don't know how to really see if really checked, so what am I doing wrong?

A: isset() determine if a variable is set and is not NULL. So in your case, the $_REQUEST['cb'] always exist, so isset() will be true. So if you have isset() in your condition, you need to add a check, if the value is true or false.
You need edit your condition to:
if($_REQUEST['cb']) { ...

or
if($_REQUEST['cb'] == true){ ...

and the best way is use isset with check above:
if( isset($_REQUEST['cb']) && $_REQUEST['cb'] == true ) { ...

A: You can check like this
if(isset($_REQUEST['cb']) && $_REQUEST['cb']){


text:
Q: Computing "average" of two colors This is only marginally programming related - has much more to do w/ colors and their representation.
I am working on a very low level app. I have an array of bytes in memory. Those are characters. They were rendered with anti-aliasing: they have values from 0 to 255, 0 being fully transparent and 255 totally opaque (alpha, if you wish).
I am having trouble conceiving an algorithm for the rendering of this font. I'm doing the following for each pixel:
            // intensity is the weight I talked about: 0 to 255
            intensity = glyphs[text[i]][x + GLYPH_WIDTH*y];
            if (intensity == 255)
                continue; // Don't draw it, fully transparent
            else if (intensity == 0)
                setPixel(x + xi, y + yi, color, base); // Fully opaque, can draw original color
            else { // Here's the tricky part
                // Get the pixel in the destination for averaging purposes
                pixel = getPixel(x + xi, y + yi, base);
                // transfer is an int for calculations
                transfer = (int)  ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.red + (float) pixel.red)/2); // This is my attempt at averaging
                newPixel.red = (Byte) transfer;
                transfer = (int)  ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.green + (float) pixel.green)/2);
                newPixel.green = (Byte) transfer;
                // transfer = (int) ((float) ((float) 255.0 - (float) intensity)/255.0 * (((float) color.blue) + (float) pixel.blue)/2);
                transfer = (int)  ((float)((float) (255.0 - (float) intensity/255.0) * (float) color.blue + (float) pixel.blue)/2);
                newPixel.blue = (Byte) transfer;
                // Set the newpixel in the desired mem. position
                setPixel(x+xi, y+yi, newPixel, base);
            }

The results, as you can see, are less than desirable. That is a very zoomed in image, at 1:1 scale it looks like the text has a green "aura".

Any idea for how to properly compute this would be greatly appreciated.
Thanks for your time!

A: You need to blend the background and foreground colours. A-la:
pixelColour = newColour * intensity + backgroundColour * (1 - intensity)

By the way, this is a really slow way of rendering and blending fonts. You should instead render all the characters of the font to an off-screen surface with all the properties you need, and then use that as a texture to render to other surfaces when you need text.
Edit:
This doesn't look right:
(255.0 - (float) intensity/255.0)

It should instead be:
(255.0 - (float) intensity)/255.0

A: I believe that "aura" is caused by anti aliasing. The technique averages pixels with their neighbors.
I realize you don't seem to be using OpenGL but this chapter might help explain some of the theory. Wish I had a better answer, but hopefully this points you in the right direction. My first attempt would be to disable Antialiasing since it seems to do more harm than good. There is probably a better solution than that though.

A: It may be too much complicated to doing alpha blending pixel by pixel because current pixel value modifies next pixel value.
I would redesign the algorithm with the thinking of box wise blending.

With many getPixel calling for a single glyph, you can't produce proper target image.


text:
Q: Firebase Dynamic Links not shortening URL I'm trying to get Dynamic Links to shorten my URL with the following code:
guard let link = URL(string: "https://myapp.com") else { return }
let dynamicLinksDomainURIPrefix = "https://app.myapp.com/link"
let linkBuilder = DynamicLinkComponents(link: link, domainURIPrefix: dynamicLinksDomainURIPrefix)
linkBuilder?.iOSParameters = DynamicLinkIOSParameters(bundleID: "com.myapp.ios")

guard let longDynamicLink = linkBuilder?.url else { return }
print("The long URL is: \(longDynamicLink)")

let options = DynamicLinkComponentsOptions()
options.pathLength = .short
linkBuilder?.options = options
linkBuilder?.shorten() { url, warnings, error in
  guard let url = url, error != nil else { return }
  print("The short URL is: \(url)")
}

It's printing the long URL fine, but the line below (for short URL) is never being called:
print("The short URL is: \(url)")

Because url returns nil and I have no idea why. Nothing I've found in the guides or online has lead me in the right direction.
What am I doing wrong??

A: I think it is because the following is incorrect:
guard let url = url, error != nil else { return }

You are saying make sure there is a non nil URL and make sure there is an error.
I think the Firebase docs are wrong. Instead, you want:
guard let url = url, error == nil else { return }

A: What you have done here :
linkBuilder?.shorten() { url, warnings, error in
  guard let url = url, error != nil else { return }
  print("The short URL is: \(url)")
}

is you are unwrapping the url and checking if error contains some Error, then you are printing 'The short URL is: (url)' it means if shorten() succeeds and there's no Error your print method will never be executed.
What you have to do is, First check if error doesn't contain any Error than call print()
linkBuilder?.shorten() { url, warnings, error in
  guard error == nil else { return }
  if let shortUrl = url {
      print("The short url is \(shortUrl)")
  }
}


text:
Q: Asking multiplication questions and computing the total of answers correct in Java The code should output a table for Farenheit and Celsius
public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |",          temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int)sum );
            System.out.printl

n();

A: You should do this all in one encompassing while loop.
the while loop pseudo code is like this:
string answer = "";
While (answer != quit)
{
answer = (ask question to user)
if (answer != quit)
   compute/display response
}

A: Looks like your braces are not opened and closed properly. Also the userScore and totalScore is reset in each iteration. So you will not have the proper score. Move it outside the loop.
import java.util.Scanner;

public class Multiplication {

    private static String question;
    private static Scanner input;
    private static Scanner scanner;
    private static int totalScore;
    private static int answer1;
    private static int userScore;

    public static void main(String[] args) {
        int number1;
        int number2;
        totalScore = 0;
        userScore = 0;
        input = new Scanner(System.in);
        do {
            number1 = (int)(Math.random() * 10);
            number2 = (int)(Math.random() * 10);

            System.out.print("What is " + number1 + " * " + number2 + "? ");
            int answer = input.nextInt();
            while (number1 * number2 != answer)
            {
                int answer1 = number1 * number2;
                System.out.println("Incorrect. The answer is " + answer1+".");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                totalScore++;
                break;
            }

            if (number1 * number2 == answer)
            {
                System.out.println("Correct. Nice work!");
                System.out.print("Want more questions yes or no? ");
                scanner = new Scanner (System.in);
                question = scanner.next();
                userScore++;
                totalScore++;
            }

        }while(question.equals("yes") || question.equals("y"));
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }
}

A Better Implementation
The code looks more readable here and few unnecessary lines of code are removed.
import java.util.Scanner;

public class Multiplication {

    private static final Scanner scanner = new Scanner (System.in);
    private static int totalScore = 0;
    private static int userScore = 0;
    private static int number1;
    private static int number2;
    private static int answer;

    public static boolean continueExe(){
        String question;
        System.out.print("Want more questions yes or no? ");
        question = scanner.next();
        return (question.equals("yes") || question.equals("y"));
    }

    public static void printOutput(){
        System.out.println("You have this many questions correct:" + userScore +" out of " + totalScore);
    }

    public static void askQuestion(){
        number1 = (int)(Math.random() * 10);
        number2 = (int)(Math.random() * 10);
        System.out.print("What is " + number1 + " * " + number2 + "? ");
    }

    public static void readAnswer(){
        answer = scanner.nextInt();
    }

    public static void isAnswerCorrect(){
        if (number1 * number2 != answer){
            System.out.println("Incorrect. The answer is " + number1 * number2 +".");
        }else{
            userScore++;
            System.out.println("Correct. Nice work!");
        }
        totalScore++;
    }

    public static void main(String[] args) {
        do{
            askQuestion();
            readAnswer();
            isAnswerCorrect();
        }while(continueExe());
        printOutput();
    }
}

A: Mistake was you opened '{' two times for 'if'statement -
if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer)){
{

and forgot to close one bracket in last line.
Below code solves error due to brackets:
import java.util.Scanner;

public class Program3_3 {

private static String question;
private static Scanner input;
private static Scanner scanner;
private static int totalScore;
private static int answer1;
private static int userScore;

public static void main(String[] args) {
do {
    int number1 = (int)(Math.random() * 10);
    int number2 = (int)(Math.random() * 10);
    totalScore = 0;
    userScore = 0;
    input = new Scanner(System.in);
    System.out.print("What is " + number1 + " * " + number2 + "? ");
    int answer = input.nextInt();
    while (number1 * number2 != answer) {
        int answer1 = number1 * number2;
        System.out.println("Incorrect. The answer is " + answer1+".");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        break;
     }

    if (number1 * number2 == answer){
        System.out.println("Correct. Nice work!");
        System.out.print("Want more questions yes or no? ");
        scanner = new Scanner (System.in);
        question = scanner.next();
        }
    if (question.equals("no")||question.equals("n")&& (number1 * number2 == answer))
    {
        userScore++;
        totalScore++;
          System.out.println("You have this many questions correct:" + totalScore);
       }
}
   while(question.equals("yes") || question.equals("y"));
    }
 }


text:
Q: Find first occurrence of a character before a keyword with Regex I'm trying to extract each first occurrence of a character before a keyword.
In the string below, the idea would be to extract the position of ">" just for lines that contain the word "Change", and should match 3 ">" on the 3 last lines.
Thing
Second Thing
Third Thing

Thing Change
Second Thing Change
Third Thing Change

I have a begin of answer, using look-alike operator, I'm currently able to extract text from the ">" to the "Change" Keyword, but I'm stuck to extract just the ">" properly
([^"]*(?=Change))

A: Use
>(?=.*?Change)

See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
  >                        '>'
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .*?                      any character except \n (0 or more times
                             (matching the least amount possible))
--------------------------------------------------------------------------------
    Change                   'Change'
--------------------------------------------------------------------------------
  )                        end of look-ahead


text:
Q: how to open camera in a tkinter frame and close only the frame/camera when needed I have a tkinter multi-frame application that involves multiple page/frames in one page I want to have a camera using open cv and the camera should close when I navigate to some other screen/page and should start automatically when the frames comes on screen or is in focus
the frame is comming when I navigate to a page but it is not closing and always running in the background when I use frame.quit() it closes the whole application but I only want to close that camera
The main class which controls navigation
import tkinter as tk
import connectionPage
import startPage
// it has more than 15 pages but for example I have removed others

class tkinterApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        self.frames = {}
        self.geometry(geometry)
        self.attributes("-fullscreen", True)
        StartPage=startPage.StartPage
        ConnectionPage=connectionPage.connect_page
        FrontCameraPage = frontCameraPage.FrontCameraPage
        for F in (StartPage, ConnectionPage,FrontCameraPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(startPage.StartPage)
    def show_frame(self, cont):
        frame = self.frames[cont]
        if hasattr(frame, 'refresh'):
            frame.refresh()
        frame.tkraise()

    def get_page(self, page_class):
        return self.frames[page_class]

if __name__ == "__main__":
    app = tkinterApp()
    app.mainloop()

my camera frame/page
class FrontCameraPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.label = tk.Label(self, text="FRONT CAMERA", font=MediumFont, bg="white").grid(row = 0,column = 0,columnspan=2, sticky = "nsew")
        self.cameraFrame = tk.Frame(self, bg=gray)
        self.cameraFrame.grid(row = 1,column = 0, sticky = "nsew")
        self.buttonFrame  = tk.Frame(self,bg = "white")
        self.buttonFrame.grid(row = 1,column = 1, sticky = "nsew",padx = (10,0))

        def end_trip():
            self.cameraFrame.quit()# right now i am using quit but it is closing whole applicaiton i just want to close camera

        self.Info = tk.Label(self.buttonFrame, text="FACE NOT\n DETECTED", font=MediumFont,bg = dark_red,fg ="white")
        self.Info.grid(row=0, column=0, ipadx=8,pady = (0,5))

        self.switchCamera = tk.Button(self.buttonFrame, text="SWITCH CAMERA", font=small_Font, bg=dark_blue, command=lambda: self.switch_camera(),fg ="white")
        self.switchCamera.grid(row=1, column=0, ipadx=5,pady = (0,5))

        self.endTrip = tk.Button(self.buttonFrame, text="END TRIP", font=small_Font, bg=dark_blue, command=pass = "White")
        self.endTrip.grid(row=2, column=0, ipadx=10,pady = (0,5))

        self.cancelButton = tk.Button(self.buttonFrame, text="Cancel", font=small_Font, bg=dark_blue, command=pass,fg="white")
        self.cancelButton.grid(row=3, column=0, ipadx=10)

    def refresh(self):
        time.sleep(1)
        width, height = 200, 200
        cap = cv2.VideoCapture(0)
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        lmain = tk.Label(self.cameraFrame)
        lmain.pack()

        def show_frame():
            _, frame = cap.read()
            frame = cv2.flip(frame, 1)
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            img = PIL.Image.fromarray(cv2image)
            imgtk = ImageTk.PhotoImage(image=img)
            lmain.imgtk = imgtk
            lmain.configure(image=imgtk)
            lmain.after(10, show_frame)
        show_frame()

the camera should close when I change the frame and go to another frame or click any button.

A: One of the way is to use virtual events to notify the camera frame when it is being switched in or out.
When the camera frame receives those virtual events, it can then start or stop the capturing based on the type of the event.
Below is the modified FrontCameraPage:
class FrontCameraPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        self.label = tk.Label(self, text="FRONT CAMERA", font=MediumFont, bg="white").grid(row = 0,column = 0,columnspan=2, sticky = "nsew")
        self.cameraFrame = tk.Frame(self, bg=gray)
        self.cameraFrame.grid(row = 1,column = 0, sticky = "nsew")
        self.buttonFrame  = tk.Frame(self,bg = "white")
        self.buttonFrame.grid(row = 1,column = 1, sticky = "nsew",padx = (10,0))

        self.Info = tk.Label(self.buttonFrame, text="FACE NOT\n DETECTED", font=MediumFont,bg = dark_red,fg ="white")
        self.Info.grid(row=0, column=0, ipadx=8,pady = (0,5))

        self.switchCamera = tk.Button(self.buttonFrame, text="SWITCH CAMERA", font=small_Font, bg=dark_blue, command=lambda: self.switch_camera(),fg ="white")
        self.switchCamera.grid(row=1, column=0, ipadx=5,pady = (0,5))

        self.endTrip = tk.Button(self.buttonFrame, text="END TRIP", font=small_Font, bg=dark_blue, fg = "White")
        self.endTrip.grid(row=2, column=0, ipadx=10,pady = (0,5))
        self.endTrip['command'] = self.stop_capture

        self.cancelButton = tk.Button(self.buttonFrame, text="Cancel", font=small_Font, bg=dark_blue, fg="white")
        self.cancelButton.grid(row=3, column=0, ipadx=10)
        self.cancelButton['command'] = lambda: controller.show_frame(startPage.StartPage)

        # setup callbacks for switching in and out events
        self.bind('<<SwitchIn>>', self.start_capture)
        self.bind('<<SwitchOut>>', self.stop_capture)

        self.capture = None  # task id for the capture loop

        # label for showing the captured image
        self.lmain = tk.Label(self.cameraFrame)
        self.lmain.pack()

    def start_capture(self, event=None):
        if self.capture is None:
            # create the capture object
            width, height = 200, 200
            self.cap = cv2.VideoCapture(0)
            self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
            self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
            # start the capture loop
            self.show_frame()
            print('capture started')

    def stop_capture(self, event=None):
        if self.capture:
            # stop the capture loop
            self.after_cancel(self.capture)
            self.capture = None
            # release the capture object
            self.cap.release()
            print('capture stopped')

    def show_frame(self):
        ret, frame = self.cap.read()
        if ret:
            frame = cv2.flip(frame, 1)
            cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
            img = Image.fromarray(cv2image)
            self.imgtk = ImageTk.PhotoImage(image=img)
            self.lmain.configure(image=self.imgtk)
        self.capture = self.after(10, self.show_frame)

And below is the modified tkinterApp:
class tkinterApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        ...

        self.frame = None # the current frame shown
        self.show_frame(startPage.StartPage)

    def show_frame(self, cont):
        if self.frame:
            # trigger the switching out handler of the frame
            self.frame.event_generate('<<SwitchOut>>')
        self.frame = self.frames[cont]
        self.frame.tkraise()
        # trigger the switching in handler of the frame
        self.frame.event_generate('<<SwitchIn>>')

    ...

Update: create self.cap inside start_capture() and release it inside stop_capture().


text:
Q: Get the size of a vector that is an element in a vector that is a pointer for(int i=0; i < synthesizer_->GetNotation()->size(); i++){
   for(int j=0; j < synthesizer_->GetNotation()[i]->size(); j++){}
}

I want to display the elements of a vector of vectors, row by row.
The error (right after [i]) is:
base operand of '->' has non-pointer type 'std::vector<std::vector<std::basic_string<char> > >'

GetNotation() returns a pointer to the vector of vectors.
I'm assuming the error is telling me the syntax is incorrect (but I'm not sure).
I don't know how else to access the contained vectors except by the index in a bracket. I've searched and can't find an explanation or code example.
protected: std::vector<std::vector<std::string> > notation_;
std::vector<std::vector<std::string> >* GetNotation(){return &notation_;}

A: If GetNotation() returns a vector* pointer (why not a vector& reference?), then you need to first dereference the pointer to access the vector being pointed at, before you then try to access the vector's operator[], eg:
for(size_t i = 0; i < synthesizer_->GetNotation()->size(); ++i){
   for(size_t j = 0; j < (*(synthesizer_->GetNotation()))[i].size(); ++j){
      // use (*(synthesizer_->GetNotation()))[i][j] as needed...
   }
}

Which would be much easier to manage and read if you call GetNotation() only one time and cache the result in a local variable, eg:
auto notation = synthesizer_->GetNotation();
for(size_t i = 0; i < notation->size(); ++i){
   auto &strings = (*notation)[i];
   for(size_t j = 0; j < strings.size(); ++j){
     // use strings[j] as needed...
   }
}

Alternatively:
auto &notation = *(synthesizer_->GetNotation());
for(size_t i = 0; i < notation.size(); ++i){
   auto &strings = notation[i];
   for(size_t j = 0; j < strings.size(); ++j){
     // use strings[j] as needed...
   }
}

That being said, you could use iterators instead of indexes:
auto notation = synthesizer_->GetNotation();
for(auto i = notation->begin(); i != notation->end(); ++i){
   auto &strings = *i;
   for(auto j = strings.begin(); j != strings.end(); ++j){
     // use *j as needed...
   }
}

In which case, you could use range-based for loops instead, eg:
for(auto &strings : *(synthesizer_->GetNotation())){
   for(auto &str : strings){
     // use str as needed...
   }
}


text:
Q: Create a simple PHP Array from this text I have this lovely chunk of text found inside an XML element and want to convert it into a simple array, the XML is from wikia.com.
The array would be something like this:
card name => [Martial] Ares, character name => Ares, release_date => May 1 2013 and so on..

I've tried all sorts of imploding and exploding variations but no luck.. This one has got me stumped..
|card name=[Martial] Ares
|character name=Ares
|release_date=May 1 2013
|image 1=MartialAres5.jpg
|rarity 1=Super Special Rare
|pwr req 1=28
|sale price 1=94200
|max card lv 1=60
|max mastery lv 1=40
|quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear.  But he can use any weapon expertly, and turn most ordinary objects into lethal weapons.
|base atk 1=2440
|base def 1=2650
|max atk 1=7015
|max def 1=7613
|mastery bonus atk 1=915
|mastery bonus def 1=993
|image 2=MartialAres6.jpg
|rarity 2=Ultimate Rare
|sale price 2=188400
|max mastery lv 2=200
|quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds.
|max atk 2=9822
|max def 2=10660
|mastery bonus atk 2=1098
|mastery bonus def 2=1192
|alignment=Bruiser
|ability=Warhawk
|gender=Male
|usage=Average
|faction=Super Hero
|effect=Significantly harden DEF of your Bruisers.
|centretrait=None

Code I've tried:
if (file_exists('card.xml')) {
    $xml = simplexml_load_file('card.xml');

    $text = $xml->page->revision->text;
    $newtext = explode('|', $text);
    foreach($newtext as $newnewtext) {
        $newtext2 = explode('=', $newnewtext);
        print_r($newtext2);

    }

} else {
    exit('Failed to open card.xml.');
}

A: as requested:
<?php
$file="|card name=[Martial] Ares
|character name=Ares
|release_date=May 1 2013
|image 1=MartialAres5.jpg
|rarity 1=Super Special Rare
|pwr req 1=28
|sale price 1=94200
|max card lv 1=60
|max mastery lv 1=40
|quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear.  But he can use any weapon expertly, and turn most ordinary objects into lethal weapons.
|base atk 1=2440
|base def 1=2650
|max atk 1=7015
|max def 1=7613
|mastery bonus atk 1=915
|mastery bonus def 1=993
|image 2=MartialAres6.jpg
|rarity 2=Ultimate Rare
|sale price 2=188400
|max mastery lv 2=200
|quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds.
|max atk 2=9822
|max def 2=10660
|mastery bonus atk 2=1098
|mastery bonus def 2=1192
|alignment=Bruiser
|ability=Warhawk
|gender=Male
|usage=Average
|faction=Super Hero
|effect=Significantly harden DEF of your Bruisers.
|centretrait=None";

$x=explode("\n",$file);
$out=array();
foreach($x as $each){
  $xx=explode('=',$each);
 $out[ltrim($xx[0],'|')]=$xx[1];
}
echo '<pre>';
print_r($out);

working demo: http://codepad.viper-7.com/3BkXD6

A: The simplest and most efficient way to achieve that is using regular expressions. Given that $string holds the data, do the following:
preg_match_all('/^\|(?<key>[^=]+)=(?<value>.*)$/m', $string, $matches);
print_r(array_combine($matches['key'], $matches['value']));

For the data you provided as an example you'll get:
Array
(
  [card name] => [Martial] Ares
  [character name] => Ares
  [release_date] => May 1 2013
  [image 1] => MartialAres5.jpg
  [rarity 1] => Super Special Rare
  [pwr req 1] => 28
  [sale price 1] => 94200
  [max card lv 1] => 60
  [max mastery lv 1] => 40
  ...and so on
)

A: This should work for you:
First explode() your string by a new line. Then go through each element with array_map() and explode the substr() with an offset of 1 by an equal sign.
At the end just use array_column() to use the first column as value and the 0 column as key.
$arr = array_column(array_map(function($v){
    return explode("=", substr($v, 1));
}, explode(PHP_EOL, $str)), 1, 0);

print_r($arr);

A: @Dagon is correct. This is how an implementation might look:
<?php
$keyvalues = array();
$text = file_get_contents('path/to/your/file');
$rows = explode('|',$text);
foereach($rows as $row) {
    if (strpos($row,'=')) {
        $kv = array_map('trim',explode('=',$row));
        $keyvalues[ $kv[0] ] = $kv[1];
    }
}
?>

A: First, I would split the string on the '|' charater.
$parts = explode("|", $str);
This will result in an array like the following:
    Array
    (
        [0] =>
        [1] => card name=[Martial] Ares

        [2] => character name=Ares

        [3] => release_date=May 1 2013

        [4] => image 1=MartialAres5.jpg

        [5] => rarity 1=Super Special Rare

        [6] => pwr req 1=28

        [7] => sale price 1=94200

        [8] => max card lv 1=60

        [9] => max mastery lv 1=40

        [10] => quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear.  But he can use any weapon expertly, and turn most ordinary objects into lethal weapons.

        [11] => base atk 1=2440

        [12] => base def 1=2650

        [13] => max atk 1=7015

        [14] => max def 1=7613

        [15] => mastery bonus atk 1=915

        [16] => mastery bonus def 1=993

        [17] => image 2=MartialAres6.jpg

        [18] => rarity 2=Ultimate Rare

        [19] => sale price 2=188400

        [20] => max mastery lv 2=200

        [21] => quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds.

        [22] => max atk 2=9822

        [23] => max def 2=10660

        [24] => mastery bonus atk 2=1098

        [25] => mastery bonus def 2=1192

        [26] => alignment=Bruiser

        [27] => ability=Warhawk

        [28] => gender=Male

        [29] => usage=Average

        [30] => faction=Super Hero

        [31] => effect=Significantly harden DEF of your Bruisers.

        [32] => centretrait=None
    )

Next, I would loop over the array and split each string on the "=" character and build an associative array from the pieces.
    //First remove the first empty element from the array.
    array_shift($parts);

    $finalArray = array();
    foreach($parts as $part)
    {
        $b = explode("=", $part);
        $finalArray[$b[0]] = $b[1];
    }

This should result in the structure you are seeking.
Array
(
    [card name] => [Martial] Ares

    [character name] => Ares

    [release_date] => May 1 2013

    [image 1] => MartialAres5.jpg

    [rarity 1] => Super Special Rare

    [pwr req 1] => 28

    [sale price 1] => 94200

    [max card lv 1] => 60

    [max mastery lv 1] => 40

    [quote 1] => Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear.  But he can use any weapon expertly, and turn most ordinary objects into lethal weapons.

    [base atk 1] => 2440

    [base def 1] => 2650

    [max atk 1] => 7015

    [max def 1] => 7613

    [mastery bonus atk 1] => 915

    [mastery bonus def 1] => 993

    [image 2] => MartialAres6.jpg

    [rarity 2] => Ultimate Rare

    [sale price 2] => 188400

    [max mastery lv 2] => 200

    [quote 2] => Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds.

    [max atk 2] => 9822

    [max def 2] => 10660

    [mastery bonus atk 2] => 1098

    [mastery bonus def 2] => 1192

    [alignment] => Bruiser

    [ability] => Warhawk

    [gender] => Male

    [usage] => Average

    [faction] => Super Hero

    [effect] => Significantly harden DEF of your Bruisers.

    [centretrait] => None
)

A: With the minimal error checking:
$text = explode('|', $text);
$result = array();
foreach ($text as $entry) {
    if ($entry) {
        $entry = explode('=', $entry);
        $result[$entry[0]] = $entry[1];
    }
}


text:
Q: Jquery IE Compatibility : Member Not Found Error I have an aspx page. While i was developing that page, The error: 'member not found' occured in jquery 1.11.0 library. To avoid this error I used meta tag like shown below
        <meta http-equiv="X-UA-Compatible" content="IE=10" />
                                  or
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />

With that tag i avoided the error and i was able to finish my aspx page. After i finished my project I created an application on IIS and publish the project to that application. When I browse the web form from IIS,
the error :'Member not found' occured again. Even though i use the other versions of jquery libraries the error didn't went away. What is changing when i try to reach the page from url.
The Part Of jquery library where error occured
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {

// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
    set: function( elem, value, name ) {
        // Set the existing or create a new attribute node
        var ret = elem.getAttributeNode( name );
        if ( !ret ) {
            elem.setAttributeNode(
                (ret = elem.ownerDocument.createAttribute( name ))
            );
        }

           ret.value = value += "";  **error occured here**

        // Break association with cloned elements by also using setAttribute (#9646)
        if ( name === "value" || value === elem.getAttribute( name ) ) {
            return value;
        }
    }
};

How can i solve this. Thanks for reply in advance

A: The head tag was like
   <head runat="server">

After i remove 'runat' attribute, it worked properly.


text:
Q: json_encode doesn't print anything I have the follow code which doesn't print anything:
$array = array();
while ($res = $query->fetch_array(MYSQLI_ASSOC)) {
    array_push($array, array(
        'value' => $res['pregunta'],
        'tokens' => explode(' ',$res['pregunta']),
        'url' => $res['id-cadena']
        ));
}

echo json_encode($array);

But when I use print_r it works correctly:

    Array
(
    [0] => Array
        (
            [value] => ¿Cuál es la obra de Pablo Picasso basada en triangulos?

etc...

Have somebody had the same problem?
Thanks a lot!


text:
Q: Improve loading time of fragment transaction for android applications I'm currently developing an app ( you may have answered or saw some other questions of me ) and am having an usability problem. I have a navigation drawer and when the user clicks on one of the items another fragment replaces the main frame_content. The problem I'm encountering is that, the transaction takes some time on my devie.
I click on one item in the navigation drawer, then the app "stucks" for some seconds and will continue working fine.
I also know where the problem is, because, when I'm replacing a fragment that has no data in it it works instantly. It's just, that the app has to display really much data. I'm passing a HashMap<String, Collection<String>> to the fragment and am reading it out there. I'm saving it into an array and then I'm reading that array out again in a for loop and displaying the data.
I thought about various other ways like: reading all the data out in the main activity and then pass multiple arrays to the fragment. but the problem is, that i need 13 arrays for each fragment, because the hashmap contains data of 13 different keys. each key has 1 value. and there are 50 entries in total. So
50 Entries contain 13 keys contain 1 value.
This is pretty much data to load for the device. So I thought about how I could probably improve the speed of the loading fragment.
I'm downloading data from XML with AsyncTask while a splash screen is loading, then I'm saving it into different hashmap (depending on which xml i loaded). i then start a new intent to the main activity and pass all hash maps. then depending on the navigation drawer list a new fragment is opened and the hashmap is passed into a function in the fragment. then the data gets read into arrays and the array gets read out again in the OnCreateView method to add the data to the layout.
Any speed improvements ideas? this is how I currently change my fragments
protected void onNavItemSelected(int id) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
    switch ((int) id) {
    case 101:
        MainFragment.passList(hashMap);
        ft.replace(R.id.content_frame, new MainFragment());
        ft.commit();
        break;
//further cases....

A: Maybe
ft.commit();
getSupportFragmentManager().executePendingTransactions();
break;

will help you to execute the transaction faster (be sure to call it on main thread)
http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions()
Or if the problem is not in the transaction itself, maybe it is your loop that need improvment ?


text:
Q: Custom shortcode not working I tried to make my own shortcode for a first time. I have done all things and there is no syntax error. Can somebody tell me what's the mistake? It's not working.
I have implemented this code into function.php file and Dreamweaver tells me that there is no syntax error.
function booknovelist_button( $atts ) {
    // Attributes
    extract( shortcode_atts( array(
        'style' => 'rfc',
        'link' => 'www.booknovelist.com'
    ), $atts ) );

    $style  = '$atts[style]'; $choice = ' '; $choicehover = ' ';

    if ($style == 'rfc') {
        $choice='link to image';
        $choicehover='link to image';
    };

    if ($style == 'sn') {
        $choice='link to image';
        $choicehover='link to image';
    }

    if ($style == 'pon') {
        $choice='link to image';
        $choicehover='link to image';
    }

    if ($style == 'amazon') {
        $choice='link to image';
        $choicehover='link to image';
    }

    echo '

 ' ; }
}

add_shortcode ( 'bn_btn', 'booknovelist_button' );

A: You should review the documentation for add_shortcode() and look at the examples. You are supposed to return the content that is to be output by the shortcode.
function footag_func( $atts ) {
    return "foo = {$atts['foo']}";
}
add_shortcode('footag', 'footag_func');

So instead of echoing your div, you should return it.
Your code seems to have other syntax errors as well.


text:
Q: grails FAILURE: Build failed with an exception.Execution failed fro task ':boot run' got this error while I tried to run my very first grail app..:(
enter image description heregot this error while I tried to run my very first grail app..:(

A: The initial memory allocated to your JVM is bigger than the maximum JVM memory size you allocated via your -Xmx parameter.
see What are the Xms and Xmx parameters when starting JVMs?

A: Some steps you can follow to resolve...

*

*Check the JDK and Grails, both need to be same 32 bit or both need to be same 64 bit

*Execute this on command prompt: java -Xmx2048m -Xms256m

*Then rebuild and run app


text:
Q: Float formatting in C++ How do you format a float in C++ to output to two decimal places rounded up? I'm having no luck with setw and setprecision as my compiler just tells me they are not defined.
cout << "Total     : " << setw(2) << total << endl;
total outputs: Total     : 12.3961
I'd like it to be: 12.40 or 12.39 if it's too much work to round up.

A: If you want the trailing zero from rounding, you can use the C function printf.
#include <iostream>
#include <cstdio>

int main() {
    float v = 12.3961;
    std::printf("%.2f",v); //prints 12.40
}

Compared to:
#include <iostream>
#include <iomanip>

int main() {
    float v = 12.3961;
    std::cout << std::setprecision(4) << v; //prints 12.4
}

A: You can do it with C++20 std::format:
std::cout << std::format("Total     : {:.2f}\n", total);

or the fmt::format function from the {fmt} library, std::format is based on. {fmt} also provides the print function that integrates formatting and output making it even easier and more efficient (godbolt):
#include <fmt/core.h>

int main() {
  fmt::print("Total     : {:.2f}\n", 12.3961);
}

Output:
Total     : 12.40

This uses the IEEE754 default rounding mode (round to nearest even) so you'll have to round up yourself (How do I round up/down a decimal place of a float value? C++).

A: You need to include <iomanip> and provide namespace scope to setw and setprecision
#include <iomanip>
std::setw(2)
std::setprecision(5)

try:
cout.precision(5);
cout << "Total : " << setw(4)   << floor(total*100)/100 << endl;

or
 cout << "Total : " << setw(4)   << ceil(total*10)/10 << endl;

iostream provides precision function, but to use setw, you may need to include extra header file.

A: This is a little dirty...
template <typename T>
string sFormat(const char *f, T value)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), f, value);
    return string(buffer);
}

And do things like this :
cout << "Result :" << sFormat(" %5.2f", 3.14) << sFormat(" %5d", 2300) << endl;

A: Use cout << fixed or cout.setf(ios::fixed), and std::cout.precision(<# of decimal digits>) as in the following (using the Clang-503.0.40 compiler included with OSX Mavericks):
#include <iostream>

int main()
{
   using namespace std;

   float loge = 2.718;
   double fake = 1234567.818;
   cout << fixed;
   cout.precision(2);
   cout << "loge(2) = " << loge << endl;
   cout << "fake(2) = " << fake << endl;
   cout.precision(3);
   cout << "loge(3) = " << loge << endl;
   cout << "fake(3) = " << fake << endl;
}

The output from this is (note the rounding):
loge(2) = 2.72
fake(2) = 1234567.82
loge(3) = 2.718
fake(3) = 1234567.818

This is the simple version.  In lieu of using cout << fixed;, you can use cout.setf(ios::fixed); (for displaying scientific notation, replace fixed with scientific; both will set the number of digits to the right of the decimal point).  Note the cout.precision() is also used to set the number of digits displayed in total on either side of the decimal point if the format flags do not include fixed or scientific.  There are tutorials for this on the Internet.

A: To also include the trailing zero, it isn't sufficient to set the precision. You also have to change the floating point format to fixed format, which uses the number of digits as told by setprecision as the number of digits after the decimal point:
std::cout << std::fixed << std::setprecision(2) << v;

Working online example code


text:
Q: Mongo $and selector How does mongo $and selector work? I have trouble getting correct results back.
Let's say I have a collection something like this:
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 5 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 9 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 34 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 66 }

and I run query:
var selectorMin = 9;
var selectorMax = 42;

ScrapReport.find({ $and: [ { quantity: { $gte: selectorMin }, quantity: { $lte: selectorMax } } ] })

I would expect mongo to return me only 9 and 34. But for some reason it also returns 5 and 66.
What's wrong with my query?

A: Your query is returning all the documents in that sample because it is first looking for documents whose quantity >= 9 i.e. 9, 34 and 66 AND combines that query with documents whose quantity <= 42 i.e 34, 9 and 5. It's not looking for documents within a particular range but your query explicitly looks for all documents that satisify two ranges i.e.
Documents which satisfy "quantity >= 9"
+
Documents which satisfy "quantity <= 42"

not
Documents which satisfy "9 <= quantity <= 42"

Just simplify your query to
ScrapReport.find({ "quantity": { "$gte": selectorMin, "$lte": selectorMax } })

That way, you specify a range for MongoDB to filter your documents with i.e.
9 <= quantity <= 42

Specifying a comma separated list of expressions implies an implicit AND operation and use an explicit AND with the $and operator when when the same field or operator has to be specified in multiple expressions.

A: Using an implicit AND operation like the other answers suggested would work. But I would like to dig deeper into the specifics. Why is your query not working as you expected it to work?
Why? Why is this seemingly correct query of yours returning not so correct results? After all, whether you use implicit or explicit AND operation should be a matter of your choice and you should be able to achieve your goal irrespective of which form you use. How to make your query work with an explicit AND operation?
Let us look at the syntax of the AND operation.
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

The value of your AND operator should be an array containing expressions on which you would like to perform the AND operation.
After a first glance at your query, everything looks fine. But if you take a moment to look deeper, you would see that your query is not matching the AND syntax exactly. It is still syntactically correct. No doubt about that. But it is logically incorrect. I will explain how.
This is your $and operator value
{ $and: [ { quantity: { $gte: selectorMin }, quantity: { $lte: selectorMax } } ] }

You think you have an expression1 quantity: { $gte: selectorMin } and an expression2 quantity: { $lte: selectorMax }. An AND operation with these expressions should return the documents with quantity 9 and 34. But actually, all you have is one expression. Pay close attention to the braces. You have added both these expressions in a single {} block. Do you see it? So effectively, there is no 2nd expression for the AND operator to work with. But AND operator requires two or more expressions to function properly.
So your query is of the form
{ $and: [ { <expression1> } ] }

With an incorrect form, the results will also be incorrect. The correct query using an explicit AND operation would be
ScrapReport.find({ $and: [ { quantity: { $gte: selectorMin } }, { quantity: { $lte: selectorMax } } ] })

Do you see the difference? Try this query and you will get the results that you expected in the first place.
If you are not satisfied by just having the answer and are curious to know how Mongo interpreted your first query, read further.
Consider this query
ScrapReport.find({ quantity: 9 })

What would you expect the result to be? If you expected Mongo to return a single document whose value in the quantity field is 9, you are right. That is exactly what the result is. Now consider the same query with a small twist.
ScrapReport.find({ quantity: 9, quantity: 5 })

What would the result be now? Things are getting interesting now, huh? If you execute this query and have a look at the result, you will still see only a single document. But the value in the quantity field is 5. Now that is interesting!
ScrapReport.find({ quantity: 9, quantity: 5, quantity: 34 })

What about this? The result is still a single document with value in the quantity field being 34. You can try other combinations. What you will find out is this -

Within an expression, if you are referencing a field multiple times, the result will be determined by the last reference to that field in that expression.

Now apply this concept to your original query. It has already been pointed out that you have a single expression with two parts quantity: { $gte: selectorMin } and quantity: { $lte: selectorMax }. Since within an expression, you are referring to the same field twice, only the last one will be relevant. The selection criteria will be quantity: { $lte: selectorMax }. The result will be 3 documents with quantity values 5, 9 and 34.
If you swap the order i.e. write quantity: { $lte: selectorMax } first and then quantity: { $gte: selectorMin }, the selection criteria will now be determined by quantity: { $gte: selectorMin }. The result will be 3 documents with quantity values 9, 34 and 66.
Although it wasn't your intention, your original query is effectively
ScrapReport.find({ quantity: { $gte: selectorMin }, quantity: { $lte: selectorMax } })

When you miss braces or add them at the wrong position, it can completely change the meaning of your query.

Moral - Pay close attention to where you place your braces in complex queries.

A: Actually you have two problems in there:
Your query is equivalent to the following:
ScrapReport.find( { "$and": [{ "quantity": { "$lte": selectorMax } } ] } )

or even better:
ScrapReport.find( { "quantity": { "$lte": selectorMax } } )

The reason is because duplicate key are allowed in JSON document but the last value for a given key is maintained.
So this will only return all those documents where "quantity" is less than or equal selectorMax.
The second problem is already mentioned in @chridam's answer so the right query is:
ScrapReport.find({ "quantity": { "$gte": selectorMin, "$lte": selectorMax } })


text:
Q: Different outputs in Python I want to delete strings("324a" included) and leave only integers in a list. Here is the code;
a = ["345", "sadas", "324a", "14", "john"]

for i in a:
    try:
        if i == int(i):
            continue
    except ValueError:
        a.remove(i)
print(a)

With this code the output is;
['345', '324a', '14']

Even tho "324a" is not an integer and code should return ValueError the code still does not remove it from the list.

Here is another simple code that shows "324a" is not a integer;
a = "324a"
a = int(a)
print(a)

Output of the code above;
a = int(a)
ValueError: invalid literal for int() with base 10: '324a'

Thanks for the answers in advance!

A: It has to do with you mutating the list while iterating over it.
Look at the code below and watch the printed index...you remove sadas at index 1 which now leaves 324a at index 1, but the loop doesn't recognize the value change and thus does not repeat index 1 twice during the iteration.
for idx, i in enumerate(a):
    print(idx)
    try:
        if i == int(i):
            continue
    except ValueError:
        a.remove(i)
print(a)

try -
a = ["345", "sadas", "324a", "14", "john"]
b = []
for i in a:
    try:
        int(i)
        b.append(i)
    except ValueError:
        continue
print(b)

A: mixed_array = ["345", "sadas", "324a", "14", "john"]
only_integers= []

# A method to check if an object is integer
def is_int(s):
    try:
        int(s)
    except ValueError:
        return False
    else:
        return True

# Add integer objects from mixed_array to only_integers like:
only_integers = [i for i in mixed_array if is_int(i)]

# OR like:

only_integers = list(filter(is_int, mixed_array ))

A: You can't shouldn't remove items from a list while iterating through it.
Also, when i is a str following statement will be False: i == int(i).
I suggest using this instead:
a = ["345", "sadas", "324a", "14", "john"]
tempList = []
for i in a:
    try:
        int(i)
        tempList.append(i) # if int(i) fails, this line won't be reached
    except ValueError:
        pass

a = tempList[:] # we use [:] to copy the list
print(a)

or this one-liner:
a = ["345", "sadas", "324a", "14", "john"]
print([int(x) for x in a if x.isdigit()])

A: Don't modify the list you are iterating. Create a new one instead like this:
a = list(filter(None, map(lambda x: x if x.isdigit() else None, a)))

Edit: From the comment, we can directly use str.isdigit with filter,
a = list(filter(str.isdigit, a)))

A: You could use a simple list comprehension like this:
a = [word for word in a if word.isdigit()]

And this will create a list with all the numbers.


text:
Q: Retrieving the image and add caption to it I wanted to create an app by taking images from the sd card and add caption to it. Also I wanted to move the caption as per our wish and place it somewhere as desired and save it .can you please suggest an idea for doing this.  Also   if we want to add a caption to the existing image from SD card then , do we need to have database for doing this. or can it be saved directly to the SD card.

A: Use canvas (Custom Views) for it..
I think this is the only way to make one view (Image in one canvas) on other view (caption in other canvas) on it. So in this you have to complete knowledge of how views draw on canvas and how to move to that views. And using canvas you can also smoothly move your views on screen.
After creating custom views you can save those views in Bitmap, now you can also combine those images to one bitmap..
(Here Customeviews are ImageViews, TextViews, EditText etc..)
All the best. :-)

A: Refer This Answer
You can put an EditText and Write into it and after writting you first convert it to Bitmap like
Bitmap bmp = Bitmap.createBitmap(mEditText.getDrawingCache());

Now you can add created image bmp to your original image like this
call :
 Bitmap combined = combineImages(bgBitmap,bmp);
 public Bitmap combineImages(Bitmap background, Bitmap foreground) {

        int width = 0, height = 0;
        Bitmap cs;

        width = getWindowManager().getDefaultDisplay().getWidth();
        height = getWindowManager().getDefaultDisplay().getHeight();

        cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas comboImage = new Canvas(cs);
        background = Bitmap.createScaledBitmap(background, width, height, true);
        comboImage.drawBitmap(background, 0, 0, null);
        comboImage.drawBitmap(foreground, matrix, null);

        return cs;
    }

A:   USe like this.

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);
    background = Bitmap.createScaledBitmap(background, width, height, true);
    comboImage.drawBitmap(background, 0, 0, null);
    comboImage.drawText("title", x, y, paint);


text:
Q: Is emulation mode in IE11 same as setting meta EmulateIE7 tag? For IE11 browser I use I see this message on console :
"HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8."
Searching this error code on https://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-IE&k=k(VS.WebClient.Help.HTML1122)
Displays : "This mode is configured by IT Management for specific sites. If an individual user needs to turn it off on a webpage, uncheck the Enterprise Mode option in the Tools menu. For more about management of Enterprise Mode, see the IT documentation."
This is fine but I want to control this by setting the meta tag.
Will adding <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> to head have same affect as "running in Enterprise Mode emulating IE8" ?

A: No.  Using content="ie=8" will get similar results but not the same.
Enterprise mode IE (EMIE) is a special mode designed to provide greater compatibility with IE8 than was possible using x-ua-compatible.  IE8 standards mode was introduced with IE9 and some organizations were able to use it to migrate their legacy apps.  Other organizations struggled, however.  Because there was reliance on the then-current behavior of IE8 standards mode, IE11 introduced EMIE to help those who still struggled.
Some of this complexity is what led to the clean break being introduced with MS Edge.
To the best of my knowledge, you cannot enable or disable EMIE through markup. (You can do it through group policy, however, and that may help if your concern is related to rolling it out to a number of machines.)
Hope this helps...
-- Lance


text:
Q: connect Epson Printer TM-U220 with ePOS-Device SDK for JavaScript Printer TM-U220 is connected to router and able to print something like

GET /HTTP/1.1
Host : 192.168.1.100:9100
Accept : text/html,application/xhtml + xml,

With that, im sure that my printer is connected to the network with IP 192.168.1.100
Now, id like to connect my TM-U220 to my web application using
ePos SDK Javascript
but after trying to connect the device from my web app, im getting this

Failed to load resource: Could not connect to the server.
     http://192.168.1.100:8008/socket.io/1/?t=1473523306578


text:
Q: How to send form-encoded List from SwaggerUI? I'm getting 400 Bad Request on sending List<long> from SwaggerUI to .net application
Swagger

Response : {"statusCode":400,"message":["The value '"1","2","3"' is not valid."]}
Payload

Modal used by Swagger
public class DataArgs {
   public List<string> strVar { get; set; }
   public List<long> longVar { get; set; }
}


text:
Q: MicrosoftGraph API fails to mark a message as read I am using the Microsoft.Graph nuget package (version 1.6.2) and I try to mark an email as read.
This is the code:
        msg.IsRead = true;
        await MainPage.GraphServiceClient.Me.Messages[msg.Id].Request().Select("IsRead").UpdateAsync(msg);

From my understanding, the above code should only send the IsRead property to the server for update.
However, executing this, sends the whole message object (I have verified this with Fiddler) and you get this response:
{
  "error": {
    "code": "ErrorInvalidPropertyUpdateSentMessage",
    "message": "Update operation is invalid for property of a sent message.",
    "innerError": {
      "request-id": "<A guid here that I wont share>",
      "date": "2017-07-29T21:10:18"
    }
  }
}

Is the code correct, is this a bug, am I missing something or what?
Is there a way around this?

A: I've just encountered your question after being stuck with the same problem my self.
As I came to see after several tries the problem occurs when you try to update (PATCH) fields that aren't allowed to be updated.
In your case and in my case as well,
The problem was that we sent the msg object with all of his fields and not only with the patched and modified fields.
Instead of Doing the following:
var msg = await MainPage.GraphServiceClient.Me
    .Messages[imapMessage.MessageId]
    .Request()
    .GetAsync();

msg.IsRead = true;

await MainPage.GraphServiceClient.Me
    .Messages[msg.Id]
    .Request()
    .Select("IsRead")
    .UpdateAsync(msg);

You should only get the IsRead property in the first place,
Update
since version 1.9 of the GraphAPI, we need to send only the updated properties without the readonly properties.
await MainPage.GraphServiceClient.Me
    .Messages[msg.Id]
    .Request()
    .Select("IsRead")
    .UpdateAsync(new Message {IsRead = true});

Hoping it will help you if it's still releavent any way.

A: I found the following code works and wanted to share it as it might help other.
First thing I did was to ensure that the Credentials are set followed by calling the API that sets IsRead = true
 // setup the credentials
 // the brackets are are not used but only to help the data stand-out
 var credentials = new ClientSecretCredential(
     [Your.TenantId],
     [Your.ClientId],
     [Your.ClientValue],
     new TokenCredentialOptions { AuthorityHost =
           AzureAuthorityHosts.AzurePublicCloud });

 // mark the message as read,
 // the brackets for .Users[...] are required
 // the brackets for .Messages[...] are also required
 GraphServiceClient graphServiceClient = new GraphServiceClient(credentials);

   await graphServiceClient
      .Users[Your.ApiUserEmail]
      .Messages[Your.Message.id]
      .Request()
      .UpdateAsync(new Microsoft.Graph.Message() { IsRead = true });

if you are attempting the graphServiceClient code without using an "async" method, then use the following:
   graphServiceClient
      .Users[Your.ApiUserEmail]
      .Messages[Your.Message.id]
      .Request()
      .UpdateAsync(new Microsoft.Graph.Message() { IsRead = true }).Result;

Hope this helps...


text:
Q: Four-current, Induced Charge and Magnetic Flux I'm studying Jackiw's "Fractional Charge and Zero Modes for Planar Systems in a Magnetic Field" DOI: 10.1103/PhysRevD.33.2500
but I have difficulties at some points. One of the problems is
$$\langle j^0\rangle=\pm\frac{e}{4\pi}B$$
where $j$ is four-current, $B$ is magnetic field. How can I derive this result (and why we used only $j^0$ component)?.


text:
Q: converting oracle Date field Object to java Date I have a Date field in Oracle DB.
Date field1
Now  there is a existing DAO that fetches this field1 in form of Object
Object field1

Now I need to typeCast it to java Date
But if i do like following i get error:
Date dt = (Date) object;  //object holds date object
DateTime jdt = new DateTime(dt) ; //convert it to jodaDate

Error : cannot cast Long to Date.
How to convert it to javaDate and than Joda DateTime

A: You are confusing the datatype DATE in the Oracle DB with the Java type Date. The error cannot cast Long to Date states that the object you are holding is of the Java type Long, which is why the cast to the Java Date type fails. The Long represents the number of seconds or miliseconds since 01/01/1970, depending on yor DOA layer (see it's documentation), since the DATE precision in Oracle only goes down to seconds. To receive a date, use new Date((long) object) or new Date(1000 * (long) object) respectively.
You also can use those number of milliseconds to generate a DateTime directly without using the Java Date class at all.

A: The object that is fetched is a Long type, as evident from the error message. Now, you can simple contruct a java.util.Date object from a Long object as below:
Date dt = new Date((Long)object)


text:
Q: Python module import order I have downloaded and installed the development version of Numpy from Github and at first this module is imported with a standard import. Somewhere along the line (package manager updates or other python package installs from git sources I suspect) Python imports revert to the Numpy module installed by the package manager.
How do I get Python to import the modules I have installed from git sources?
I would like to avoid having to modify the sys.path in every script.
I run Ubuntu Gnome 14.10.
The path is as follows:
>>> import sys
>>> sys.path
['',
 '/usr/local/bin',
 '/usr/local/lib/python2.7/dist-packages/matplotlib-1.5.x-py2.7-linux-x86_64.egg',
 '/usr/lib/python2.7/dist-packages',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages/PILcompat',
 '/usr/lib/python2.7/dist-packages/gtk-2.0',
 '/usr/lib/pymodules/python2.7',
 '/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
 '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode',
 '/usr/lib/python2.7/dist-packages/IPython/extensions']

A: Recommended way is off course, using VirtualEnv. But as a suggestion, you can add the git numpy source to the pythonpath manually, before working on that module.
$ export PYTHONPATH=$PYTHONPATH:/YOUR/REPO/LOCATION

I used to do this before I learnt of virtualenvs ;)

A: As suggested in comments above, it is highly recommended to use virtualenv module, because when you will have more that 1 project you will face the problem that different projects require different modules or different versions of one module.
Imagine you have 200 projects and each of them require some modules to work. If you decide to share one of your project with anybody it will be a nightmare to determine which dependencies has this exact project and what modules are required for it to work.
So please check virtualenv and also virtualenvwrapper which makes work with virtualenv very comfortable.
Both modules available for pip install, they are not complex, you will get hands on them very quick. Time spent to study them worth of benefit you will get.


text:
Q: Logging files names that contain Norwegian letters in the file name in Unix OS using a Jar executable I have a simple java program that when run is supposed to traverse through the whole directory on a Unix server and log all files on the fileserver that contain Norwegian letters "å,ø,æ".
This is how it looks on the fileserver using winSCP:

In the end the logs.log file should look like this:
2022-10-25 14:27:02 INFO  Logger:99 - File: 'DN_Oppmålings.pdf'
2022-10-25 14:27:02 INFO  Logger:99 - File: 'Salg_av_gærden.pdf'

However, this is how it ends up in the log file, all Norwegian letters are represented with a square.

I can't seem to figure out why it happens. It probably has something to do with the encodings. Because when I run it on windows locally, everything runs as expected and I get the result I need. But when I build the project as an executable jar and run on the server it gets wrong.
Here is the code I am using.
public static void renameFiles3(File[] files) throws IOException {
    for (File filename : files) {
        if (filename.isDirectory()) {
            renameFiles3(filename.listFiles());
        } else {
            String fileNameString = filename.getName();
            if (fileNameString.contains("å") || fileNameString.contains("ø") || fileNameString.contains("æ")){
                logger.info("File: '" + filename.getName());
            }
        }
    }
}

public static void main(String[] args) {
    File[] files = new File(path).listFiles();
        try {
            renamer.renameFiles3(files);
        } catch catch(IOException ex){
            logger.error(ex.toString());
        }
}

Someone pointed out that the encoding should be specified, but I am not sure how that is done. If I run "locale" command on the Unix server this is what I get as output.
[e1111111@ilt repository]$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

I use Putty to run the jar file. Here are the configs.

Stacktrace of the error I get when running the jar:
java.nio.file.NoSuchFileException: ./documentRepository/DN_Oppm�lings.pdf
    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
    at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
    at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:430)
    at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
    at java.base/java.nio.file.Files.move(Files.java:1422)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:105)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.renameFiles2(Renamer.java:89)
    at com.example.fixfilenamesonfileserver.Renamer.main(Renamer.java:154)

What makes it even more strange, is that I can create for instance a folder with mkdir containing Norwegian letters in the name and it would be displayed correctly and also logged correctly if I create a file with Norwegian letters.

A: Some time ago I wrote an answer for a very similar problem.
As stated in the aforementioned solution, the problem could be related with the use of different charsets in your local Windows laptop (probably, cp-1252 or some variant) and your server.
As suggested, please, consider review the charset which is in place in the JVM in every environment, and review and adapt if necessary the value of the file.encoding system property on your laptop and the server environment, maybe it will help you solve the problem.
Probably running your jar with a proper value for the file.encoding JVM property may do the application work properly:
java -Dfile.encoding=UTF-8 -jar your_app.jar

A: I suspect there is no problem with your Java nor your file.
The problem is likely with the app you use to view that text. That app is using a font that lacks a glyph for those characters.
Edit your Question to note the app and OS if you want further assistance.

A: Assuming you are printing the letters to a terminal, the problem is most likely the terminal you use. If you are printing the characters to a terminal, make sure it is set to chcp65001, and a font that supports displaying norwegian letters fully. I have encountered similar problems while trying to display multilingual text due to the shortage of support for multiple languages in the same font.
So, to summarize, first set the terminal code-page encoding to chcp 65001, and then change the font of the terminal to a font that supports norwegian letter fully, and then run the jar file from the terminal like : java -jar <jarname>.jar


text:
Q: Error Running Development Web Server I am new to learning AngularJS, after installing Node.js I also cloned the angular.phonecat repository, I am finding it difficult to start the development web server using:
   npm install

Please find attached the errors i got.

A: Install Python 2.7.* , node-gyp is looking for it to be specified and can't find it.
If you want to use a different version of Python with NPM, see this post.


text:
Q: Appcompat Toolbar doesn't give styles to spinner I need all the icons and text in the toolbar to be light, and the overflow menu, the spinner, and the drawer (not shown in image) to all have a light backgrounds and dark text. (Using the android themes)
Why is only the overflow doing it how I'd like, but the drawer (not shown) and the spinner staying dark?
Any ideas help! (even though I feel I've tried everything)
Must be IDENTICAL to this
styles.xml
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">@color/teal500</item>
        <item name="colorPrimaryDark">@color/teal700</item>
        <item name="colorAccent">@color/accent</item>
        <item name="windowActionBar">false</item>
        <item name="actionBarWidgetTheme">@style/Theme.AppCompat.Light</item>
    </style>

</resources>

toolbar.xml
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    ...
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>


text:
Q: Не могу во втором окне получить текущее значение label, которое передается из первого окна Помогите разобраться, работаю с PyQT5 и с Qt Designer.
Есть два окна, я передаю значение из ComboBox первого окна в label второго окна, это без проблем.
Дальше мне нужно получить это значение во втором окне из label и провести с ним некоторые манипуляции, но при попытке его получить, мне всегда возвращается его изначальное значение, как будто на форму оно и не передалось... код ниже)
from PyQt5 import QtCore, QtGui, QtWidgets
from SecondWindow import SecondWindowView

class Ui_FirstWindow(object):
    def setupUi(self, FirstWindow):
        FirstWindow.setObjectName("FirstWindow")
        FirstWindow.resize(313, 375)
        self.centralwidget = QtWidgets.QWidget(FirstWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(90, 60, 121, 41))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(80, 200, 141, 71))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        FirstWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(FirstWindow)
        self.statusbar.setObjectName("statusbar")
        FirstWindow.setStatusBar(self.statusbar)
        self.retranslateUi(FirstWindow)
        QtCore.QMetaObject.connectSlotsByName(FirstWindow)

    def retranslateUi(self, FirstWindow):
       _translate = QtCore.QCoreApplication.translate
       FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
       self.comboBox.setItemText(0, _translate("FirstWindow", "User1"))
       self.comboBox.setItemText(1, _translate("FirstWindow", "User2"))
       self.comboBox.setItemText(2, _translate("FirstWindow", "User3"))
       self.pushButton.setText(_translate("FirstWindow", "SendData"))

class FirstWindowView(QtWidgets.QMainWindow, Ui_FirstWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pushButton.clicked.connect(self.open_second_window)

    def open_second_window(self):
       self.sw = SecondWindowView()
       val = self.comboBox.currentText()
       self.sw.label_get_user.setText(val)
       self.hide()
       self.sw.show()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    fw = FirstWindowView()
    fw.show()
    sys.exit(app.exec_())
'''

'''
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_SecondWindow(object):
    def setupUi(self, SecondWindow):
        SecondWindow.setObjectName("SecondWindow")
        SecondWindow.resize(320, 384)
        self.centralwidget = QtWidgets.QWidget(SecondWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label_user = QtWidgets.QLabel(self.centralwidget)
        self.label_user.setGeometry(QtCore.QRect(10, 80, 71, 41))
        font = QtGui.QFont()
        font.setPointSize(18)
        self.label_user.setFont(font)
        self.label_user.setObjectName("label_user")
        self.label_get_user = QtWidgets.QLabel(self.centralwidget)
        self.label_get_user.setGeometry(QtCore.QRect(100, 70, 251, 61))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_get_user.setFont(font)
        self.label_get_user.setStyleSheet("color:red")
        self.label_get_user.setObjectName("label_get_user")
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(40, 250, 251, 71))
        self.lineEdit.setObjectName("lineEdit")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(40, 212, 241, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        SecondWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(SecondWindow)
        self.statusbar.setObjectName("statusbar")
        SecondWindow.setStatusBar(self.statusbar)
        self.retranslateUi(SecondWindow)
        QtCore.QMetaObject.connectSlotsByName(SecondWindow)

    def retranslateUi(self, SecondWindow):
        _translate = QtCore.QCoreApplication.translate
        SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
        self.label_user.setText(_translate("SecondWindow", "User:"))
        self.label_get_user.setText(_translate("SecondWindow", "UserFromFirstWindow"))
        self.label_3.setText(_translate("SecondWindow", "GetItButNeedUserFromFirstWindow"))

class SecondWindowView(QtWidgets.QMainWindow, Ui_SecondWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setText(self.label_get_user.text())

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    sw = SecondWindowView()
    sw.show()
    sys.exit(app.exec_())
'''

A: Конструктор, т.е. метод __init__ выполняется ОДИН раз при инициализации.
Да, вы присвоили label_get_user новое значение:
self.sw.label_get_user.setText(val)

но lineEdit и не догадывается, что надо взять значение из label_get_user,
помогите ему это сделать:
self.sw.lineEdit.setText(self.sw.label_get_user.text())     # +++

from PyQt5 import QtCore, QtGui, QtWidgets
from q1334359_SecondWindow import SecondWindowView

class Ui_FirstWindow(object):
    def setupUi(self, FirstWindow):
        FirstWindow.setObjectName("FirstWindow")
        FirstWindow.resize(313, 375)
        self.centralwidget = QtWidgets.QWidget(FirstWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.comboBox = QtWidgets.QComboBox(self.centralwidget)
        self.comboBox.setGeometry(QtCore.QRect(90, 60, 121, 41))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.comboBox.addItem("")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(80, 200, 141, 71))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        FirstWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(FirstWindow)
        self.statusbar.setObjectName("statusbar")
        FirstWindow.setStatusBar(self.statusbar)
        self.retranslateUi(FirstWindow)
        QtCore.QMetaObject.connectSlotsByName(FirstWindow)

    def retranslateUi(self, FirstWindow):
       _translate = QtCore.QCoreApplication.translate
       FirstWindow.setWindowTitle(_translate("FirstWindow", "MainWindow"))
       self.comboBox.setItemText(0, _translate("FirstWindow", "User1"))
       self.comboBox.setItemText(1, _translate("FirstWindow", "User2"))
       self.comboBox.setItemText(2, _translate("FirstWindow", "User3"))
       self.pushButton.setText(_translate("FirstWindow", "SendData"))

class FirstWindowView(QtWidgets.QMainWindow, Ui_FirstWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton.clicked.connect(self.open_second_window)

    def open_second_window(self):
        self.sw = SecondWindowView()
        val = self.comboBox.currentText()
        self.sw.label_get_user.setText(val)

        self.sw.lineEdit.setText(self.sw.label_get_user.text())     # +++

        self.hide()
        self.sw.show()
        print('Hello self.sw.label_get_user') #

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    fw = FirstWindowView()
    fw.show()
    sys.exit(app.exec_())


text:
Q: Excel formula that returns row if value is found in a column I have a list of DNS entries that I need to sort to get the good records.
In sheet1, I have a dump of the raw data, in column 1 is a zone ID which is a number.
In sheet2, I have a column made up of the zone ID's that I want to keep.
On sheet3 I am looking for a way to take sheet1 column 1, to see if it matches one of the values in sheet2 column 1. If it does, then the result should be the entire row into sheet 3.
Is this possible?  Data example is below:
Sheet1 - 4 columns
1   foo            A     IP_Address

1   foomaster    CNAME   IP_Address

392 jimmy          A     IP_Address

Sheet2
In column1 is a list of acceptable zone ID's I want.
Sheet3
If value from sheet1-column1 exists in sheet2-column1, paste the entire row from sheet1.

A: One quick and dirty way to do it is with =COUNTIF(). If the value is found, return the value from cell A1, B1, C1, etc. by filling the formula to the right.
In Sheet 3, Cell A1, enter the following:
=IF(COUNTIF(Sheet2!$A:$A,Sheet1!$A1),Sheet1!A1)
Now use the Fill right (Ctrl+R) and Fill down (Ctrl+D) features to apply the formula to as many cells as required, depending on the number of columns+rows expected in the raw data you have in Sheet 1. If the search is successful, it will fill out the data from that row in Sheet 1.
If the search is unsuccessful, the row will return FALSE. If a cell on sheet 1 does not have data, it will return 0. If desired, you can return blank text ("") instead of a FALSE or a 0 with a formula like:
=IF(COUNTIF(Sheet2!$A:$A,Sheet1!$A1),IF(ISBLANK(Sheet1!A1),"",Sheet1!A1),"")
To say it again - this is quick and dirty and will have performance implications if you have a large dataset. You are typically better off putting your raw data in a database - you can then use a Pivot Table or simple SQL queries to extract the data you need in the format required.

A: Ok, but you need a third sheet for this trick. In this third sheet, you'll need to drag this formula right and down, to match the size of the table(sheet1) where the values you will be looking for reside. Sheet2 will be where we will try to find said values.
=index('sheet2'!A$1:A$1000,Match('sheet1'$D1:$D1000,'sheet2'!$A$1:$A$1000,0))

So this is like a dragable vlookup where you will be filling a new table the same size as sheet1, in the case it doesn´t find any match it will return #N/A, if you want to handle that then sorround it in a IFERROR like this
=IFERROR(index('sheet2'!A$1:A$1000,Match('sheet1'$D1:$D1000,'sheet2'!$A$1:$A$1000,0));"NO MATCH")
Then you will need to filter and delete the "NO MATCH" entries. But this is the formula I personally use for this kind of things.
Maybe the ,, ', etc; sintax is not the same to you because of locale and different Excel versions.
Cheers


text:
Q: When factoring an equation to find the solution for x, is the non-solution number proof math is invented? Let's say one is factoring an equation. This equation is solved by factoring and upon doing so one is left with x=-1 and x=3 (the specific number does not really matter for the sake of this question). When plugging those values back into the equation the -1 is found to not equal 0, and 3 does, thus 3 is a solution and -1 is not.
This makes me wonder. Does this support the idea that math is invented rather than discovered? (Given that we get some random value that is meaningless...)
Or does this value actually mean something... If so what?

A: The situation you describe cannot happen, at least not exactly the way you describe it; "factoring" means replacing an expression with a product of two expressions which it is equal to, and if one of those expressions is zero the product must always be.
However, a situation like the one you describe - in which one solution is extraneous - can happen in slightly different circumstances. For example, consider the equation
$$\log_3{x} + \log_3(x - 2) = 1$$
By using a property of logarithms, and raising $3$ to the power of both sides, this gives $x^2 - 2x = 3$, which has solutions $x = -1$ and $x = 3$. But, while $x = 3$ does satisfy the original equation, plugging in $x = -1$ requires taking $\log_3(-1)$, which is nonsense.
This doesn't seem to be a reason to believe that math is an invention - but the filter we see it through, and the words we use for it, are. Here, the issue is that the logarithm property we used (that $\log_3x + \log_3y = \log_3(xy)$) isn't correct in exactly the way we usually think of it; it's only true when the relevant logarithms exist.
This is a general rule - when you get an apparent solution that isn't an actual solution, it's because you've made a mistake in your reasoning somewhere, sometimes a very subtle one.

A: When such solutions wildy appear but aren't satisfied by original equations these are called extraneous solutions and discarded.
But I don't think they might appear in factoring.


text:
Q: Need help making a list accept multiple user inputs without removing the input before it I need help making a Score Calculator for my class. The inputs for the scores can't be preset and it has to add up all previous inputs while increasing the count number.
For example say I entered 23 into the text box and hit enter then typed in 45 i need my program to keep the 23 and add it to the 45 and it needs to repeat this for as long as the user inputs numbers.
I know it needs to be a collection and i have the basis for it down i just need the code that will save the input from before and add it to the new one and save that total to add it to the next input.
This is my attempt at solving this problem:
 List<decimal> score = new List<decimal>();
        score.Add(scoreInput);
        decimal scoreTotal = 0;
        decimal scoreHolder = 0;
        foreach (decimal d in score)
        {

            scoreTotal = scoreHolder + scoreInput;
            scoreHolder = scoreInput;
            scoreInput = 0;
            txtTotal.Text = scoreTotal.ToString("");
            txtCount.Text = score.Count.ToString("");
            txtScore.Clear();
            txtScore.Focus();
        }

A: Simply add an event handler for the KeyDown event, and use a code like the following:
private void tbEntry_KeyDown(object sender, KeyEventArgs e)
{
    Decimal entry;

    if (e.KeyCode == Keys.Enter)
    {
        if (Decimal.TryParse(tbEntry.Text, out entry))
        {
            score.Add(entry);
        }

        tbResult.Text = score.Sum(s => s).ToString();
        tbEntry.Text = string.Empty;
    }
}

This is one way of doing what you want to achieve.
EDIT:
This is assuming that you have your variable "score" declared as a member of your Form:
private  List<decimal> score = new List<decimal>();

Cheers


text:
Q: KnockoutJS observable properties in observable array not tracked This is a model:
        function DiscountItem(minDays, percent) {
            var self = this;
            self.minDays = ko.observable(minDays);
            self.discount = ko.observable(percent);
        }

        function TableItem(name, from, to, price, hasDiscount) {
            var self = this;
            self.name = name;
            self.from = from;
            self.to = to;
            self.price = price;
            self.discount = hasDiscount;
        }

        function AppViewModel() {
            var self = this;

            self.discounts = ko.observableArray([
                new DiscountItem(12, 4),
                new DiscountItem(20, 6)
            ]);

            self.table = ko.observableArray([
                new TableItem("first", "20.03","3.04", 400, 1),
                new TableItem("second", "11.04","4.05", 600, 0)
            ]);

            self.addDiscount = function() {
                self.discounts.push(new DiscountItem(0, 0));
            }

            self.removeDiscount = function() {
                self.discounts.remove(this);
            }

            self.addPeriod = function() {
                self.table.push(new TableItem("","","", 0, 1));
            }

            self.removePeriod = function() {
                self.table.remove(this);
            }

            self.pricing = ko.computed(function() {
                return JSON.stringify({
                    durationDiscount : self.discounts(),
                    periods: self.table()
                })
            }, self);
        }

and this is what i need:

Every time i change one of observable properties or add new item in observableArray i need to populate other input with JSON representation of data combined from self.discounts and self.table
something like this
{"durationDiscount":[{"minDays":12,"discount":4},{"minDays":20,"discount":6}],"periods":[{"name":"first","from":"20.03","to":"3.04","price":400,"discount":1},{"name":"second","from":"11.04","to":"4.05","price":600,"discount":0}]}

all works fine if I remove ko.observable() on model properties, but i need to track them.
If i add ko.observable(), self.discounts in ko.computed retuns me empty array

A: I think the only problem is that when those properties are observable, you are not getting their value in your pricing property. Try this:
self.pricing = ko.computed(function() {
    return JSON.stringify({
        durationDiscount : self.discounts().map(function(x){
              return { minDays: x.minDays(), discount: x.discount() }
        }),
        periods: self.table()
    })
}, self);

function DiscountItem(minDays, percent) {
    var self = this;
    self.minDays = ko.observable(minDays);
    self.discount = ko.observable(percent);
}

function TableItem(name, from, to, price, hasDiscount) {
    var self = this;
    self.name = name;
    self.from = from;
    self.to = to;
    self.price = price;
    self.discount = hasDiscount;
}

function AppViewModel() {
    var self = this;

    self.discounts = ko.observableArray([
        new DiscountItem(12, 4),
        new DiscountItem(20, 6)
    ]);

    self.table = ko.observableArray([
        new TableItem("first", "20.03","3.04", 400, 1),
        new TableItem("second", "11.04","4.05", 600, 0)
    ]);

    self.addDiscount = function() {
        self.discounts.push(new DiscountItem(0, 0));
    }

    self.removeDiscount = function() {
        self.discounts.remove(this);
    }

    self.addPeriod = function() {
        self.table.push(new TableItem("","","", 0, 1));
    }

    self.removePeriod = function() {
        self.table.remove(this);
    }

    self.pricing = ko.computed(function() {
        return JSON.stringify({
            durationDiscount : self.discounts().map(function(x){ return { minDays: x.minDays(), discount: x.discount() }}),
            periods: self.table()
        })
    }, self);
}

ko.applyBindings(new AppViewModel());

        <input data-bind="value: minDays" />
        <input data-bind="value: discount" />

A: The observableArray actually doesn't provide the notification about items changes, see the documentation note. So you have two options - to subscribe to the item's change or to call item's observable in your computed's scope. I'd prefer second one like this
self.pricing = ko.computed(function() {
         return ko.toJSON({
                durationDiscount : ko.utils.arrayMap(this.discounts(),
function(item){
  return new DiscountItem(ko.unwrap(item.discount), ko.unwrap(item.minDays)); })
               })}, self);

see my fork http://jsfiddle.net/xv62vs6c


text:
Q: PHP Database Entry Issue (Wampserver) I'm a complete code nooby and months ago built a basic website before my server mobo died. I just rebuilt the server and copied over all my website/db code I had backed up to my desktop. To the best of my knowledge everything is the same between php code and database setup.
My site works 90% except for when I go to input data. I get an error of "waiting for entry" opposed to the expected "New record created successfully". The relative if statement is on the very bottom of the below code.
Does anyone by chance have any clue why after inputting all my proper data that it does not trigger the "New record created successfully"? If it means anything the code works fine on my desktop and unless I did something really dumb I copy/pasta'd everything appropriately to this server :(
<?php

 //Connect to database

include('database.php');

   //grab user logged in for database insertion

   $user_check = $_SESSION['login_user'];

   $ses_sql = mysqli_query($dbcon,"select username from t_login where username = '$user_check' ");

   $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

   $login_session = $row['username'];

 // Create DB Variable

 $login_session = $row['username'];
 $excercisename = (isset($_POST['excercisename']) ? $_POST['excercisename'] : null);
 $setcount = (isset($_POST['setcount']) ? $_POST['setcount'] : null);
 $rep1 = (isset($_POST['rep1']) ? $_POST['rep1'] : null);
 $rep2 = (isset($_POST['rep2']) ? $_POST['rep2'] : null);
 $rep3 = (isset($_POST['rep3']) ? $_POST['rep3'] : null);
 $rep4 = (isset($_POST['rep4']) ? $_POST['rep4'] : null);
 $rep5 = (isset($_POST['rep5']) ? $_POST['rep5'] : null);
 $rep6 = (isset($_POST['rep6']) ? $_POST['rep6'] : null);
 $rep7 = (isset($_POST['rep7']) ? $_POST['rep7'] : null);
 $rep8 = (isset($_POST['rep8']) ? $_POST['rep8'] : null);
 $weight1 = (isset($_POST['number1']) ? $_POST['number1'] : null);
 $weight2 = (isset($_POST['number2']) ? $_POST['number2'] : null);
 $weight3 = (isset($_POST['number3']) ? $_POST['number3'] : null);
 $weight4 = (isset($_POST['number4']) ? $_POST['number4'] : null);
 $weight5 = (isset($_POST['number5']) ? $_POST['number5'] : null);
 $weight6 = (isset($_POST['number6']) ? $_POST['number6'] : null);
 $weight7 = (isset($_POST['number7']) ? $_POST['number7'] : null);
 $weight8 = (isset($_POST['number8']) ? $_POST['number8'] : null);
 $cardio = (isset($_POST['cardio']) ? $_POST['cardio'] : null);
 $duration = (isset($_POST['duration']) ? $_POST['duration'] : null);
 $weight = (isset($_POST['weight']) ? $_POST['weight'] : null);
 $comments = (isset($_POST['comments']) ? $_POST['comments'] : null);

 //Execute the insert statement
 if(!empty($excercisename)){
 $sql = "INSERT INTO t_workout (username, excercisename, setcount, set1reps, set2reps, set3reps, set4reps, set5reps, set6reps, set7reps, set8reps, set1weight, set2weight, set3weight, set4weight, set5weight, set6weight, set7weight, set8weight, cardio, cardio_dur, weight, comments)
 VALUES ('$login_session', '$excercisename', '$setcount', '$rep1', '$rep2', '$rep3', '$rep4', '$rep5', '$rep6', '$rep7', '$rep8', '$weight1', '$weight2', '$weight3', '$weight4', '$weight5', '$weight6', '$weight7', '$weight8', '$cardio', '$duration', '$weight', '$comments')";
 }

  if($weight > 0){
     $sql = "INSERT INTO t_workout (username, weight)
     VALUES ('$login_session', '$weight')";
  }

if(isset($sql)){
    if ($dbcon->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Waiting for entry.";
}
}
$dbcon->close();
?>

A: Sweet mercy I am sorry for anyone that looked into this lol.
I solved it. The code and everything is fine (well, for how amateur the code is).
The issue is with wampserver, in my mysql.ini file there was a semi-colon commenting out sql-mode. I simply removed the semicolon and now it works. I don't know what sql mode in the ini-file did...but its something I had edited in the ini file months ago that I caught when comparing all my wampserver config files.
;sql-mode=""