text:
Q: How to use more than one method? So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.
Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.
The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.
Customer:
public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
        String custPhone) {
    super();
    this.customerName = customerName;
    this.streetAddress = streetAddress;
    this.custCity = custCity;
    this.custState = custState;
    this.custZip = custZip;
    this.custPhone = custPhone;
}
public String getCustomerName() {
    return customerName;
}
public void setCustomerName(String customerName) {
    this.customerName = customerName;
}
public String getStreetAddress() {
    return streetAddress;
}
public void setStreetAddress(String streetAddress) {
    this.streetAddress = streetAddress;
}
public String getCustCity() {
    return custCity;
}
public void setCustCity(String custCity) {
    this.custCity = custCity;
}
public String getCustState() {
    return custState;
}
public void setCustState(String custState) {
    this.custState = custState;
}
public String getCustZip() {
    return custZip;
}
public void setCustZip(String custZip) {
    this.custZip = custZip;
}
public String getCustPhone() {
    return custPhone;
}
public void setCustPhone(String custPhone) {
    this.custPhone = custPhone;
}

}

Video:
public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
    super();
    this.videoName = videoName;
    this.videoYear = videoYear;
    this.copyNum = copyNum;
    this.rentalRate = rentalRate;
}
public String getVideoName() {
    return videoName;
}
public void setVideoName(String videoName) {
    this.videoName = videoName;
}
public int getVideoYear() {
    return videoYear;
}
public void setVideoYear(int videoYear) {
    this.videoYear = videoYear;
}
public int getCopyNum() {
    return copyNum;
}
public void setCopyNum(int copyNum) {
    this.copyNum = copyNum;
}
public double getRentalRate() {
    return rentalRate;
}
public void setRentalRate(double rentalRate) {
    this.rentalRate = rentalRate;
}

Invoice (incomplete) :
    import java.util.Scanner;

public class Invoice {
     public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    Customer Brandon = new Customer("Brandon James" , "112 Oak Street"
        , "CityVille" , "Alabama" , "18229",
        "912-2248");

Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
        "Metropolis" , "Pennsylvania" , "24057", "241-8009");

Video Easter = new Video("Easter 2", 2002, 4, 2.49);

Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);

if( Prog4.newRental = "Brandon"){
    Customer Brandon = newCust

}
}
}

Prog4(incomplete):
import java.util.*;

public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;

public static void main(String[] args){
Scanner in = new Scanner(System.in);

System.out.println("Enter Customer Name: ");
 String newRental = in.nextLine();

System.out.println("Enter Video Name: ");
String vidName = in.nextLine();

System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();

System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}

public String getNewRental() {
    return newRental;
}

public void setNewRental(String newRental) {
    this.newRental = newRental;
}

public String getVidName() {
    return vidName;
}

public void setVidName(String vidName) {
    this.vidName = vidName;
}

public String getRentalDate() {
    return rentalDate;
}

public void setRentalDate(String rentalDate) {
    this.rentalDate = rentalDate;
}

public String getDaysRented() {
    return daysRented;
}

public void setDaysRented(String daysRented) {
    this.daysRented = daysRented;
}

}


text:
Q: click a button multiple times to run the same function, java android studio when i click a button i want to print a random string, but so far i can only click it once then i have to restart to print a new one. what do i have to do to continuously print strings.
java code:
    public String converse = randomStarter();

public static String randomStarter() {

    Random generator = new Random();
    int rand = generator.nextInt(6);
    String starter = new String("");

    switch (rand) {

        case 0: starter = "What was your favorite subject in \n school as a kid? \n Worst?";

            break;

        case 1: starter = "My favorite room in the house is...";

            break;

        case 2: starter = "If you had 1 million dollars, what would you do with it?";

            break;

        case 3: starter = "Did you ever have a nickname? \n If so, what was it?";

            break;

        case 4: starter = "If I had magical powers I would...";

            break;

        case 5: starter = "If you were invisible for a day, \nwhat would you do?";
            break;

        case 6: starter = "5 people I would NOT like to meet...";

            break;

    }

        return starter;

}

public void printStarter(View view) {
    ((TextView)findViewById(R.id.fullscreen_content)).setText(converse);

}

xml code to where the text is printed:
    <TextView android:id="@+id/fullscreen_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:keepScreenOn="true"
    android:textColor="#2f4b66"
    android:textStyle="bold"
    android:textSize="50sp"
    android:gravity="center"
    android:text="@string/dummy_content" />

button xml:
 <Button android:id="@+id/dummy_button"
            style="?metaButtonBarButtonStyle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/dummy_button"
            android:clickable="true"
            android:onClick="printStarter"
            />

A: You're getting the same string because your variable converse always has the same string, when you click the button it doesn't change
public String converse = randomStarter();

The easy way out would be modifying the code for you button like this:
((TextView)findViewById(R.id.fullscreen_content)).setText(randomStarter());

This will work, but your code is very inefficient. The best way to do it is create an array of strings where you keep all the values, and each time the button is pressed you generate a random number and pull the string from the array whose index corresponds to that number.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help to transform the code for removing punctuation from Java string into recursion I have come up with a solution for removing punctuation from a String in Java.Need to convert this into a recursive method.I would be thankful if someone can help me to solve this.
The code is as below:
public class punctuationRemove {

//private static String punc = "[][(){},.;!?<>%]";
 static StringBuilder sb = new StringBuilder();
 static char[] punc = "',.;!?(){}[]<>%".toCharArray();

 public static void main(String[] args){
        String s = "Hello!, how are you?";
        System.out.println(removePuntuation(s));
    }

 public static String removePuntuation(String s)
 {
     String tmp;
     boolean fl=true;

     for(int i=0;i<s.length()-1;i++)
     {
         fl=true;
         char strChar=s.charAt(i);
         for (char badChar : punc)
         {
            if (badChar == strChar)
            {
               fl=false;
               break;
             }
          }

          if(fl)
          {
             sb.append(strChar);
           }
     }
     return sb.toString();
 }
}

A: Recursion usually has two parts to it:

*

*A base case in which all recursion stops and a result is returned, and

*An iterative step in which recursion continues.

How does one recursively examine each character of a String?  They only look at the first character and send the substring from 1 to the end of it off to a recursive call.
As an example:
public String splitRecursive(String s) {
    if(!s.isEmpty()) {
        return s.charAt(0) + splitRecursive(s.substring(1));
    } else {
        return "";
    }
}

Let's think about that for a moment - so long as the string isn't empty (i.e. base case), then I should take the first character I get and append that to the result of another call (i.e. iterative step), which takes the substring from 1 to however many characters are left.  If it is empty, I just return the empty string.
This skeleton piece of code is actually 3/4ths of what you need to work out your problem.  You need to augment it to insepct the character to see if it is one of your punctuation characters you've already isolated.
Consider your iterative step:  if you see punctuation, what should you do?  If you don't see punctuation, what should you do?  I leave the rest as an exercise to the reader.

A: I think this would help you,
public class RemovePunctuations {

public static int i = 0;
public static void main(String[] args){
        String s = "Hello!, how are you?";
        System.out.println(removePuntuation(s));
    }

Using Recursion,
public static String removePuntuation(String s){
    char [] charArray = s.toCharArray();
            if(!Character.isLetter(charArray[i]) && !Character.isSpaceChar(charArray[i])){
                s = s.replace(String.valueOf(charArray[i]), "");
                i--;
            }
            i++;
            if(i<s.length())
                return removePuntuation(s);
        return s;
}

}

You can get the same result from the following way without using recursion,
public static String removePuntuation(String s){
     char [] charArray = s.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            if(!Character.isLetter(charArray[i]) && !Character.isSpaceChar(charArray[i])){
                s = s.replace(String.valueOf(charArray[i]), "");
            }
        }
        return s;
}


text:
Q: Likelihood of a hard drive PCB replacement working? I have a 1.5TB Seagate 7200.11 that died.  The platter still spins up initially when attached to a machine, but then the drive clicks and spins down.  Then the cycle repeats.  I've found a few sites that sell replacement PCBs, however I don't know if the PCB is the issue, or something else.  Given the symptoms above, is it at all likely that a PCB replacement would help?  If not, I won't waste my money on the PCB replacement.

Note:  I put the drive in an external ESATA controller and tried hooking it up to a Linux box here at work and got some error messages in the logs.  I can post them if anyone thinks it will help in determining whether a PCB swap would fix the problem I'm running into.

A: First, lots of Seagate 7200.11 drives were affected by a firmware problem, which results in drive being inaccessible. This specific problem can be solved by a firmware flash, which can be done using a special cable & adapter, but it is not for the faint of heart. If you have this specific problem, you might try fixing it yourself, or maybe RMA disk to Seagate.
Second, generally speaking replacement of PCB board is possible, but complicated. You need to reflash the firmware, copy data from old PCB to the new one, PCB must be from the same model and series, etc:

Firmware is unique to the PCB this controls calibration and track information so it is very rare to be able to interchange the same model PCB with one that has another firmware revision.

My advise is: if your data on that disk is worth more than several thousand dollars, it is worth going to a professional data recovery company. If not, then messing with the PCB replacement will most probably not be successful.

A: If you need to get some data off the disk really badly, then you could try the PCB replacement. If not, I would say that it's not worth it and you should just replace the drive.

A: My understanding is that the answer is "no".  The hard disk controller is more than just a controller, it keeps track of SMART, bad sectors, and other stuff that I couldn't get a hardware recovery company to reveal ("that is our IP").
So putting another PCB on a drive only works in a small percentage of cases - and that is even if you can get hold of the exact same controller with ideally the same firmware revision.
The clicking sound is ominous, and I take it to indicate a mechanical issue of some kind.  I think you may have to just accept the loss.
If you have another drive that is the same model, you could try the pcb swap if you are happy to sacrifice the other drive (again, just my understanding, but it seems that you can mess with the controller swapping it to another drive to the point that it may well not work if you put it back on the old drive).

A: Replacement the PCB will not solve the problem below:

*

*The drive will power up normally (no ticking noises, errors etc) but will not be recognized by the computer.

*The drive will power up normally and be recognized correctly but will report a size of 0 bytes.

*The drive will power up but report SMART errors on boot

I am very lucky, I successfully fixed my wd drive by a pcb replacement. swaped the BIOS, and the drive is restored. you can search the seagate barracuda 7200.11 pcb here on their site: http://www.hddzone.com/seagate-barracuda-720011-pcb-c-8.html They are trusted.

A: Rather than going for a complex fix, that might require a lot of effort, you might want to try simpler solutions first
You said it spins then ticks and then its done for, right?  Well, sounds to me the disc was thrown off balance or there is dust particles in it.  For real, I'm being serious.
Before you do anything, tap it with slight pressure a couple of times on each side and swallow all your spit (to ensure you do not make it worse by spitting on it) and gently blow on it.  It sounds odd but I have brought back several things from the grave, and one of Apples documented ways of fixing " hitting it hard on the back right side", so its not unprecedented
If it still doesn't work connect it to your computer as a secondary / storage drive and boot into your os that you have on another drive (not the broken one) and in sessions copy your data off the broken disk.  Doing it this way improves the chance of a successful data extraction as the drive does not take as much power nor spins as fast.  Avoid xcopy and robocopy or equivalent as that will spin your disk harder than you want, and try to go into the disk then using right-click copy/paste or its equivalent instead.
Your way though, honestly, with consideration to money, time, and labor, you ought just get a ssd instead... But just try what I am saying because it is already busted so if I am wrong you are out nothing if i am right!

A: In reply to  Journeyman Geek;
I actually was able to recover my data several years ago on a 2.5" IDE HDD by placing it into an anti-static bag and put it in the freezer for 2 hours. Since this was a last resort, I didn't care if it got damaged, but it worked. I recovered about 100 GB of data this way. Sounds unbelievable, but I saved my valuable data at the time. I suppose lowering the temperature shrink the platters or affect the electronic components in some way.


text:
Q: How to get xml element using element value? I need to get xml element using element value and I have to get parent element with xml element using jaxb?
sample XML:
 <ifx>
<nam-ref>LID</nam-ref>
<val>01</val>
<then>
    <int>
        <name>WHEELSPEED</name>
        <description></description>
    </int>
    <int>
        <name>FRONT</name>
        <description></description>
    </int>
    <manyInt>
        <int>
            <name>REAR_LEFT</name>
            <description></description>
        </int>
    </manyInt>
    <int>
        <name>REAR_RIGHT</name>
    </int>
</then>

I know only the name value as "REAR_LEFT". With this I have find the xml element and its parent element .

A: You could do this with JAXB if you have a schema and generate a lot of classes and iterate through each of the attributes to find the value you search for.
Or you use a little data projection (Disclosure: I'm affiliated with that project):
import org.xmlbeam.XBProjector;
import org.xmlbeam.XBProjector.Flags;
import org.xmlbeam.annotation.XBRead;

public class Demo {

    public interface Projection {

        @XBRead("name()")
        String getType();

        @XBRead("./name")
        String getName();

        @XBRead("./description")
        String getDescription();
    }

    public static void main(String[] args) {
        String xpath="//*[name='REAR_LEFT']";
        Projection projection = new XBProjector(Flags.TO_STRING_RENDERS_XML).io().url("res://data.xml").evalXPath(xpath).as(Projection.class);
        System.out.println(projection.getType()+":"+projection.getName()+" "+projection.getDescription());
        System.out.println("As XML:\n"+projection);
    }

}

After correction of you XML (add a root element, close the ifx element) this program prints out:
int:REAR_LEFT
As XML:
<int>
    <name>REAR_LEFT</name>
    <description/>
</int>

This is how it works:

*

*The xpath //*[name='REAR_LEFT'] selects every element that has a child named "name" with the content "REAR_LEFT".

*The XBProjector "projects" the selected element to the Java interface Projection

*The projection interface can access the data in the element by defined projection methods (e.g. for type, name & description=

*The projection interface can print itself out as XML


text:
Q: Angular 2: Trigger Interpolation From other Component not working I have two components, C1 and C2.
I want to trigger the interpolation in C2 when clicking a button in C1.
The interpolated value is defined in C2 as a public variable:
public elementType: string = "test";
C2 is defined in C1 as following:
import {PropertiesComponent} from "../properties/properties.component";
constructor(private propComp: PropertiesComponent) {}
setActive(model){console.log("test");
this.propComp.elementType = "updated value";}

The console log is triggered, but the interpolation is not.

A: You are treating the component like a service. So added it to the constructor and all.
You can pass the elementType from C2 to C1 as @Input() elementType and it will meet your expectation.
In C1
@Input() elementType;
setActive(model){
console.log("test");
this.elementType = "updated value";
}

A: Make use of Angular services to refer the values set by C1 component inside C2 component.
Inject the Service in both the components.
Declare the variable elementType in your service.
Set the variable elementType of service within component C1.
Now you can access it in component C2 via service instance.
If you dont like to use service, then you have to pass from C1 to C2 using @Input() and @Output() variables.
As @Padmapriya said, you cannot inject component like a service. Rather you can use component as a child component to exchange data.


text:
Q: How to read the contents of a CSV file and put it into a 2D array in Java? I just want to ask on how to read the contents of a CSV file and put it into a 2D array.
The content of my CSV file contains 7 columns(which are comma separated ",") for each row. The rows on the other hand are separated by a dash/hyphen "-". But note that the rows are still on the same line(they are just identified when there is a dash/hyphen which separates the 7 columns(for each row).
(The contents that appear on the CSV file are user inputted, meaning the user inputs 7 values for columns in each row.)

My problem is that whenever the user finishes inputting the values for the first row, I get a java.lang.ArrayIndexOutOfBoundsException: 7  which comes from the declared 7 columns of my 2D array(where I plan to insert the values of the CSV file) that is in my readCustomerCSV fuction.
The specific line from the function is this:  read2DString[read2DStringIndex][g] = fromfile[g];
Here is my source code:
public void writeCustomerCSV() {  // everything in this snippet code works fine(it creates a CSV file which stores the inputs of the user)
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
        StringBuilder sb = new StringBuilder();
        int y;
        for (int x = 0; x < itemTo2D.length; x++) {
            for (y = 0; y < itemTo2D[0].length; y++) {
                if (itemTo2D[x] != null) {
                    sb.append(itemTo2D[x][y]);
                    sb.append(",");
                }
            }
            sb.append("-");  //separation for rows
            sb.append(",");  // separation for columns
        }
        bw.write(sb.toString());
        bw.close();
    } catch (Exception ex) {

    }
}

public void readCustomerCSV() {  // reads the contents of the CSV file     *having issues with ArrayINdexOutofBounds
    String[] fromfile = {};   // 1d string for getting the columns(7 columns) of the CSV file
    String[][] read2DString = new String[10][7];   // 2D array where the contents of the CSV file will be inserted (can only get 10 unique values of 7 columns)
    try {
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
        String line;
        while ((line = br.readLine()) != null) {
            fromfile = line.split(",");  //separates the columns by a comma
        }
    } catch (Exception ex) {

    }

    for (int g = 0; g < fromfile.length; g++) {
        read2DString[read2DStringIndex][g] = fromfile[g];  // the ArrayIndexOutofBounds is here (inserts the values of the 2D array(by row))
        //   System.out.print(fromfile[g] + " ");
        if (fromfile[g].equals("-")) {     //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
            read2DStringIndex++;
        }
    }
}

Is there anything that I missed in my codes or is my approach not good enough?

A: Before parsing your data into a 2D array, your code loops through a 1D array of the data, each eventual row separated by dashes. When you get to the for-loop, your code views the dash as an 8th column in the line  read2DString[read2DStringIndex][g] = fromfile[g], as g would represent an index of 7. Only afterward does your code increment the row. To solve this, you would want to put the if-statement before this line and then use "continue;" to skip to the next iteration of the loop to bypass this problem.
You also have to reset the columns to 0 when you increment the row so instead of
read2DString[read2DStringIndex][g] = fromfile[g]
, use read2DString[read2DStringIndex][g%8] = fromfile[g]. The modulus operator (%) will give you the remainder after division, which in this case is the correct column number after dividing out the length of completed rows worth of columns.


text:
Q: Complex time interval check in PHP I have a complex time interval check I'm struggling to solve. Here is the problem:
I need to dynamically calculate pick up time for orders.
Orders from Monday 10:01am till Wednesday 10am will be delivered on Friday. Orders from Wednesday 10:01 till Friday 10:00am will be delivered on  the following Monday.
Orders from Friday 10:01am till Monday 10:00am will be delivered on
following Wednesday.
I'm working in PHP and using Carbon (http://carbon.nesbot.com/docs/) and the order placement time will be Carbon::now()

A: Sorry for my previous code. I checked and found several flaws there. I have rewritten the code and here is complete and working solution for you. You can have a look over the conditions to figure out what I've done:
<?php
    date_default_timezone_set('Asia/Karachi'); // set default timezone if needed
    $time = new DateTime();
    $day = $time->format('l');
    $IntervalA = new DateTime('10:01');
    $IntervalB = new DateTime('10:00');

    // for friday delivery
    if(in_array($day, array('Monday', 'Tuesday')) AND $time >= $IntervalA OR in_array($day, array('Wednesday')) AND $time <= $IntervalB) {
        echo "The product will be delivered on Friday";
    }

    // for monday delivery
    if(in_array($day, array('Wednesday', 'Thursday')) AND $time >= $IntervalA OR in_array($day, array('Friday')) AND $time <= $IntervalB) {
        echo "The product will be delivered on Monday";
    }

    // for wednesday delivery
    if(in_array($day, array('Friday', 'Saturday', 'Sunday')) AND $time >= $IntervalA OR in_array($day, array('Monday')) AND $time <= $IntervalB) {
        echo "The product will be delivered on Wednesday";
    }


text:
Q: Array conversion to type only known at runtime - C# I'm trying to convert a string array to an array whose type is going to be known only at runtime. I tried that in two different ways :
PropertyInfo info = obj.GetType().GetProperty("PropertyName");

//GetElementType() because in this case the dynamic element is an array
var converter = TypeDescriptor.GetConverter(info.PropertyType.GetElementType());
var firstWay = stringProperty.Split(';').Select(x => converter.ConvertFrom(x)).ToArray();

var secondWay = Array.ConvertAll(stringProperty.Split(';'), x => Convert.ChangeType(x, info.PropertyType.GetElementType()));

Both, the first and second way return an array of objects. I needed the array to be of the type of the property info (info.PropertyType.GetElementType()). Let's suppose the info.PropertyType is Int32, decimal, bool. I wanted the converted array to match this type instead of returing a generic array of objects. How can I do that ?
Regarding @Sweeper comment... I intent to use the converted array to set another object property dynamically as well. Something like this:
obj2.GetType().GetProperty("PropertyName").SetValue(obj2, firstWay, null);

Basically, the first array will be the result of a split from a string (stringProperty.Split(';')). That array should then be converted to that dynamic type that will at the end be stored in an object property that has that dynamic type used on the array conversion.


text:
Q: Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation In a .babelrc file, I wrote :
"plugins": [
    [
      "@babel/plugin-proposal-class-properties"
    ]
  ]

In my class, I wrote :
class Login extends React.Component {
    constructor(props){
        super(props);
        this.state={
            ...
        };
        this.changeValue=this.changeValue.bind(this);
        ...
    }
    changeValue = (e) => {
        this.setState({[e.target.name]: e.target.value});
    };
    ...

But when I try to import this module, I get :

I don't want to use webpack, it seems very complicated. If there is no other way than webpack, then how should I configure it ?
Complete project : https://github.com/maifeeulasad/react-mua-login


text:
Q: Swiftui enter value in TextField then button click need change Text - not working I am enter value in TextField then i button click, after click i need change Text and put my result but my code not working, could you help me
Code:
import SwiftUI

struct ContentView: View {
    @State var numeral: Double = 0.00
    @State var result: Double = 0.00

    var body: some View {
        VStack{

            TextField("Enrer numeral", value: self.$numeral, formatter:  NumberFormatter())
                .padding(20)
                .frame(width: 300, height: 100)
                .font(.largeTitle)

            Text("\(result)")
                .font(.largeTitle)
                .padding()

            Button(action: {
                self.result = self.numeral*1.2

                print(self.result)
                print("sfsdfd")
            }) {
                Image(systemName: "play.fill")
                    .font(.largeTitle)
                    .foregroundColor(.red)

            }
        }
       }
    }

A: It seems while using value: as an input, SwiftUI does not reload the view.
SwiftUI reloads the view using text: as an input whenever a key is pressed.
do it using below approach.
struct ContentView: View {

    @State var numeral : String = "0.00"
    @State var result: Double = 0.00

    var body: some View {

       VStack {

            TextField("Enrer numeral", text: $numeral)
                .keyboardType(.decimalPad)
                .padding(20)
                .frame(width: 300, height: 100)
                .font(.largeTitle)

            Text("\(result)")
                .font(.largeTitle)
                .padding()

            Button(action: {

                UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
                if let val = Double(self.numeral) {
                    self.result = val * 1.2
                    print(self.numeral)
                    print(self.result)
                }
                else {
                    print("Entered value is invalid")
                }
            }) {
                Image(systemName: "play.fill")
                    .font(.largeTitle)
                    .foregroundColor(.red)
            }
        }
    }
}

A: This should help
Button(action: {
    // force textfield to commit
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder),
       to: nil, from: nil, for: nil)

    self.result = self.numeral*1.2

    print(self.result)
    print("sfsdfd")
}

A: A different approach, but this should work for you on ios devices and macos catalyst.
import SwiftUI

struct ContentView: View {

@State var numeral: Double = 0.00
@State var result: Double = 0.00

var body: some View {
    VStack{

        TextField("Enrer numeral", text: Binding<String>(
            get: { String(format: "%.02f", self.numeral) },
            set: {
                if let value = NumberFormatter().number(from: $0) {
                    self.numeral = value.doubleValue
                }}))
            .padding(20)
            .frame(width: 300, height: 100)
            .font(.largeTitle)

        Text("result \(result)")
            .font(.largeTitle)
            .padding()

        Button(action: {
            self.result = self.numeral * 1.2
            print("---> result: \(self.result)")
            // if you want to reset the TextField value
            self.numeral = 0.00
        }) {
            Image(systemName: "play.fill")
                .font(.largeTitle)
                .foregroundColor(.red)
        }
    }
}
}


text:
Q: SQL Server - How to remove IsPersisted attribute on computed column In SQL Server, how can we switch off the PERSISTED attribute of a computed column using T-SQL? I am able to do this using Management Studio GUI but do not know how to do it using T-SQL.

A: If you want to drop the PERSISTED property from your column, then you can try the following:
ALTER TABLE dbo.MyTable ALTER COLUMN MyColumn DROP PERSISTED;

According to MSDN:

[ {ADD | DROP} PERSISTED ]
Specifies that the PERSISTED property is added to or dropped
from the specified column. The column must be a computed column that is
defined with a deterministic expression.

Related: You can also have a look at this article by Aaron Bertrand.

A: You can do this by following this steps:

*

*Create a new column in your table having the same datatype as that of your persisted column.

*Update the new column with the persisted column value.

*Remove the persisted column from your table.

*Rename the new column as that of the persisted column.


text:
Q: How many milliseconds do "slow", "normal", and "fast" represent in jQuery? jQuery allows use of the string values "slow", "normal", and "fast" in animations (e.g.: $('#example').fadeOut('slow');).  How many milliseconds do each of these values represent?

A: 600, 400 and 200, respectively "slow", "normal", "fast". All in the docs

A: I would be original and answer 600, 400, 200 respectively. Since higher number of milliseconds means slower speed =) All in the source

A: 600ms, 400ms and 200ms respectively.
Source


text:
Q: Why does this cause segmentation fault? I'm doing an excersise with linked lists. It works when I enter value at the beginning of the list and values which are smaller than the values in the list. But when number is bigger I get a segmentation fault. Anybody thoughts on what is wrong with code below?
//Header (called headeroef):
typedef struct node
{
    int n;
    struct node* next;
}    node;

//Other code
#include <cs50.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "headeroef.h"

void insert(void);
void traverse(void);

node* first = NULL;

int main (void)

{

    int c;
    do

        {
            printf("Print instructions: \n"
                   "1. insert\n"
                   "2. Delete\n");

            printf("Command: ");
            c = GetInt();

            switch(c)

                {
                case 1: insert(); break;
                }
        }

    while (c!=0);

}
void insert(void)

{
    node* newPtr = malloc(sizeof(node));
    printf("Number to insert: \n");
    newPtr->n = GetInt();
    newPtr->next = NULL;

    if (first == NULL)
        {
            first = newPtr;
        }

    else if(newPtr->n < first->n)
        {
            newPtr->next = first;
            first = newPtr;
        }

    else
        {
            node* predPtr = first;

            //Dit houdt dus als in als aan deze else wordt voldaan!
            while (true)

                {
                    if (predPtr->n == newPtr->n)
                        {
                            free(newPtr);
                            break;
                        }
                    else if (predPtr->next->n > newPtr->n)
                        {
                            //Hiermee doe je weer die swap
                            newPtr->next = predPtr->next;
                            predPtr->next = newPtr;
                            break;
                        }
                    //Uitzoeken waarom hier een segmentation fault komt.s
                }
        }
    traverse();

}

void traverse(void)

{
    printf("The list is now\n");
    node* ptr = first;
    while (ptr!=NULL)

        {
            printf("%i\n", ptr->n);
            ptr = ptr->next;
        }
}

A: The while(true) loop that walks the list in search of the insertion spot does not check if it has reached the end of the list, resulting in dereferencing a NULL pointer eventually.
This check will cause the trouble when predPtr is pointing to the last node of the linked list:
if (predPtr->next->n > newPtr->n)

When predPtr is the last node, predPtr->next is NULL, so taking predPtr->next->n is undefined behavior.

A: Let's say you have the single number 5 in the list and you want to add 7.
Because first isn't NULL and the number you're trying to insert isn't less than the first, it ends up in the final block:
node* predPtr = first;
//Dit houdt dus als in als aan deze else wordt voldaan!
while (true)
{
    if (predPtr->n == newPtr->n)
    {
        free(newPtr);
        break;
    }
    else if (predPtr->next->n > newPtr->n)
    {
        //Hiermee doe je weer die swap
        newPtr->next = predPtr->next;
        predPtr->next = newPtr;
        break;
    }
    //Uitzoeken waarom hier een segmentation fault komt.s
}

Because you're not trying to insert a duplicate, the first if statement is irrelevant. The combination of:
node* predPtr = first;
while (true) {
    :
    else if (predPtr->next->n > newPtr->n)

is what's causing your crash, because predPtr->next is NULL (there's only the 5 element), so predPtr->next->n will dereference the null pointer.
You basically need to detect this before you try that dereference. If you get to the last element and it's still less than the one you're trying to insert, you need to append it rather than run off the end of the list.
Probably the easiest way to do that with your current code is to change the while loop to something like:
while (true) {
    // gooi als identiek.

    if (predPtr->n == newPtr->n) {
        free(newPtr);
        break;
    }

    // voegen als aan het einde van de lijst

    if (predPtr->next == NULL) {
        predPtr->next = newPtr;
        break;
    }

    // steek indien minder

    if (predPtr->next->n > newPtr->n) {
        newPtr->next = predPtr->next;
        predPtr->next = newPtr;
        break;
    }

    // vooruit naar volgend element.

    predPtr = predPtr->next;
}

You'll notice I've also added the statement at the bottom of the loop to advance through the list. Without this, you'll almost certainly end up with an infinite loop at some point.
You could also refactor your loop to use a different ending condition but that would require more work, and I'm not that keen on doing more than I have to, unless I'm paid by the hour :-)

A: else if (predPtr->next->n > newPtr->n)

You check predPtr->next->n without checking if next is null. Also while(true) loop might never end.


text:
Q: request.pipe() allow failing request I am forwarding my enriched request using request.pipe().
Problem is that it forwards the response when the piped request is successful but it responds with an error when the request fails. What I want is for the pipe to respond with whatever the request is returning. For example when it returns a 404 then pass along the 404 response to the original request.
Here's what I have
app.all('*', (req: Request, res: Response) => {
  req.headers.extraHeader = JSON.stringify(res.locals.infoFromMiddleware)

  req.pipe(request(`http://localhost:3000${req.url}`)).pipe(res)
})

I get the following error:
UnhandledPromiseRejectionWarning: Error: Request failed with status code 404 (or 400 / 500 / etc.)

A: Probably something like this
app.all('*', (req: Request, res: Response) => {
  req.headers.extraHeader = JSON.stringify(res.locals.infoFromMiddleware)

  req
   .pipe(request(`http://localhost:3000${req.url}`))
   .once('error', err => res.status(404).send(JSON.stringify(err)))
   .pipe(res)
})


text:
Q: How to get variable value from Javascript using Selenium with Python Using Selenium, the following is the code I am running on Python to get my geo-coordinates via use of the navigator web api:
        coordinates = driver.execute_script(
        " return () => {                                            " +
        "   var savedCoordinates;                                   " +
        "                                                           " +
        "   navigator.geolocation.getCurrentPosition(               " +
        "       (pos) => savedCoordinates = pos.coords,             " +
        "       error,                                              " +
        "       options);                                           " +
        "                                                           " +
        "   let options = {                                         " +
        "       enableHighAccuracy: true,                           " +
        "       timeout: 5000,                                      " +
        "       maximumAge: 0                                       " +
        "   };                                                      " +
        "                                                           " +
        "   function error(err) {                                   " +
        "       console.warn(`ERROR(${err.code}): ${err.message}`); " +
        "   };                                                      " +
        "                                                           " +
        " return savedCoordinates;                                  " +
        " }                                                         " )
        print(coordinates)

Expected output: {latitude: XXX.XXX, longitude XX.XXXX}
Actual output: {}
Can someone help me figure out how I can get my geo-coordinates using this method?

A: It should work without return () => { }
    coordinates = driver.execute_script(
    "   var savedCoordinates;                                   " +
    "                                                           " +
    "   navigator.geolocation.getCurrentPosition(               " +
    "       (pos) => savedCoordinates = pos.coords,             " +
    "       error,                                              " +
    "       options);                                           " +
    "                                                           " +
    "   let options = {                                         " +
    "       enableHighAccuracy: true,                           " +
    "       timeout: 5000,                                      " +
    "       maximumAge: 0                                       " +
    "   };                                                      " +
    "                                                           " +
    "   function error(err) {                                   " +
    "       console.warn(`ERROR(${err.code}): ${err.message}`); " +
    "   };                                                      " +
    "                                                           " +
    " return savedCoordinates;                                  " )

    print(coordinates)

As for me this () => {} only defines function but it doesn't run it - so it returns this function, not result from function. You may need () to run it
return (() => {...code...})()


text:
Q: Getting strange googleapi Err 400 message connecting to postgresql CloudSQL instance I´m getting a strange Err 400 missing project parameter when trying to connect to a CloudSQL instance using the cloud_sql_proxy mechanism
I have a GCE project with a working CloudSQL postgres database, my apps on the compute api can use it and I can do regular psql from any of the VM I have configured inside my GCE project.
However, when I try to connect to the database from my laptop using the cloud_sql_proxy I get this strange error.
I´m following to the letter this documentation: https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#install
So, following that documentation I have:

*

*CloudSQL enabled and working as I commented

*Proxy Installed

*I have a service account created as the documentation say with Cloud SQL Admin role as follows:

{
  "type": "service_account",
  "project_id": "my-proyect-21432",
  "private_key_id": "<hidden intentionally>",
  "private_key": "<hidden intentionally>",
  "client_email": "cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com",
  "client_id": "<hidden intentionally>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com"
}

*I started the cloud_sql_proxy successfully as follows:

user@hostname:~$ ./cloud_sql_proxy -instances=db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/29 10:17:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/29 10:17:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/29 10:17:25 Listening on 127.0.0.1:15432 for db1
2019/05/29 10:17:25 Ready for new connections

*And finally I launch the psql client as follows:

psql "host=127.0.0.1 port=15432 sslmode=disable dbname=db1 user=dbuser"

I see on the cloud_sql_proxy the following error:
2019/05/29 10:17:33 New connection for "db1"
2019/05/29 10:17:34 couldn't connect to "db1": googleapi: Error 400: Missing parameter: project., required

And on the client side I'm getting:
psql: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

At this point I should get my psql client connected successfully and I can´t find anything about this error online or in the google's documentation
I have no clue where I need to set a project parameter, I tried crazy places like on the psql side with -v or using the url with ? at the end with no luck, I also tried on the cloud_sql_proxy side using the -projects flag, also with no luck.

EDIT: New findings!!!
I think I'm close to solve this, the first setup I did (as commented above) was on my windows pc that I use at home, today I'm at the office and I decided to replicate all of that using macos, I don't think that the OS matter at all, the interesting thing is that I replicated all and founded a small thing that make me to move forward
So, I started again and execute points 1., 2., 3., 4. and wait? the documentation states that the instances string is as follows: myproject:us-central1:myinstance NOT what I originally wrote, so I changed that and start having a more reasonable error:
I started cloud_sql_proxy make the connection with psql and got this:
user@hostname:~$ ./cloud_sql_proxy -instances=my-proyect-21432:us-east1:db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/30 14:13:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/30 14:13:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/30 14:13:25 Listening on 127.0.0.1:15432 for db1
2019/05/30 14:13:25 Ready for new connections

<< when I run psql>>

2019/05/30 14:14:08 New connection for "my-proyect-21432:us-east1:db1"
2019/05/30 14:15:24 couldn't connect to "my-proyect-21432:us-east1:db1": dial tcp 10.26.112.3:3307: connect: operation timed out

My db1 instance has only the private IP 10.26.112.3
I started to look for that error around the internet and found a sugestion to allow incoming traffic to 3307 port:
Cannot Connect by Cloud SQL Proxy from Cloud Shell By Proxy
https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/164
So I added the following rule:
allow-cloudsqlproxy | Ingress | Apply to all | IP Ranges 0.0.0.0/0 | tcp,udp 3307 | allow | default | 1000

But that didn't make any difference because after that I'm still getting the same error message :(

EDIT: from a VM on the same project
I created a VM on that project and replicate all this, I was able to connect, no connection refused on port 3307 message.
I have no idea who is blocking that traffic...

A: Thank you for keeping us updated with your findings. I encountered the same problem. I just solved it—your first edit tipped me off.
While following the google CloudSQL documentation process for connecting to CloudSQL from an external application, I started the proxy like this:
`./cloud_sql_proxy -instances=<instance_name>=tcp:5433`

It didn't let me connect. I was receiving this error
`couldn't connect to "xxxxxxx": googleapi: Error 400: Missing parameter: project., required`

After reading your edit I modified the command to use the entire instance name as stated on the instance details page, and it worked. This is the new command that got it working.
`./cloud_sql_proxy -instances=myproject:us-central1:instancename=tcp:5433`

I hope this saves someone a few hours.

A: Actually cloudsql-proxy does work when your Cloud SQL instance has only an internal IP address. In this scenario you use private services access to establish the connection between the cloudsql-proxy and the Cloud SQL instance. It is also recommended to execute the proxy using the option --ip_address_types=PRIVATE to force it to use the internal IP instead the public when connecting to the Cloud SQL instance.
Look here and here for more details.
I hope this helps.

A: Ok, apparently the cloud_sql_proxy does not work if your db instance only has a private ip address, I had to add a public one so the proxy server had access to my instance.
I understand certain limitations but if Google provides a cloud_sql_proxy it should support all customer cases, I mean, I´m using the default network, that network is managed by google, the network should allow somehow the Proxy Server to reach my db instances.. I don't know ...
The second I added the public IP the second it started working ... but I honestly don't want a public IP on my db instances.

A: However trivial it may sound, for me an update from gcr.io/cloudsql-docker/gce-proxy:1.05 to gcr.io/cloudsql-docker/gce-proxy:latest* of the CloudSQL proxy image in Kubernetes deployment file resolved the problem.
Bearing in mind the final comments of the question author, I believe it may be a bug of CloudSQL that requires you to trigger something that will completely restart its instance. This is just speculation though.

* I tried this on version 1.16. If you are unsure about the stability of futures releases, you can specify the version instead of the latest tag.


text:
Q: NiFi: LDAP Authentication Issue I installed NiFi 1.7.1 and NiFi ToolKit.
And, I try to add LDAP auth in NiFi.
But, I try to login NiFI login page, but it occurs error "
The supplied username and password are not valid."
login-identity-providers.xml :
<provider>
    <identifier>ldap-provider</identifier>
    <class>org.apache.nifi.ldap.LdapProvider</class>
    <property name="Authentication Strategy">SIMPLE</property>

    <property name="Manager DN">CN=admin,OU=NIFI,DC=evidnet,DC=com</property>
    <property name="Manager Password">passwd</property>

    <property name="TLS - Keystore"></property>
    <property name="TLS - Keystore Password"></property>
    <property name="TLS - Keystore Type"></property>
    <property name="TLS - Truststore"></property>
    <property name="TLS - Truststore Password"></property>
    <property name="TLS - Truststore Type"></property>
    <property name="TLS - Client Auth"></property>
    <property name="TLS - Protocol"></property>
    <property name="TLS - Shutdown Gracefully"></property>

    <property name="Referral Strategy">FOLLOW</property>
    <property name="Connect Timeout">10 secs</property>
    <property name="Read Timeout">10 secs</property>

    <property name="Url">ldap://myhost:389</property>
    <property name="User Search Base">OU=NIFI,DC=evidnet,DC=com</property>
    <property name="User Search Filter">(sAMAccountName={0})</property>

    <property name="Identity Strategy">USE_USERNAME</property>
    <property name="Authentication Expiration">12 hours</property>
</provider>

and, My LDAP Server table is:

Why does not it work?
I entered the correct password, but it does not work.
(id: admin, password: passwd)

A: Your configured "User Search Filter" is referencing the entry's sAMAccountName. What is admin's sAMAccountName? Did you mean to reference the cn like your showing in the screenshot?


text:
Q: Generic function for self-calling a recursive function in definition Is there a reader macro or core function in Clojure that is similar to recur but possible with non-tail position?
For example, in this recursive function
(defn insertR* [newkey oldkey l]
  (cond
    (empty? l)  '()
    (not (seq? (first l)))
        (if (= (first l) oldkey)
        (cons oldkey (cons newkey (insertR* newkey oldkey (rest l))))
        (cons (first l) (insertR* newkey oldkey (rest l))))
    :else
        (cons (insertR* newkey oldkey (first l)) (insertR* newkey oldkey (rest l)))))

Is there some generic function I can use to call itself instead of calling insertR* explicitly?

A: Your question is unclear. If you mean: Can I do this without using stack space? No. Your insertR* has multiple self-calls, and that's impossible to express without a stack.
If you mean: Can I use a word like recur to mean "Call yourself recursively", and I don't care if it uses stack? Not really. You could write it yourself, though. Something like:
(defmacro defrec [name & fntail]
  `(def ~name (fn ~'recurse ~@fntail)))

(defrec foo [x]
  (when-not (zero? x)
    (recurse (dec x))))

I suspect this has a few holes, but it does basically what you're thinking.

A: Why do you need this kind of function/macro?
recur is created for tail-call optimization. It seems that your function doesn't allow it (may be I'm wrong). Though you said you don't need it. Why do you want to replace your calling insertR* explicitly to something else?
If you don't like passing newkey oldkey every time (and they not changed) you can create inner function, which will use this keys.


text:
Q: What is meant by "the JSF runtime", and how is the "javax.faces.webapp.FacesServlet" related? I've seen references to "the JSF runtime".  I understand in some way the 'javax.faces.webapp.FacesServlet" is the "entry point" to the JSF runtime. It is not clear to me what this consititues.
I gather it is something to do with lifecycle management (- an analogue for which i am faintly familiar with, from my knowledge of Serlvets + JSP - in it being a thing that does the calling of the constructor, the init() method, the Servlet's service() method and destroys the Servlet when the Container shutsdown). However, I suspect there is more to the JSF runtime than this. Should the JSF runtime simply be a thing limited to (and concerned only about) lifecycle management - I would most appreciate a little light being shed on what exactly this means for JSF (- though i understand what it means with Servlet's and JSP's), i do not see what this means specifically in terms of JSF, and would most appreciate guidance on this.

A: The exact phrase "the JSF runtime" is indeed mentioned a several times in the JSF  specification.

Upon completion of rendering, but before state saving the JSF runtime must publish a
javax.faces.event.PostRenderViewEvent. After doing so the JSF runtime must save the completed state
using the methods of the class StateManager. [...]

A JSF
implentation must support JSR 303 Bean Validation if the environment in which the JSF runtime is included requires
JSR 303 Bean Validation. [...]

The following method gives the JSF runtime access to the list of listeners stored by this instance.:
[...]

When the JSF runtime is directed to shutdown by its container, the following actions must be taken. [...]

There are by the way far more hits on the exact phrase "the runtime" in the very same JSF specification, but I'll leave up to you to find them.
It basically boils down to the currently configured and active JSF application. The entire JSF ecosystem with the FacesServlet, Lifecycle and Application being ready and waiting to process a HTTP request as a Faces request. Configured either as default or overridden/customized via faces-config.xml JSF deployment descriptor files and/or @FacesXxx annotated classes.
The FacesServlet is just a part of the JSF runtime. It indeed acts as the entry point of the ecosystem. If an incoming HttpServletRequest matches the URL pattern of the servlet mapping of the FacesServlet, then it will be invoked by the servletcontainer as usual. The FacesServlet will in turn create the FacesContext and process the request through the Lifecycle of the Application and finally destroy the FacesContext right before returning to servletcontainer.
See also:

*

*Picture/article which describes JSF lifecycle in detail

*Debugging JSF Life Cycle - what exactly happens in each phase

*What components are MVC in JSF MVC framework?


text:
Q: Putting a floating image in the bottom-right corner for example Basically I want to put a transparent image in the bottom-right corner. I read the questions about top-right, right, and so on. However, I can only apply margin-top: 100%; which will put it where I want BUT it shows the scroll bar then and the picture will be really at the bottom, I can't even see it.
Any ideas are welcome.

A: Try
right: 0px;
bottom: 0px;

Of course you'll need fixed positioning:
position: fixed;

This will make it stick to the bottom-right corner wherever the user scrolls.

A: Do it like:
background-image:url('someurl/image.png');
background-position:right bottom;
background-repeat:no-repeat;

Grz, Kris.


text:
Q: A question about the proof of Hilbert's Basis Theorem I have a question regarding the proof of Hilbert's Basis Theorem.
Say $I=(f_1,f_2,f_3,\dots)$ is an ideal in $A[x]$, where A is a Noetherian ring. Say we take the leading coefficients $a_i$ of all the polynomials generating $I$. Then the ideal $J$ generated by those coefficients will be finitely generated. We assume $J=(a_1,a_2,\dots,a_m)$. The proof says that $I=(f_1,f_2,\dots,f_m)$, where $f_i$ is the polynomial with leading coefficient $a_i$ for $i\in\{1,2,3,\dots,m\}$. How Hilbert goes about this (by successively selecting the polynomial of minimal degree) is well known, and can be seen in the link given.
My question is this:
Why does $f_i$ have to be the polynomial of minimal degree in $I$ for some $i\in\{1,2,3,\dots,m\}$? In fact, why do all $f_i$ have to be the minimal polynomials in the set $I\setminus (f_1,f_2,\dots,f_{i-1})$? I see no correlation between generating the ideal of leading coefficients and being the polynomial of lowest degree in $I$.


text:
Q: Difference between Auto and Star for TableColumn and GridColumn in WPF In Grid, Auto means the content width will define the column width, and Star means the column width will use the left space available.
However in Table, I find a different behavior. If you have 3 columns with the width: 100, Auto, 100; the width second column does not depend on its content. Instead, it uses the remaining space available as its width.
Moreover in Table, if you combine Star column with Auto or fixed pixel width column, the Star column will be very small, around 1 character width.
Could anyone explain whether this is a bug in Table, or it's simply the default behavior?

Additional info:
If I combine Auto with fixed width, the Auto column (the second) will use the remaining space available.

    <TableColumn Width="100"/>
    <TableColumn Width="Auto"/>
    <TableColumn Width="100"/>

  <TableRowGroup>
    <TableRow>
      <TableCell>...
      <TableCell>...
      <TableCell>...
    </TableRow>
  </TableRowGroup>

If I combine Star with fixed width or Auto, the Star column's width is very small, and the other columns will be divided equally on the remaining space available.

    <TableColumn Width="*"/>
    <TableColumn Width="100"/>
    <TableColumn Width="100"/>

  <TableRowGroup>
    <TableRow>
      <TableCell>...
      <TableCell>...
      <TableCell>...
    </TableRow>
  </TableRowGroup>

A: Okay I understand that this is not an answer as such, but since there's no one else responding at the moment, I figured I'd try to help out a little bit.
This appears to be a bug that's been around since at least WPF 4.0
https://connect.microsoft.com/VisualStudio/feedback/details/724483/the-width-of-tablecolumns-in-a-wpf-flowdocument-doesnt-work-with-non-star-widths
Tables appear to be relatively useless unless you're using the star notation, which, as near as I can tell basically functions more like a percentage, but there's some flaky behavior in there as well.
If you set everything to star it basically does the equivalent of auto across the board, but setting one or more elements to anything but star will cause the existing stars to occupy 1 percent the total width, likewise if you changed it to 50* it would take up 50 percent of the total width.
I know this isn't extremely helpful, but it's the best I could do.


text:
Q: The sum of unbounded sequence and bounded sequence in higher dimension Suppose we have $\{a_n\}, \{b_n\} \in R^L$ such that $\{a_n\}$ is unbounded while $\{b_n\}$ is bounded. Prove that ${a_n + b_n}$ is unbounded.
I can solve it for $L = 1$ in a roundabout way but I'm having trouble with higher dimension. I want to prove that
$$\forall K \in R: ||a_n + b_n|| > K$$ for $n$ sufficiently large. The want to find a lower bound for $||a_n + b_n||$ but cannot come up with a good one because the only inequality I know related to the sum of two sequences is the Triangle Inequality, and that doesn't help here.
EDIT: I made this mistake of saying that $||a_n + b_n||$ diverges to infinity.

A: You have
$$a_n = (a_n + b_n)-b_n$$
If $(a_n + b_n)$ was bounded, then $(a_n)$ would be the difference between two bounded sequences, and hence would be bounded. Contradiction.


text:
Q: How can I change an Icon in flutter when i add a new Entry in my Database? So i set up a working Realtime Database, to which i can add entries. Now i want to notify the user whenever a new entry was added to the Database by adding a little Red Dot to the Icon in the BottomNavigationBar which disappears again when the user has clicked it. Any ideas on how to achieve this?

A: I recommend using the badge package to achieve this. You will have to ensure the state updates using your own state management. If the user goes to the notification screen, you will need to trigger an update to mark notifications as read.
 return Badge(
          showBadge: unreadNotifications > 0,
          badgeContent: Text(
            '$unreadNotifications',
            style: kTextStyle,
          ),
          position: const BadgePosition(
            top: -3,
            end: 3,
          ),
          child: IconButton(
            icon: const Icon(
              Icons.notifications,
            ),
            onPressed: () {
              Navigator.pushNamed(context, NotificationScreen.id);
            },
          ),
        );


text:
Q: JSON parsing in swift different ways. Which one to use? I have been following a tutorial for JSON parsing in swift. It has the following mentioned codes for parsing and retrievig the data.
func jsonParsingFromURL () {
        let url = NSURL(string: "http://theappguruz.in//Apps/iOS/Temp/json.php")
        let request = NSURLRequest(URL: url!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
            self.startParsing(data!)
        }
    }

    func jsonParsingFromFile()
    {
        let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
        let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)

        self.startParsing(data)
    }

    func startParsing(data :NSData)
    {
        let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        for var i = 0 ; i < (dict.valueForKey("MONDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("MONDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("TUESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("TUESDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("WEDNESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("WEDNESDAY") as! NSArray) .objectAtIndex(i))
        }
        tvJSON .reloadData()
    }

This is fine but I am unable to understand what is going on at the line -
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                self.startParsing(data!)

I saw another tutorial which was using functions like the following to parse JSON-
//Making the API Request

var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
//Preparing for the response

// Declare an array as below
var data: NSMutableData = NSMutableData()

// Receiving the response
1.

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object
   self.data = NSMutableData()
}
2.

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
   self.data.appendData(data)
}
3.

func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, self.data should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results
      self.appsTableView.reloadData()

   }
}

So what is the difference between the above 2 coding and which one is advisable to use. Please also say something about
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                    self.startParsing(data!)

Thanks!

A: First, and most importantly, NSURLConnection is deprecated in iOS 9. You should be using NSURLSession instead.
As to your questions, they are about async network reads more than JSON parsing.
NSURLConnection:
NSURLConnection has at least 2 different ways you can use it.

*

*You can set up a delegate, start the connection, and wait for your delegate methods (like connection:didReceiveData:) to be called.

*You can use the class method sendAsynchronousRequest, which takes a completion block.

The sendAsynchronousRequest method is simpler to implement, but not as powerful. You don't get called until all the data has been received, so you can't do things like display a progress indicator, or save the data to disk as it comes in to avoid holding everything in memory.
If you don't need those things, I would suggest going with the block-based sendAsynchronousRequest method.
NSURLSession:
NSURLSession, the replacement for NSURLConnection, also offers both a delegate-based and a block-based approach, with pros and cons similar to those for NSURLConnection.
With NSURLSession, if you don't need fine-grained control it's easier to use the system's shared session (NSURLSession.sharedSession()). Then you create an NSURLSessionTask using the NSURLSession method dataTaskWithRequest:completionHandler: and start the task running with the resume() method. Just like NSURLConnection, it invokes your completion block (closure) when the download is complete.
NSURLSession also allows you to download your data directly to disk, set up secure connections, get your data in chunks as it is downloaded, and lots of other options (that you may or may not need.)
EDIT:
Here is an excerpt from the NSURLSession class reference about sharedSession:

*

*(NSURLSession *)sharedSession Discussion For basic requests, the URL session class provides a shared singleton session object that gives
  you a reasonable default behavior. By using the shared session, you
  can fetch the contents of a URL to memory with just a few lines of
  code.

  Unlike the other session types, you do not create the shared session;
  you merely request it by calling [NSURLSession sharedSession]. As a
  result, you don't provide a delegate or a configuration object.
  Therefore, with the shared session:
You cannot obtain data incrementally as it arrives from the server.
You cannot significantly customize the default connection behavior.
Your ability to perform authentication is limited.
You cannot perform background downloads or uploads while your app is
  not running.
The shared session uses the shared NSURLCache, NSHTTPCookieStorage,
  and NSURLCredentialStorage objects, uses a shared custom networking
  protocol list (configured with registerClass: and unregisterClass:),
  and is based on a default configuration.
When working with a shared session, you should generally avoid
  customizing the cache, cookie storage, or credential storage (unless
  you are already doing so with NSURLConnection), because there's a very
  good chance that you'll eventually outgrow the capabilities of the
  default session, at which point you'll have to rewrite all of those
  customizations in a manner that works with your custom URL sessions.
In other words, if you're doing anything with caches, cookies,
  authentication, or custom networking protocols, you should probably be
  using a [custom] session instead of the [shared] session.

(I fixed a couple of typos in Apple's docs in my quote. My changes are in square brackets in the last sentence.)
Do a search online for NSURLSession Swift or NSURLSessionDataTask Swift and you should be able to find tutorials on using NSURLSession. It's actually quite easy.
AlamoFire
You might also do a search on "AlamoFire". It's a lightweight Swift framework that offers easy async downloading including built-in JSON handling.


text:
Q: Column width is different on different computers I need to provide custom column width for my excel.  I'm achieving it with a getColumn method by setting a number of points to width property.
Main question is why on different computers I'm getting different column width both in pixels and points. Is it possible to have same value (at least in points) for all exported excels?
For example the width of column is set to 16 points: on first computer I got 15.36 points and 176px, on the second - 15.29 points and 112px.
Additional question: is it happening because of different monitor resolutions or because of excel settings?

A: This should work (according to the docs):

*

*Specify the style of your columns, e.g. Normal, and specify the Font and Font Size of that style on the source computer that creates the workbook.

*Explicitly set the Font and Font size of Normal Style on the target computer's Excel when opening the file to match that of the source computer.

By doing this you will have matched styles on the source and target computers, and hence experience the same column width.
PS: I'm assuming here that you are not using any Style other than Normal. If you are, then you will of course need to approach these styles appropriately.

A: The reason is different fonts available on each OS. Following by Ecma-376, widths and heights has digit size as a unit (ch or em unit from css). Setting sizes should work perfectly with an available font for all OS.


text:
Q: What are the best practices for writing unit tests with Mock frameworks I am new to mocking and I have goggled a lot for the best practices but till now I couldn't find any satisfying resource so I thought of putting in SO.
I have tried few test cases and had following doubts:

*

*Do you write a separate unit test for each method (public private etc) and mock other methods calls that's being invoked inside this method or you test only public method?

*Is it okay to verify the invocation of stubbed method at the end when testing a method that returns nothing e.g DB insertion?
Please add other practices also that are must to know.

A: There are many levels of testing. Unit testing is of a finer granularity to integration testing which you should research separately. Regrettably this is still quite a young area of the software engineering industry and as a result the terminology is being intermixed in ways not intended.
For unit testing you should write tests that determine if the behaviour of the class meets expectations. Once you have all such tests you should find any private methods are also tested as a consequence so no need to test private methods directly. If you only test behaviour, you should find your tests never need to change although the class under test may over time - you may of course need to increase the number of tests to compensate just never change the existing tests.
Each class, in a good design, should have minimal use of other classes (collaborators). Those collaborators that get mocked are often implementing infrastructure such as database access. Be wary of testing collaboration as this is more closely associated with a larger system test - mocking collaborators gives your unit test knowledge not only of how it behaves but also how it operates which is a different subject matter.
Sorry to be vague but you are embarking on a large topic and I wanted to be brief.


text:
Q: Deleting a word from a string I want to delete a specific word from a file.
Let's say the file name agent_file.txt contains below string
-queues winall,dustat,envstat,netstat,iostat,winconfig,netwarestat,netwareconfig,pawmin,paw15,db2,sqlserver,vmstatvmw2,vmstatvm2,netstatvm,netstatvmw,vmstatvm,vmstatvmw,iostatvm,iostatvmw,envstatvm,envstatvmw,vmscpu,vmsdisk,vmsmem,vmstatvcw,process,winprocess

I want to delete character or the word process only in this file, so I use below command under Unix
perl -pi -e 's/process//g' agent_file.txt

The output will be
-queues winall,dustat,envstat,netstat,iostat,winconfig,netwarestat,netwareconfig,pawmin,paw15,db2,sqlserver,vmstatvmw2,vmstatvm2,netstatvm,netstatvmw,vmstatvm,vmstatvmw,iostatvm,iostatvmw,envstatvm,envstatvmw,vmscpu,vmsdisk,vmsmem,vmstatvcw,,win

The word is deleted, but it also deletes part of winprocess.
How can I delete only process as well as a preceding comma , if there is one?
The output should be
-queues winall,dustat,envstat,netstat,iostat,winconfig,netwarestat,netwareconfig,pawmin,paw15,db2,sqlserver,vmstatvmw2,vmstatvm2,netstatvm,netstatvmw,vmstatvm,vmstatvmw,iostatvm,iostatvmw,envstatvm,envstatvmw,vmscpu,vmsdisk,vmsmem,vmstatvcw,winprocess

A: Use auto-splitting (-a) by comma (-F,), to avoid the comma-problem altogether
perl -F, -lane 'print join ",", grep { not /^process$/ } @F' input  > output

Input is broken up by , into @F. The grep filters out the word and the rest is joined back by ,
In order to change the input file in place add -i and drop > output
See Command switches in perlrun

The problem is that the first and last word have one comma, which needs to go if they are removed, while others have two commas where one needs to stay. One way with regex is to make two passes, removing the word and then extra commas (still be careful with first and last).
Or run code in the replacement part to select cases suitably
echo "go,stay,ago,go,got,end,go" |

    perl -pe's/(,)?\bgo\b(,)?/$1 && $2 && ","/ge'

Prints: stay,ago,got,end.  The /e evaluates the replacement side as Perl code.
If both commas are there ($1 && $2) then (&&) we replace with comma (",").
This works because in Perl && returns the value

The ||, // and && operators return the last value evaluated (unlike C's || and &&, which return 0 or 1).

A: Here's an awk solution.
awk 'BEGIN{OFS=FS=","} {for(i=1;i<=NF;i++) if($i=="process") $i=""} 1' file

This sets your field separator to comma for both input and output, and then steps through your fields, checking for equivalence against the string you're interested in and emptying the field if it matches.  The 1 at the end is awk short-hand for "print the current line".

Similarly, one could slice up input data by record instead of by field:
awk 'BEGIN{ORS=RS=","} /^process$/{next} 1' file

or
awk 'BEGIN{ORS=RS=","} $0=="process"{next} 1' file

This walks through your input using the comma as a RECORD separator (RS), so that individual words can be evaluated using awk's record-awareness. You can do your evaluation via regex or not -- regex is ever so slightly slower, but appears to save you two characters of typing. :-)
The strategy using RS/ORS eliminates the problem you noticed with the field being emptied but not removed. When the comma is a record separator, then a skipped record causes the record separator not to be shown, which is closer to the "ideal" output you've included in your question.

Last option might be to do this right inside your shell (ksh). This will have the advantage of greatest portability (you won't have to worry about perl version, whether awk/sed are GNU or BSD or something else). The disadvantage is that with the method below, your file size will be limited by your system memory (and perhaps configurable limits).
$ IFS=, read -A arr < file
$ for i in "${!arr[@]}"; do [[ "${arr[$i]}" == "process" ]] && unset arr[$i]; done
$ output=$(printf "%s," "${arr[@]}")
$ echo "${output%,}"
-queues winall,dustat,envstat,netstat,iostat,winconfig,netwarestat,netwareconfig,pawmin,paw15,db2,sqlserver,vmstatvmw2,vmstatvm2,netstatvm,netstatvmw,vmstatvm,vmstatvmw,iostatvm,iostatvmw,envstatvm,envstatvmw,vmscpu,vmsdisk,vmsmem,vmstatvcw,winprocess

Note that the $output variable is only required in order to strip the trailing comma generated by printf. Another option might be to set $IFS more globally:
$ IFS=,
$ echo "${arr[*]}"
-queues winall,dustat,envstat,netstat,iostat,winconfig,netwarestat,netwareconfig,pawmin,paw15,db2,sqlserver,vmstatvmw2,vmstatvm2,netstatvm,netstatvmw,vmstatvm,vmstatvmw,iostatvm,iostatvmw,envstatvm,envstatvmw,vmscpu,vmsdisk,vmsmem,vmstatvcw,winprocess

I should point out that despite appearances, the printf option doesn't really spawn external commands, because ksh implements printf as a built-in.

A: you can do in three steps
sed 's/,process,/,/g;s/^process,//;s/,process$//'

testing for positions,: in-between, beginning or at the end.

A: If it's comma separated use them to your advantage for making it a word.
perl -pi -e "s/, \s* process\s* , /, /g filename

If there is not going to be spaces after or before comma then remove \s*

A: Like this perhaps?
It  searches for all occurrences of process, using word boundaries to ensure that it isn't found as part of another word, and also matching optional commas , before and after. The match is replaced by a single comma if two commas were found (process was found in the middle of the list) and deleted if there was only one (process appears only at the beginning or end of the list)
perl -pi -e 's/ ,? \b process \b ,? ) / $1 =~ tr/,// > 1 ? ',' : '' /xge' agent_file.txt

A: awk '{sub(/process,/,"")}1' file


text:
Q: The collapsed navigation bar button is not expanding when clicked in CodePen CodePen link: http://codepen.io/mraduldubey/pen/OMmzYV?editors=100
Here is the navigation bar's code. This collapsed button expands in Tryit Editor of w3cschools website but doesn't expand in CodePen:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                Toggle navigation

            </button>
            Mradul Dubey

Home

About

Portfolio

Contact

A: You are probably not referencing the jquery, bootstrap.js and bootstrap.css in your code. Here is your code on jsfiddle and codepen...
JSFiddle
CodePen


text:
Q: combine word document using python docx I have few word files that each have specific content. I would like for a snippet that show me or help me to figure out how to combine the word files into one file, while using Python docx library.
For example in pywin32 library I did the following:
rng = self.doc.Range(0, 0)
for d in data:
    time.sleep(0.05)

    docstart = d.wordDoc.Content.Start
    self.word.Visible = True
    docend = d.wordDoc.Content.End - 1
    location = d.wordDoc.Range(docstart, docend).Copy()
    rng.Paste()
    rng.Collapse(0)
    rng.InsertBreak(win32.constants.wdPageBreak)

But I need to do it while using Python docx library instead of win32.client

A: If your needs are simple, something like this might work:
source_document = Document('source.docx')
target_document = Document()

for paragraph in source_document.paragraphs:
    text = paragraph.text
    target_document.add_paragraph(text)

There are additional things you can do, but that should get you started.
It turns out that copying content from one Word file to another is quite complex in the general case, involving things like reconciling styles present in the source document that may be conflicting in the target document for example. So it's not a feature we're likely to be adding in the next year, say.

A: Create an empty document (empty.docx) and add your two documents to this.
On each loop of the iteration over the files, add a page break if necessary.
On completion save the new file that contains your two combined files.
from docx import Document

files = ['file1.docx', 'file2.docx']

def combine_word_documents(files):
    combined_document = Document('empty.docx')
    count, number_of_files = 0, len(files)
    for file in files:
        sub_doc = Document(file)

        # Don't add a page break if you've
        # reached the last file.
        if count < number_of_files - 1:
            sub_doc.add_page_break()

        for element in sub_doc._document_part.body._element:
            combined_document._document_part.body._element.append(element)
        count += 1

    combined_document.save('combined_word_documents.docx')

combine_word_documents(files)

A: The alternative approach to merge two documents including all the styles is to use python library docxcompose ( https://pypi.org/project/docxcompose/) . We do not need to explicitly define the styling and we do not have to read the document paragraph by paragraph and append it to the master document. The usage of the python docxcompose is shown in the below code
#Importing the required packages

from docxcompose.composer import Composer
from docx import Document as Document_compose
#filename_master is name of the file you want to merge the docx file into
master = Document_compose(filename_master)

composer = Composer(master)
#filename_second_docx is the name of the second docx file
doc2 = Document_compose(filename_second_docx)
#append the doc2 into the master using composer.append function
composer.append(doc2)
#Save the combined docx with a name
composer.save("combined.docx")

If you want to merge multiple documents into one docx file you can use the below function

#Filename_master is the name of the file you want to merge all the document into
#files_list is a list containing all the filename of the docx file to be merged
def combine_all_docx(filename_master,files_list):
    number_of_sections=len(files_list)
    master = Document_compose(filename_master)
    composer = Composer(master)
    for i in range(0, number_of_sections):
        doc_temp = Document_compose(files_list[i])
        composer.append(doc_temp)
    composer.save("combined_file.docx")
#For Example
#filename_master="file1.docx"
#files_list=["file2.docx","file3.docx","file4.docx",file5.docx"]
#Calling the function
#combine_all_docx(filename_master,files_list)
#This function will combine all the document in the array files_list into the file1.docx and save the merged document into combined_file.docx

A: If you just need to combine simple documents with only text, you can use python-docx as mentioned above.
If you need to merge documents containing hyperlinks, images, lists, bullet points etc. You can do this using lxml to combine the document body and all the reference files, like:

*

*word/styles.xml

*word/numbering.xml

*word/media

*[Content_Types].xml

A: I've adjusted the example above to work with the latest version of python-docx (0.8.6 at the time of writing). Note that this just copies the elements (merging styles of elements is more complicated to do):
from docx import Document

files = ['file1.docx', 'file2.docx']

def combine_word_documents(files):
    merged_document = Document()

    for index, file in enumerate(files):
        sub_doc = Document(file)

        # Don't add a page break if you've reached the last file.
        if index < len(files)-1:
           sub_doc.add_page_break()

        for element in sub_doc.element.body:
            merged_document.element.body.append(element)

    merged_document.save('merged.docx')

combine_word_documents(files)

A: This is all very useful. I combined the answers of Martijn Jacobs and Mr Kriss.
def combine_word_documents(input_files):
    """
    :param input_files: an iterable with full paths to docs
    :return: a Document object with the merged files
    """
    for filnr, file in enumerate(input_files):
        # in my case the docx templates are in a FileField of Django, add the MEDIA_ROOT, discard the next 2 lines if not appropriate for you.
        if 'offerte_template' in file:
            file = os.path.join(settings.MEDIA_ROOT, file)

        if filnr == 0:
            merged_document = Document(file)
            merged_document.add_page_break()

        else:
            sub_doc = Document(file)

            # Don't add a page break if you've reached the last file.
            if filnr < len(input_files)-1:
                sub_doc.add_page_break()

            for element in sub_doc.element.body:
                merged_document.element.body.append(element)

    return merged_document

A: Another alternative solution is Aspose.Words Cloud SDK for Python. It retains the formatting/style of the documents based on ImportFormatMode parameter. The parameter defines which formatting will be used: appended or destination document. Possible values are KeepSourceFormatting or UseDestinationStyles.
# For complete examples and data files, please go to https://github.com/aspose-words-cloud/aspose-words-cloud-python
import os
import asposewordscloud
import asposewordscloud.models.requests
from shutil import copyfile

# Please get your Client ID and Secret from https://dashboard.aspose.cloud.
client_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx'
client_secret='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

words_api = asposewordscloud.WordsApi(client_id,client_secret)
words_api.api_client.configuration.host='https://api.aspose.cloud'

remoteFolder = 'Temp'
localFolder = 'C:/Temp'
localFileName = 'destination.docx'
remoteFileName = 'destination.docx'
localFileName1 = 'source.docx'
remoteFileName1 = 'source.docx'

#upload file
words_api.upload_file(asposewordscloud.models.requests.UploadFileRequest(open(localFolder + '/' + localFileName,'rb'),remoteFolder + '/' + remoteFileName))
words_api.upload_file(asposewordscloud.models.requests.UploadFileRequest(open(localFolder + '/' + localFileName1,'rb'),remoteFolder + '/' + remoteFileName1))

#append Word documents
requestDocumentListDocumentEntries0 = asposewordscloud.DocumentEntry(href=remoteFolder + '/' + remoteFileName1, import_format_mode='KeepSourceFormatting')

requestDocumentListDocumentEntries = [requestDocumentListDocumentEntries0]
requestDocumentList = asposewordscloud.DocumentEntryList(document_entries=requestDocumentListDocumentEntries)
request = asposewordscloud.models.requests.AppendDocumentRequest(name=remoteFileName, document_list=requestDocumentList, folder=remoteFolder, dest_file_name= remoteFolder + '/' + remoteFileName)

result = words_api.append_document(request)

#download file
request_download=asposewordscloud.models.requests.DownloadFileRequest(remoteFolder + '/' + remoteFileName)
response_download = words_api.download_file(request_download)
copyfile(response_download, localFolder + '/' +"Append_output.docx")


text:
Q: I am getting the errors when i am running the command the qtl seq downloaded by conda. I am running following command [QTL-seq:2019-10-09 09:13:37] !!ERROR!! bcftools concat -a -O z -o Chikpea_qtl/30_vcf/qtlseq.vcf.gz Chikpea_qtl/30_vcf/qtlseq.*.vcf.gz >> Chikpea_qtl/log/bcftools.log 2>&1
Failed to open Chikpea_qtl/30_vcf/qtlseq.NW_004516646.1.vcf.gz: could not load index

Traceback (most recent call last):
File "/home/jthakur/Desktop/Software/QTL-seq/qtlseq/mpileup.py", line 191, in concat

check=True)
File "/home/jthakur/anaconda2/lib/python3.6/subprocess.py", line 438, in run

output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'bcftools concat -a -O z -o Chikpea_qtl/30_vcf/qtlseq.vcf.gz Chikpea_qtl/30_vcf/qtlseq.*.vcf.gz >> Chikpea_qtl/log/bcftools.log 2>&1' returned non-zero exit status 255.
Traceback (most recent call last):

File "/home/jthakur/anaconda2/bin/qtlseq", line 11, in
load_entry_point('qtlseq', 'console_scripts', 'qtlseq')()
File "/home/jthakur/Desktop/Software/QTL-seq/qtlseq/qtlseq.py", line 192, in main

QTLseq(args).run()
File "/home/jthakur/Desktop/Software/QTL-seq/qtlseq/qtlseq.py", line 123, in mpileup

mp.run()
File "/home/jthakur/Desktop/Software/QTL-seq/qtlseq/mpileup.py", line 232, in run

self.concat()
File "/home/jthakur/Desktop/Software/QTL-seq/qtlseq/mpileup.py", line 194, in concat

sys.exit()
NameError: name 'sys' is not defined


text:
Q: Adding Suffixes to labels I have some labels that have a mathematical formula attached to them and i was wondering how you add a suffix to them. I am aware of one way to add prefixes
LblUsername.Text = "Welcome " & TxtUsername.Text

I have tried to add the suffix like this
Label1.Text = ((2 * TextBox1.Text * 0.707106781) / 9.8) & "Seconds"

But to no avail, any help would be greatly appreciated

A: Convert string to integer before calculating.
Label1.Text = ((2 * Ctype(TextBox1.Text, integer) * 0.707106781) / 9.8).ToString & "Seconds"


text:
Q: How to fallback in a table? I'm making a registration page in HTML. I'm using placeholder for inputs, but I am aware that some major browsers (IE <9, Firefox <3.7,  Chrome/Safari <4.0) don't support this HTML5 feature.
My favourite way to fallback for placeholder is this code, which doesn't require any Modernizr or other JavaScript:
<audio>Username: </audio>

<input type="text" placeholder="Username">

The problem is that this registration form is into a table, and fallbacking doesn't work - it shows the fallback text, too:

    <audio>

            Username:

    </audio>

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

So, how should I do the fallback? I am aware of Modernizr and other JS libraries, but I'd prefer to avoid them due to the low upload speed of my server and as a general guideline.
Also, I didn't consider using <audio>Fallback</audio>	 due to issues with the graphical issues (adds horizontal white space, also styling the td may give problems).

A: You don't need any fallback if you have an explicit label for any input field, which is recommended for accessibility and usability.
It would be rather strange to rely on the assumption that a browser supports the audio element if and only if it supports the placeholder attribute. For example, IE 9 supports audio but not placeholder.
A more reasonable approach (to removing the label when placeholder is supported, which is IMHO a non-problem) is to add a piece of JavaScript that checks whether placeholder is recognized as an attribute and remove the label if it is. The risk with this is that a browser may recognize the attribute without actually supporting it. The safest way seems to be to create an input element in JavaScript and check whether the object has the placeholder property:

            Username:

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


text:
Q: How to make Chrome and/or Firefox play  elements in Karma tests? I'm working on a library that can extract audio from HTML5 <audio> and <video> elements and send it to a remote server for speech-to-text processing. (e.g. automatic subtitles.) When I test manually, everything works as expected, but when karma runs my test, it always fails for <audio> elements.
For context, HTML5 audio script processors immediately get a stream of audio as soon as they are connected to an <audio> element, but it's all 0's (no sound) until the element begins playing.
When my tests run in karma, it appears that the element never begins playing; I just get 0's even though I've called .play() on the element. Also, I don't hear any audio coming out of my speakers, which should happen at the same time.
(I get that audio during tests could be super-annoying and probably should be disabled by default, but is there a way to enable it for cases like mine?)
If you're interested in seeing the code, it's at https://github.com/watson-developer-cloud/speech-javascript-sdk but it's still a bit of a mess, and is currently configured to skip the tests that would fail. If necessary, I'll try and set up a stripped down example, but I'm hoping I won't need to.
I'm on OS X if it makes a difference. I haven't tried this on Windows or Linux yet.

A: Found it, at least for firefox. <audio> elements apparently have stronger CORS rules than I realized! I was setting a Access-Control-Allow-Origin: * header on my file server, because I knew it was on a different port then where Karma was running my tests, but apparently that's not enough.
I can't seem to find any documentation on this anywhere, but I happened to notice a chrome Error about CORS and did a little more digging & experimentation. It seems that scriptProcessors for cross-domain <audio> elements need the the same crossOrigin attribute that <img> tags need to use their content in a <canvas>.
So, in the end, going from
  var audioElement = new Audio();
  audioElement.src = "http://localhost:9877/audio.wav";

to
  var audioElement = new Audio();
  audioElement.crossOrigin = "anonymous";
  audioElement.src = "http://localhost:9877/audio.wav";

Solved the issue for me in firefox, and chrome works sometimes but seems to have some other issues (perhaps related to load time?).
I believe the second issue in chrome is that I was calling .play() right away and then ending my test when it emitted an ended event.. but that event seems to also fire when the buffer runs empty, which I think is a bug. I changed it to wait on the canplaythrough event before calling .play() and it seems to be reliably passing the test now.

A: Some browser implementations will block attempts to automatically play <audio> elements unless a user interaction has occurred (for obvious reasons).
There are several suggestions in this similar question, but they are all attempting to circumvent a designed feature and would probably not be very reliable across multiple browsers / devices.
Depending on your setup and which browsers you are targeting, you might need to factor in a 'click to start' button in your test.


text:
Q: Ms Excel Problem Linking Range in Source Document to Custom Function in Target Document I have some customer MS Excel VBA code (MS Excel 2007) that takes a range as input and then does some work on it (it is quite a large range).  I want to use a separate excel document as the source of the range data.  If I have both the source and target document open then the function works just fine.  If I have only the target document open I get #Value! returned and stepping through in the debugger I see "Error 2023" in the data value passed in.  Any ideas how I make this work without having to open both spreadsheets simultaneously?

A: I am not sure if I have understood the problem correctly; as you have mentioned that there are 2 excel spreadsheets viz source and target and since you would be referring both you should have both the spreadsheets open.
Are you looking for a solution to open the reference spreadsheet automatically?
Cheers... Nilesh