text:
Q: An error about "make_shared",I can't understand #include<algorithm>
#include<string>
#include<new>
#include<memory>
#include<vector>
using std::vector;
using namespace std;
int main()
{

    shared_ptr<vector<int> > pointer=make_shared<vector<int>> ({2,3,5,8});
    cout<<(*pointer)[3];
    return 0;

so make_shared can't initialize like ({2,3,5,8}),why?
    }

A: The function make_shared cannot forward intializer lists. If you need to use an initializer list constructor, you have to invoke the shared_ptr constructor directly.


text:
Q: Android notifications - what way should I pick for my app? My app is like Facebook. Every user has a friends list. The users can publish a status and the user's friends should get a notification immediately.
After doing some research I found out that most people recommend using GCM. I don't know if I should go in that way. First of all, I understood that I need to have an access to web resource? I really don't know what that means, can someone explain me that? Second, I realized that there is a lot of Terms for the users, like they should have a Google account and Android 2.2 or more. Isn't all that things make a big problem?
My biggest problem with GCM is that I'm noob with that kind of things and I don't think I can handle with it. Maybe Someone can show me a good tutorial? since the Android tutorial didn't really help me.
If I won't pick the GCM, there is another nice way and maybe easy of sending that kind of notifications - real time, when the database is changing? Can someone show me a tutorial?
Thank you very much, this is very important to me.

A: http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
I liked the tutorial hope it will be helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Populating a 2D array of objects using given probability in Java I have been given a task to create a program which models cell growth according to some given rules. To do this, I have to create a 2D array and populate it with Cell objects which are either living or dead according to a given probability. So far, I've been able to create what I think is an array of these objects, but I'm not sure how I would go about using the probability I've been given to assign "dead" or "normal" status to each object. This is what I've done so far (not that much I know...):
public class CellGrid
{
    // Store the cells of the game in this 2D array
    private Cell[][] cells;

    /**
     * Contructor for a CellGrid. Populates the grid with cells that will be
     * living and normal (with probability given by lifeChance) or dead. Cells
     * will NOT start mutated.
     *
     * @param size
     *            the size of the grid will be size x size
     * @param lifeChance
     *            the probability of each cell starting out alive
     * @param mutationChance
     *            the probability that (when required) each cell will mutate
     */
    public CellGrid(int size, double lifeChance, double mutationChance)
    {
        Cell[][] cells = new Cell[size][size];

        //populates the array with new Cell objects
        for (int i = 0; i < size; i++)
        {
            for (int j = 0; j < size; j++)
            {
                cells[i][j]= new Cell();

            }
        }

A: You can use a random value.
Random r = new Random();
double nextVal = r.nextDouble();

nextVal is then: 0 <= nextVal < 1
you can now set all cells where nextVal < lifeChance.
If lifeChance will be 0.1, then 10 percent of your cells will be alive.
...
Random r = new Random();
for (int j = 0; j < size; j++)
{
    Cell c = new Cell();
    double nextVal = r.nextDouble();
    if(nextVal < lifeChance){
        c.setLife(true);
    } else{
        c.setLife(false);
    }
    cells[i][j]= c;
}

You have to change setLife() according to your class spec...

A: What you want is this :
public CellGrid(int size, double lifeChance, double mutationChance)
    {
        cells = new Cell[size][size];
        Random r = new Random();
        for(int i=0; i<size; i++) {
            for(int j=0; j<size; j++) {
                double nextVal = r.nextDouble();
                if(nextVal < lifeChance){
                    cells[i][j] = new NormalCell();
                } else{
                    cells[i][j] = new DeadCell();
                }
            }
        }

    }

I have completed full CellGrid class implementation. Let me know if you need help.


text:
Q: Which windows docker base image use for .net 3.5 wcf application I am trying to containerize legacy .Net 3.5 WCF applications using docker. I am not able to successfully run the container.
I have tried the following base images
microsoft/dotnet-framework:3.5
microsoft/aspnet:4.7.2-windowsservercore-1803
mcr.microsoft.com/windows/servercore:ltsc2019
any help would be appreciated.

A: I advise you to adopt the official images to dockerize the WCF.  There are some official Docker images published in the DockerHub.
https://hub.docker.com/_/microsoft-dotnet-framework-wcf/?tab=description
In addition, here are some samples of Dockerizing WCF service, either IIS-hosted or self-hosted.
https://github.com/Microsoft/dotnet-framework-docker/tree/master/samples/wcfapp
Feel free to let me know if there is anything I can help with.


text:
Q: Address Book Program I'm doing an address book as part of a school assignment and I have it mostly figured out, but I'm stuck on one part. Here's my code first. I have an AddressBook class that contains variables and appropriate getter and setter methods to change/return the information for each person in the book. Then I have a TestAddressBook class with a method main that demonstrates how the address book works. The only thing I'm stuck on is the final requirement, where I'm asked to compare two names and see if they're equal and print the results. I have the program designed the way I want it but for some reason when I do the comparison, it doesn't print the comparison results. It just prints nothing at all. I've got to be missing something obvious. Here's the code for the classes.
AddressBook...
public class AddressBook {

private String firstName;
private String middleName;
private String lastName;
private String homeAddress;
private String homePhone;
private String cellPhone;
private String businessPhone;
private String skypeId;
private String facebookId;
private String personalWebSite;

public AddressBook(String firstName, String middleName, String lastName,
                   String homeAddress, String homePhone, String cellPhone,
                   String businessPhone, String skypeID, String facebookID,
                   String personalWebSite) {

                        this.firstName = firstName;
                        this.middleName = middleName;
                        this.lastName  = lastName;
                        this.homeAddress = homeAddress;
                        this.homePhone = homePhone;
                        this.cellPhone = cellPhone;
                        this.businessPhone = businessPhone;
                        this.skypeId = skypeID;
                        this.facebookId = facebookID;
                        this.personalWebSite = personalWebSite;
                        }

public AddressBook(String firstName) {
    this.firstName = firstName;
}

public AddressBook(String firstName, String middleName) {
    this.firstName = firstName;
    this.middleName = middleName;
}

public AddressBook(String firstName, String middleName, String lastName) {
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getMiddleName() {
    return middleName;
}

public void setMiddleName(String middleName) {
    this.middleName = middleName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getHomeAddress() {
    return homeAddress;
}

public void setHomeAddress(String homeAddress) {
    this.homeAddress = homeAddress;
}

public String getHomePhone() {
    return homePhone;
}

public void setHomePhone(String homePhone) {
    this.homePhone = homePhone;
}

public String getCellPhone() {
    return cellPhone;
}

public void setCellPhone(String cellPhone) {
    this.cellPhone = cellPhone;
}

public String getBusinessPhone() {
    return businessPhone;
}

public void setBusinessPhone(String businessPhone) {
    this.businessPhone = businessPhone;
}

public String getSkypeId() {
    return skypeId;
}

public void setSkypeId(String skypeId) {
    this.skypeId = skypeId;
}

public String getFacebookId() {
    return facebookId;
}

public void setFacebookId(String facebookId) {
    this.facebookId = facebookId;
}

public String getPersonalWebSite() {
    return personalWebSite;
}

public void setPersonalWebSite(String personalWebSite) {
    this.personalWebSite = personalWebSite;
}

public static String compareNames(String name1, String name2) {
    String nameEquals;
    if ( name1.equals(name2) ) {
        nameEquals = (name1 + " and " + name2 + " are equal names.");
        return nameEquals;
    }
    else {
        nameEquals = (name1 + " and " + name2 + " are not equal names.");
        return nameEquals;
    }
}

}
Test Class...
public class TestAddressBook {

public static void main(String[] args) {

    System.out.println("ENTRY 1");

    AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                         "222-321-8371", "222-423-2382",
                                         "222-438-2918", "bob483", "bobfb493",
                                         "http://www.freewebhost.com/bob848");

    System.out.println( "First Name:        " + entry1.getFirstName() );
    System.out.println( "Middle Name:       " + entry1.getMiddleName() );
    System.out.println( "Last  Name:        " + entry1.getLastName() );
    System.out.println( "Address:           " + entry1.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry1.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
    System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry1.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
    System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

    System.out.println("\nENTRY 2");

    AddressBook entry2 = new AddressBook("Bruce", "Allan", "Carter", "56 Outtamy Way",
                                         "564-342-8372", "564-283-9832",
                                         "564-293-3489", "brucie392", "brucieface28",
                                         "http://www.freewebhost.com/carteristheman");

    System.out.println( "First Name:        " + entry2.getFirstName() );
    System.out.println( "Middle Name:       " + entry2.getMiddleName() );
    System.out.println( "Last  Name:        " + entry2.getLastName() );
    System.out.println( "Address:           " + entry2.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry2.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
    System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry2.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
    System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

    System.out.println("\nENTRY 3");

    AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                         "736-453-1238", "736-392-2385",
                                         "736-926-2439", "anniep", "susananne",
                                         "http://www.freewebhost.com/Susanspage");

    System.out.println( "First Name:        " + entry3.getFirstName() );
    System.out.println( "Middle Name:       " + entry3.getMiddleName() );
    System.out.println( "Last  Name:        " + entry3.getLastName() );
    System.out.println( "Address:           " + entry3.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry3.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
    System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry3.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
    System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

    AddressBook.compareNames(entry1.getFirstName() + " " +
                             entry1.getMiddleName().charAt(0) + " " +
                             entry1.getLastName(),
                             entry2.getFirstName() + " " +
                             entry2.getMiddleName().charAt(0) + " " +
                             entry2.getLastName() );

}

}

A: well you have it good look at this
package teteo;

public class TestAddressBook {

    public static void main(String[] args) {

        System.out.println("ENTRY 1");

        AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                             "222-321-8371", "222-423-2382",
                                             "222-438-2918", "bob483", "bobfb493",
                                             "http://www.freewebhost.com/bob848");

        System.out.println( "First Name:        " + entry1.getFirstName() );
        System.out.println( "Middle Name:       " + entry1.getMiddleName() );
        System.out.println( "Last  Name:        " + entry1.getLastName() );
        System.out.println( "Address:           " + entry1.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry1.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
        System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry1.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
        System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

        System.out.println("\nENTRY 2");

        AddressBook entry2 = new AddressBook("Robert", "James", "Smith", "56 Outtamy Way",
                                             "564-342-8372", "564-283-9832",
                                             "564-293-3489", "brucie392", "brucieface28",
                                             "http://www.freewebhost.com/carteristheman");

        System.out.println( "First Name:        " + entry2.getFirstName() );
        System.out.println( "Middle Name:       " + entry2.getMiddleName() );
        System.out.println( "Last  Name:        " + entry2.getLastName() );
        System.out.println( "Address:           " + entry2.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry2.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
        System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry2.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
        System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

        System.out.println("\nENTRY 3");

        AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                             "736-453-1238", "736-392-2385",
                                             "736-926-2439", "anniep", "susananne",
                                             "http://www.freewebhost.com/Susanspage");

        System.out.println( "First Name:        " + entry3.getFirstName() );
        System.out.println( "Middle Name:       " + entry3.getMiddleName() );
        System.out.println( "Last  Name:        " + entry3.getLastName() );
        System.out.println( "Address:           " + entry3.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry3.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
        System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry3.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
        System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

      String equal =   AddressBook.compareNames(entry1.getFirstName() + " " +
                                 entry1.getMiddleName().charAt(0) + " " +
                                 entry1.getLastName(),
                                 entry2.getFirstName() + " " +
                                 entry2.getMiddleName().charAt(0) + " " +
                                 entry2.getLastName() );

System.out.println(equal);

}
}

now it is equals, but you must know that in order to do this you should use
compareTo() or comparable look at this
https://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html
What would happen if you use a map? where it depends of a key, you will get duplicate values, i mean if you won't use that it is ok your code, but if you will use it then look an eye in there :)


text:
Q: How to parse Retrofit JSON response I have a typical Retrofit API request:
RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(URL)
        .build();

ApiEndpointInterface api = restAdapter.create(ApiEndpointInterface.class);

api.getToken('1', new Callback<DefaultResponse>() {
    @Override
    public void success(DefaultResponse json, Response response) {
        //
    }

    @Override
    public void failure(RetrofitError response) {
        //
    }
});

And the returned JSON is:
{"success":true,"data":{"token_id":"pPt9AKl0Cg","token_key":"8ax224sFrJZZkStAQuER"}}

How can I parse this JSON? It seems wrong/tedious to create a new model class for each different response across my app. Is there a better way to do it?

A: you should write your model class like below
public class MyResponseModel {//write setters and getters.
        private boolean success;
        private DataModel data;

    public static class DataModel {
        private String token_id;
        private String token_key;
    }
}

now  in your getToken() method should look like this
getToken('1', Callback<MyResponseModel> response);

retrofit will parse the response and convert it to the class above.

A: Try this code,
JsonElement je = new JsonParser().parse(s);
JsonObject asJsonObject = je.getAsJsonObject();
JsonElement get = asJsonObject.get("data");
System.out.println(s + "\n" + get);
JsonObject asJsonObject1 = get.getAsJsonObject();
JsonElement get1 = asJsonObject1.get("token_id");
System.out.println(get1);
JsonElement get2 = asJsonObject1.get("token_key");
System.out.println(get2);


text:
Q: how to crop area of an image inside a rectangle or a squre?
First of all I take the picture and then I draw a rectangle over it. Now I just want to crop the image inside the rectangle. I tried drawing contours but that didn't work out in my case. I am stuck on it.
import cv2
import numpy as np

img = cv2.imread("C:/Users/hp/Desktop/segmentation/abc.jpg", 0);
h, w = img.shape[:2]
kernel = np.ones((15,15),np.uint8)

e = cv2.erode(img,kernel,iterations = 2)
d = cv2.dilate(e,kernel,iterations = 1)
ret, th = cv2.threshold(d, 150, 255, cv2.THRESH_BINARY_INV)

mask = np.zeros((h+2, w+2), np.uint8)
# cv2.floodFill(th, mask, (200,200), 255); # position = (200,200)
out = cv2.bitwise_not(th)
out= cv2.dilate(out,kernel,iterations = 3)
cnt, h = cv2.findContours(out,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(cnt)):
            area = cv2.contourArea(cnt[i])
            if(area>100):
                  mask = np.zeros_like(img)
                  cv2.drawContours(mask, cnt, i, 255, -1)
                  x,y,w,h = cv2.boundingRect(cnt[i])
                  crop= img[ y:h+y,x:w+x]
                  cv2.imshow("snip",crop )
                  if(cv2.waitKey(0))==27:break

cv2.destroyAllWindows()

A: import cv2
import numpy as np

img = cv2.imread('WwsqC.jpg');
h, w = img.shape[:2]
thresh=7
im_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
x_proj=np.median(im_gray, axis=0)
y_proj=np.median(im_gray, axis=1)

rows = np.where(x_proj<thresh)[0]
cols = np.where(y_proj<thresh)[0]
crop=img[cols[0]:cols[-1], rows[0]:rows[-1] ]

cv2.imwrite('WwsqC.png', crop)

A: Taking into consideration that the rectangle is black, and there is no other large black elements connected here is the code which crops the rectangle inside:
import cv2
import numpy as np

img  = cv2.imread("abc.jpg", 0);
h, w = img.shape[:2]
# print(img.shape)
kernel = np.ones((3,3),np.uint8)

img2 = img.copy()
img2[img2!=0]=255
img2 = 255 - img2
img2 = cv2.dilate(img2, kernel)
img2 = cv2.medianBlur(img2, 9)
img2 = cv2.medianBlur(img2, 9)

position = np.where(img2 !=0)
x0 = position[0].min()
x1 = position[0].max()
y0 = position[1].min()
y1 = position[1].max()

print(x0,x1,y0,y1)

result = img[x0:x1,y0:y1]
result = cv2.resize(result,(800,800))
# rect = cv2.resize(np.hstack((img,img2)),(1000,700))

cv2.imshow('anything', result)
cv2.waitKey(0)
cv2.destroyAllWindows()


text:
Q: FabricJS image filter with no fragmentSource? I have a filter that isn't compatible with WebGL. Is there a way to skip writing a fragmentSource? I tried overriding fabric.Image.filters.BaseFilter applyTo on the filter subclass to only call this.applyTo2d(options); but I'm not getting any image data.
applyTo: function(options) {
    if (options.webgl) {
      if (options.passes > 1 && this.isNeutralState(options)) {
        // avoid doing something that we do not need
        return;
      }
      this._setupFrameBuffer(options);
      this.applyToWebGL(options);
      this._swapTextures(options);
    }
    else if (!this.isNeutralState()) {
      this.applyTo2d(options);
    }
  },

A: I as able to accomplish this in a non-optimized way with minimal code in webgl_backend.class.js.
First, the webgl backend needs a fallback for non-webgl filters:
this.fallback2dBackend = new fabric.Canvas2dFilterBackend();
Then, instead of running all filters: fabric.filterBackend.applyFilters(filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);
Do this:
  var newSource = fabric.util.createCanvasElement();
  newSource.width = sourceWidth;
  newSource.height = sourceHeight;
  var newSourceCtx = newSource.getContext('2d');
  newSourceCtx.drawImage(this._originalElement, 0, 0, sourceWidth, sourceHeight);

  filters.forEach(function(filter) {
    if (!filter) {
      return;
    }
    var backend = fabric.filterBackend;
    if (filter.fragmentSource === null) {
      backend = backend.fallback2dBackend;
    }

    backend.applyFilters(
      [filter], newSource, sourceWidth, sourceHeight, this._element);

    newSourceCtx.clearRect(0, 0, sourceWidth, sourceHeight);
    newSourceCtx.drawImage(this._element, 0, 0, sourceWidth, sourceHeight);

  }, this);

I've published a fork in case someone wants to refactor this into a PR.


text:
Q: cannot run a app in studio android. SelectDeploymentTarget i have a problem in my Studio android program which is:
     i can't run my app when my select deployment target window show up,
     and just that message show up:
 "missing feature (WATCH)", and the pgm prepose to me those tow things:

*No USB devices or running emulators detected.
*VT-x is desabled in BIOS.[https://i.stack.imgur.com/MfdeY.jpg][1]

 [https://i.stack.imgur.com/S4mnB.jpg][2]

A: To run an Android app, Android Studio needs either a real physical android device or a virtual machine to run the code on.  Those are referred to as Deployment Targets.  Those messages mean that you do not have a physical Android device plugged in (or the drivers are not set up so that a device is recognized, or some other such reason), and that your computer's CPU doesn't have virtualization turned on in order for you to have a virtual Android device.  You can change this in your BIOS settings if your CPU does have virtulization, and then you'd have to create a virtual device using the virtual device manager that comes with the SDK.
Note: I am not sure if the virtualization NEEDS to be turned on for a virtual device or if it just ENHANCES a virtual device's performance.  In any case, you don't have a virtual device and the virtualization capabilities of your processor are not turned on.


text:
Q: PowerShell Invoke RestMethod response as file to PDF I am using invoke-restmethod GET in Powershell which produces a PDF file as a response.
I can see that file as an encoded format in the PowerShell window.
I need to create a PDF file from the response.

How to achieve?

A: Use the -OutFile parameter:
Invoke-RestMethod $uri -Method Get -OutFile output.pdf


text:
Q: What does "Runs" means in Tensorboard Profile Page? I am profiling my deep model using TensorFlow profile plugin. After the profiling, I can see multiple folders under the path-to-log-dir/plugins/profile/. And from the Profile page, I can see there're multiple Runs options.

Why there're multiple "Runs"? How are they generated?

A: These are multiple logs of runs. Each of which stored in the logs folder.
For example you can define a separate folder for each run using time like this:
from datetime import datetime

logdir = "logs/training/" + datetime.now().strftime("%Y%m%d-%H%M%S")

tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir = logdir,
                                                      histogram_freq = 1)

Each time you run the above code, a new folder will be created under logs/training/. Also you may get multiple folders in each run of the line where you passed the callback e.g. model.fit(callbacks=[tensorboard_callback]), which each of them belongs to a separate run (for example one will be created for training, and one for validation logs):

*

*logs/training/20210804-114159

*logs/training/20210804-114211
Then when you run tensorboard in parent folder:
%tensorboard --logdir logs/training

You can select each run you want to show profiled data.


text:
Q: Working with Conditional Formatting and Multiple Rules I have two columns. 1st column is an expected completion date (ECD). 2nd column is a actual completion date (ACD), which starts out blank. I want the ECD to turn red if its date is in the past...easy. I want the ECD to turn back to white if there is an ACD filled in.
To me the formula would be: =AND(A3:A5 < TODAY(), B3:B5 IS NOT BLANK) But that formula is not allowed.
Can someone please help?

A: When you setup conditional formatting you have to be very careful about how you specify things. When setting up your formulas you only reference the 1st row of your AppliesTo range, excel will adjust the references as it moves down the range. Of course this will be different if you are referencing cells that are not in your first row. If referencing constants remember to use the $ for the rows/columns that don't change.
In this specific case the formula you want is: =AND(A3<(TODAY()),B3=0,A3<>0)


text:
Q: Missing libgcc_s_dw2-1.dll I have a Windows 7 64bit system with the latest MinGW (32bit) installed along with the Qt 5.5 SDK (again 32bit) which also ships with its own MinGW. Due to the fact that I'm not the only one using the system I can't remove the standalone MinGW.
My project is using qmake and is a plain C project (not C++). Everything builds fine but when I try to execute my binary in the command line I get that the application was unable to start due to a missing libgcc_s_dw2-1.dll on the system.
After looking into the issue I found that both the standalone MinGW and the one shipped alongside the Qt SDK have the mentioned DLL.

*

*Standalone MinGW - libgcc_s_dw2-1.dll is located inside the bin subdirectory of the MinGW installation where the binaries are located (gcc, g++, gdb etc.)

*Qt MinGW - libgcc_s_dw2-1.dll is located inside C:\Qt\Tools\mingw492_32\i686-w64-mingw32\lib subdirectory while the MinGW components' binaries are inside C:\Qt\Tools\mingw492_32\i686-w64-mingw32\bin.

I would like to know how to properly set my PATH variable so that:

*

*The application starts properly

*No conflicts with the standalone MinGW installation occur

Just a side-note: I've already checked other posts here on SO but was unable to find a solution (perhaps I've missed it). I have also tried LIBS += -static but the result is the same.

A: You just need to copy this dll with your executable, i.e.:
cp <path-to-qt-install-dir>\qt5.7.0\5.7\mingw53_32\bin\libgcc_s_dw2-1.dll <path-to-dest-dir>
You mat find that you have other dependencies, to see which other deps you have you can use: ldd <your-executable>. You only need to copy the qt specific dlls you can see these by:
ldd <executable> | grep -i qt
note
You can statically link it with:
linker commands like -static-libgcc or -static, but I think you start to hit LGPL issues and also you may need to statically compile qt from source - can't recall for this particular file.
note2
Sorry ldd is for linux, just realized you have windows, in which case you can use one or both of:

*

*dependency walker: from here

*<path-to-qt-bin-folder>\windeployqt.exe <path-to-your-executable>
I have mixed results with windeployqt, but if you have any plugins its quiet good for getting that part sorted.


text:
Q: How do I upload an image using FTP with Objective-C? (mac app, not iOS) Does anyone know if there's a built in method/object I can use or an existing library? I have the host, post, username, password, path to the image (local) and destination path (remote). The sever suports 'sftp' and 'ftp', I don't think I can upload via http.

A: It's pretty easy. CFFTPSample (P.S. or it was SimpleFTPSample?) - demo app from XCode documentation. Run it, it does exactly you ask for.
Or read an article: Working with FTP Servers


text:
Q: setInterval doesn't work on .css method (no looping) I'm using setInterval to try to rotate an image every 3 seconds and am using the below code:
jQuery:
$(document).ready(function(){
    setInterval(function(){
        $bird_wing_left.css({
            transform: "rotate(30deg)"
        }, 1000)
    }, 3000);
});

CSS:
.bird_wing_left {
    background: rgba(0, 0, 0, 0) url("../images/bird_wing_left.png") repeat scroll 0 0;
    height: 59px;
    left: 17px;
    position: absolute;
    top: 66px;
    width: 78px;
    transition: all 2s;
}

...but the animation only happens once and not every 3 seconds. If I try another method (not .css), it's ok. What could be the issue?

A: It's rotating to 30 degrees, not by 30 degrees.  You need to keep track of how far it's already rotated:
$(document).ready(function(){
    var rotate = 0;
    setInterval(function(){
        rotate += 30;
        $bird_wing_left.css({
            transform: "rotate(" + rotate + "deg)"
        }, 1000)
    }, 3000);
});

A: You rotate your image always to 30 degree and after the first rotation its rotation is 30° so it wont rotate anymore. You need to save the count of the degrees in a var and increase it with every iteration (also try to set it to 0 when it hits 360).


text:
Q: Finding out which is the failed drive on Intel SRCASRB RAID Controller There is very old server with Intel RAID SRCASRB Controller with 4 x WD5003ABYX-0 500GB drives connected to it in RAID5 array.
One of those drives has failed and I want to replace it. Since server is old tower case, drives are screwed manually into 3.5" bays. There is no HDD backplane, so there is no LED indicating which drive has failed.
Intel RAID Web Console 2 only shows disk model number and doesn't show serial number, so I have no clue which drive should I replace.

Any ideas how to find out which physical drive has failed?

A: Turns out I had old v2.XX Web Console 2 version. Upgraded to v15.XX where they included detection of drive serial numbers.


text:
Q: No accounts with App Store Connect access have been found for the team Xcode 11.7 I added my .p12 file to keychain and my signing certificate selected in Xcode, when I try to Product > Archive > Distribute App I get the error:

I tried everything in this link No accounts with iTunes Connect access have been found for the team.
But my error still same.
How can i fix this error

A: To be able to upload an app to App Store Connect you will need to add your App Store Connect account to Xcode. Adding the certificates only allows you to build and sign the app, but not to upload it to App Store Connect.
In Xcode go to Preferences > Accounts > Add the account you want to upload the app to.


text:
Q: DT output takes me to 1st page when i edit a reactive DT I have a toy version of my code below. I have one of the columns (column 7) in my shiny DT output as editable. When i edit the a cell of the column it takes me back to the first row of of the column. I checked the data table object in environment, the edited cell does get update. So, that is good. But i want to stay on the same page after editing the cell. This is because a user may have applied a few filters to reach a certain page and then when he edits a cell he would like to continue from there rather than going back to start.
I am new to R so any help would be greatly appreciated.
I am using DT 0.7
My data frame has 7 columns: Continent, State, Country, Date, Rate (Pollution), Vehicles, Remark (editable column)
A user can filter the table output by select input, range and slider input. I want to make that output editable.
Thanks in advance!
library(shiny)
library(DT)

ui <- navbarPage("Hello",
  tabPanel("Tab1",
           sidebarLayout(
             sidebarPanel( width = 4,
               selectInput("continent", "Select:",
                           choices = ""),

               selectInput("country" , "Select:",
                            choices = ""),

               selectInput("state" , "Select:",
                           choices = ""),

               dateRangeInput("date", "Select:",
                              startview = "month",
                              minview = "months",
                              maxview = "decades",
                              start = as.Date('1999-01-01'),
                              end = as.Date(today()),
                              separator = "-"),

               sliderInput("rate", "Select:",
                           min = 1, max = 5, value = c(1,5),
                           dragRange = TRUE)),

               mainPanel(
                 tabsetPanel(
                   tabPanel("Analysis",
                             dataTableOutput("Table1")

           )))))

#server
server <- function(input, output, session)
{

  observe({
    updateSelectInput(session, "continent",
                             choices = c("All", unique(Df$Continent)))
    })

  observe({
    updateSelectInput(session, "country",
                      choices = c("All", Df %>%
                        filter(`Continent` == input$continent) %>%
                        select(Country)))
  })

  observe({
    updateSelectInput(session, "state",
                      choices = c("All", Df %>%
                        filter(`Continent` == input$continent &
                                 `Country` == input$country) %>%
                        select(State)))
  })

  #create reactive table
  RecTable <- reactive({

    Df
      if(input$continent != "All") {
        Df <- Df[Df$Continent == input$continent,]
      }

      if(input$country != "All") {
        Df <- Df[Df$Country == input$country,]
      }

      if(input$state != "All") {
        Df <- Df[Df$State == input$state,]
      }

      Df <- Df %>%
        filter(Date >= input$date[1] & Date <= input$date[2]) %>%
        filter(Rate >= input$rate[1] & Rate <= input$rate[2])

      Df})

  output$Table1 <- DT::renderDT({
    DT::datatable(RecTable(),
                  rownames = FALSE ,
                  editable = list(target = 'cell', disable = list(columns = c(0:6))))

  })

  proxy1 <- dataTableProxy('Table1')

  observeEvent(input$Table1_cell_edit, {

    Df <<- editData(Df, input$Table1_cell_edit, 'Table1', rownames = FALSE, resetPaging = FALSE)

     })}

#run
shinyApp(ui = ui, server = server)


text:
Q: Yii how to highlight the current label $this->breadcrumbs=array(
   'Dailymarket Reports',
);

$this->menu=array(
   array('label'=>'inbox', 'url'=>array('index')),
   array('label'=>'sent', 'url'=>array('sent')),
);

Above I have two labels. I want inbox to be default active label if mouse moves out and selects sent as active it should be highlighted.

A: If you want to add active class for specified items:
$this->menu = array(
    array(
        'label' => 'inbox', 'url' => array('index'),
        'active' => $this->action->id === 'index' ? true : null,
    ),
    array(
        'label' => 'sent', 'url' => array('sent'),
        'active' => $this->action->id === 'sent' ? true : null,
    ),
);

You need to style items with active class yourself.

You may also omit specifying url for current item, so it will be displayed as text instead of link:
$this->menu = array(
    array(
        'label' => 'inbox',
        'url' => $this->action->id === 'index' ? null : array('index'),
    ),
    array(
        'label' => 'sent',
        'url' => $this->action->id === 'sent' ? null : array('sent'),
    ),
);

A: I think you are asking about how to show the menu item selected according to the current route if you are on Home page then the Home menu item should be selected.
Although you can see solutions like adding checks but if you provide full path to your link you won't have to add any further checks for activating the menu items, just make sure you are not passing activateItems=>false inside the CMenu widget in the layout file, otherwise it defaults to true and it decides whether to automatically activate items according to whether their route setting matches the currently requested route.
Go to your view where you are adding the menu specify a full path like /controller/action for your links for example if I have a menu for the site controller SiteController actions I will provide paths like below.
$this->menu=array(
   array('label'=>'Home', 'url'=>array('/site/index')),
   array('label'=>'Demo', 'url'=>array('/site/demo')),
);

and that's it you can make it work if you don't need to add separate checks for every menu item.
Just make sure you have a css class for li.active > a so that you can get the highlighted effect,


text:
Q: return values in next line in file on every invocation of script. MIDI Command line sequencer So i have a file "scenes.txt", containing a 2-column set of numbers, about 500 lines in total:
0 01
6 22
5 03
4 97
7 05
3 98
2 99
9 00 etc...

First column range is 0-9, second column range is 0-99. The 2 fields are tab-separated.
On each invocation of the shell script, I want the script to output the set of the 2 numbers from the next line in the list to 2 variables.
So if I run the script for the first time, var1 should be 0 and var2 should be 01, on the next run of the script var1 should be 6 and var2 should be 22, and so on...
These values are going to the sendmidi command, https://github.com/gbevin/SendMIDI, to control a piece of hardware via MIDI.
You could call it a clumsy MIDI command line sequencer.
what I tried so far: I created a bash script "test1":
#!/bin/bash
read LINECNT <  pointer
echo "next line to be processed: $LINECNT"
VAR1=$(sed "${LINECNT}q;d" scenes.txt)
echo "Line and Variables: $LINECNT: $VAR1"
# here the actual magic happens:
/usr/local/bin/sendmidi dev "USB2.0-MIDI Anschluss 2" cc 32 $VAR1 PC $VAR2
((LINECNT++))
echo $LINECNT > pointer

and another file named "pointer", which just holds the pointer position for the value to output upon next invocation.
File pointer:
1

This results in:
[dirk@dirks-MacBook-Pro] ~
❯ ./test2
next line to be processed: 1
Line and Variables: 1: 0 01

[dirk@dirks-MacBook-Pro] ~
❯ ./test2
next line to be processed: 2
Line and Variables: 2: 6 22

[dirk@dirks-MacBook-Pro] ~
❯ ./test2
next line to be processed: 3
Line and Variables: 3: 5 03

[dirk@dirks-MacBook-Pro] ~
❯ ./test2
next line to be processed: 4
Line and Variables: 4: 4 97

[dirk@dirks-MacBook-Pro] ~
❯ ./test2
next line to be processed: 5
Line and Variables: 5: 7 05

My Problem:
There are two Values in each line of "scenes.txt", but the
VAR=$(sed "${LINECNT}q;d" scenes.txt) line only gives the whole line with both values.
I tried several "cut" modifications, like this
VAR1=cut -f1 - $(sed "${LINECNT}q;d" scenes.txt)
VAR2=$(cut -f2 $(sed "${LINECNT}q;d" scenes.txt))

but with no luck...
How do I push the two values from that line into VAR1 and VAR2?

A: Your sed commands are incorrect. Also, the variables can be read with a single read command:
#!/bin/bash

read -r linecnt < pointer
read -r var1 var2 < <(sed "$linecnt!d; q" scenes.txt)
/usr/local/bin/sendmidi dev "USB2.0-MIDI Anschluss 2" cc 32 "$var1" PC "$var2"
echo $((linecnt + 1)) > pointer

I changed your variable names to lower case since, by convention, capitalized variables are environment variables and internal shell variables.

A: IFS='\t'
arr=($VAR1)
/usr/local/bin/sendmidi dev "USB2.0-MIDI Anschluss 2" cc 32 ${arr[0]} PC ${arr[1]}


text:
Q: addView() by inflating a layout causes the layout parameters to fail The preview design of following XML below look like this

XML
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card="http://schemas.android.com/apk/res-auto"
        android:id="@+id/cdvConfirm"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        card:cardBackgroundColor="#fff"
        card:cardCornerRadius="2dp"
        card:cardElevation="2dp"
        android:focusable="true"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground">

    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp">

        <CheckBox
                android:id="@+id/ckbConfirm"
                android:layout_width="20dp"
                android:layout_height="20dp"
                android:layout_marginTop="16dp"
                android:layout_marginRight="10dp"
                android:layout_marginEnd="10dp"
                android:button="@drawable/checkbox_default"
                android:scaleType="fitCenter"

                />

        <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

            <TextView
                    android:id="@+id/tvShipmentType"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:layout_toLeftOf="@+id/btnDetail"
                    android:layout_toStartOf="@+id/btnDetail"
                    android:paddingTop="5dp"
                    android:paddingBottom="5dp"
                    android:text="Title"
                    android:textStyle="bold"
                    android:textColor="@android:color/black"
                    />

            <TextView
                    android:id="@+id/tvShipmentDescription"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentStart="true"
                    android:layout_alignParentLeft="true"
                    android:layout_toLeftOf="@+id/btnDetail"
                    android:layout_toStartOf="@+id/btnDetail"
                    android:layout_below="@+id/tvShipmentType"
                    android:text="No Appointment Date No Appointment Date No Appointment Date No Appointment Date"
                    android:singleLine="false"
                    android:ellipsize="end"
                    android:textSize="14sp"
                    android:textColor="@android:color/darker_gray"
                    android:textStyle="bold"
                    />

            <TextView
                    android:id="@+id/tvAlert"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/tvShipmentDescription"
                    android:layout_marginTop="15dp"
                    android:textColor="#D50000"
                    android:text="** ยังไม่ได้ทำการเลือกรายการนี้"
                    android:visibility="invisible"
                    />

            <Button
                    android:id="@+id/btnDetail"
                    android:layout_width="wrap_content"
                    android:layout_height="50dp"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_marginLeft="8dp"
                    android:layout_marginStart="8dp"
                    android:padding="10dp"
                    android:text="รายละเอียด"
                    android:background="#81C784"
                    android:src="@drawable/menu_complete"
                    android:scaleType="fitCenter"
                    />

        </RelativeLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

But when I addView() dynamically by inflate XML file by following code below it look like this. It seem that toLeftOf doesn't work.

CODE
private void addCardView(int id, String type, String description) {
    View v = View.inflate(this, R.layout.listitem_complete_confirm, null);
    CheckBox ckbConfirm = (CheckBox) v.findViewById(R.id.ckbConfirm);
    TextView tvShipmentType = (TextView) v.findViewById(R.id.tvShipmentType);
    TextView tvShipmentDescription = (TextView) v.findViewById(R.id.tvShipmentDescription);
    TextView tvAlert = (TextView) v.findViewById(R.id.tvAlert);
    Button btnDetail = (Button) v.findViewById(R.id.btnDetail);

    tvShipmentType.setText(type);
    tvShipmentDescription.setText(description);
    btnDetail.setId(id);
    btnDetail.setOnClickListener(this);
    ckbConfirm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setButtonDrawable(R.drawable.checkbox_default);
                tvAlert.setVisibility(View.INVISIBLE);
            }
        }
    });

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
    );
    int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
    params.setMargins(margin, margin, margin, 0);
    llContainer.addView(v, params);
}

How can I solved this issues it seem like some value was ignore when
inflate the XML file and use of addView(). Please advice.

A: Change your XML file with that:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cdvConfirm"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    card:cardBackgroundColor="#fff"
    card:cardCornerRadius="2dp"
    card:cardElevation="2dp"
    android:focusable="true"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:gravity="center_vertical|center_horizontal">

        <CheckBox
            android:id="@+id/ckbConfirm"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:button="@drawable/checkbox_default"
            android:scaleType="fitCenter"

            />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="0.70">

                        <TextView
                            android:id="@+id/tvShipmentType"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentLeft="true"
                            android:layout_toLeftOf="@+id/btnDetail"
                            android:layout_toStartOf="@+id/btnDetail"
                            android:paddingTop="5dp"
                            android:paddingBottom="5dp"
                            android:text="Title"
                            android:textStyle="bold"
                            android:textColor="@android:color/black"
                            />

                        <TextView
                            android:id="@+id/tvShipmentDescription"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_alignParentStart="true"
                            android:layout_alignParentLeft="true"
                            android:layout_toLeftOf="@+id/btnDetail"
                            android:layout_toStartOf="@+id/btnDetail"
                            android:layout_below="@+id/tvShipmentType"
                            android:text="No Appointment Date No Appointment Date No Appointment Date No Appointment Date"
                            android:singleLine="false"
                            android:ellipsize="end"
                            android:textSize="14sp"
                            android:textColor="@android:color/darker_gray"
                            android:textStyle="bold"
                            />

                    </LinearLayout>

                    <LinearLayout
                        android:orientation="horizontal"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="0.30"
                        android:gravity="center_vertical|center_horizontal">

                        <Button
                            android:id="@+id/btnDetail"
                            android:layout_width="wrap_content"
                            android:layout_height="50dp"
                            android:layout_alignParentEnd="true"
                            android:layout_alignParentRight="true"
                            android:padding="10dp"
                            android:text="รายละเอียด"
                            android:background="#81C784"
                            android:src="@drawable/menu_complete"
                            android:scaleType="fitCenter"
                            />
                    </LinearLayout>
                </LinearLayout>

                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="15dp">

                    <TextView
                        android:id="@+id/tvAlert"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_below="@+id/tvShipmentDescription"
                        android:textColor="#D50000"
                        android:text="** ยังไม่ได้ทำการเลือกรายการนี้"
                        android:visibility="invisible"
                        />
                </LinearLayout>
            </LinearLayout>

        </RelativeLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>

It's a better option because I used to weight instead numbers on height or width.
Weight it's like a percents on screen that XML will be adapted to any screen resolution.

A: When inflating with null param the layout params will be ignored. This is how you inflate:
View v = View.inflate(this, R.layout.listitem_complete_confirm, null);

Inflate with parent container and to not append. This would look like this:
View v = View.inflate(this, R.layout.listitem_complete_confirm, container/parentView, false);

Your container or parent view must be a ViewGroup.

A: You need to change your .xml file.
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cdvConfirm"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    card:cardBackgroundColor="#fff"
    card:cardCornerRadius="2dp"
    card:cardElevation="2dp"
    android:focusable="true"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground">

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

    <CheckBox
            android:id="@+id/ckbConfirm"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginTop="16dp"
            android:layout_marginRight="10dp"
            android:layout_marginEnd="10dp"
            android:button="@drawable/checkbox_default"
            android:scaleType="fitCenter"

            />

    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <TextView
                android:id="@+id/tvShipmentType"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_toLeftOf="@+id/btnDetail"
                android:layout_toStartOf="@+id/btnDetail"
                android:paddingTop="5dp"
                android:paddingBottom="5dp"
                android:text="Title"
                android:textStyle="bold"
                android:textColor="@android:color/black"
                />

        <TextView
                android:id="@+id/tvShipmentDescription"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentStart="true"
                android:layout_alignParentLeft="true"
                android:layout_toLeftOf="@+id/btnDetail"
                android:layout_toStartOf="@+id/btnDetail"
                android:layout_below="@+id/tvShipmentType"
                android:layout_marginRight="5dp"
                android:layout_marginEnd="5dp"
                android:text="No Appointment Date No Appointment Date No Appointment Date No Appointment Date"
                android:singleLine="false"
                android:ellipsize="end"
                android:textSize="14sp"
                android:textColor="@android:color/darker_gray"
                android:textStyle="bold"
                />

        <TextView
                android:id="@+id/tvAlert"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/tvShipmentDescription"
                android:layout_marginTop="15dp"
                android:textColor="#D50000"
                android:text="** ยังไม่ได้ทำการเลือกรายการนี้"
                android:visibility="invisible"
                />

        <Button
                android:id="@+id/btnDetail"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="8dp"
                android:layout_marginStart="8dp"
                android:padding="10dp"
                android:text="รายละเอียด"
                android:background="#81C784"
                android:src="@drawable/menu_complete"
                android:scaleType="fitCenter"
                />

    </RelativeLayout>

</LinearLayout>


text:
Q: SFDX CLI: Error authenticating with the refresh token due to: inactive user After running the command:
sfdx force:auth:web:login --setalias vscodeOrg --setdefaultdevhubusername

And getting a successful result:

Successfully authorized robs@example.com with org ID 00D4J000000EmuiXXX

I then run the command:
sfdx force:org:shape:list

And get this error:

Error (1): Error authenticating with the refresh token due to: inactive user

I am the system admin on the org.
Why is this happening and how do I fix it?

A: First, You need to log out your user with the following command
sfdx force:auth:logout -u robs@example.com.dev
Close the project/VSCode and reopen again
And then you have to authorise again against the org.


text:
Q: Center point approximation of a polygon I would like to get a center point approximation of a set of polygons so I can do a NN lookup to use for assignment instead of a point in polygon query.
Lets say I have this set of polygons:

I would like to calculate a set of centerpoints that approximates the polygon when used in a NN lookup:

Does anybody have a clue to achieve this (Python/postgis preferred)? And does anybody have a pointer to any algorithms that can achieve this?

A: I'm not sure of what problem you are trying to solve and the criteria defining these "center points", but one possible approach might be to compute the Straight skeleton of the polygon and then use the interior vertices of the skeleton as your "center points".

One such algorithm for simple polygons is described in:

*

*Cheng, Siu-Wing; Vigneron, Antoine (2002). "Motorcycle graphs and straight skeletons". Proceedings of the 13th Annual ACM-SIAM Symposium on Discrete Algorithms. pp. 156–165.


text:
Q: Getting oracle.jdbc.driver.LogicalConnection, need oracle.jdbc.OracleConnection I am trying to connect to an Oracle database inside a Java application running on WebSphere. I need to be able to create an array descriptor to use in a call to a procedure.
The code looks like this:
Connection conn=null;
ArrayDescriptor arrayDescriptor;
Connection tmpCon = jdbcTemplate.getDataSource().getConnection();
conn =  WSCallHelper.getNativeConnection(tmpCon);
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",conn);
IDs = new oracle.sql.ARRAY(arrayDescriptor, conn, list.toArray());

The line that calls ArrayDescriptor.createDescriptor throws a class cast exception

java.lang.ClassCastException: oracle.jdbc.driver.LogicalConnection incompatible with oracle.jdbc.OracleConnection
    at oracle.sql.ArrayDescriptor.createDescriptor(ArrayDescriptor.java:149)
    at oracle.sql.ArrayDescriptor.createDescriptor(ArrayDescriptor.java:115)

Walking through this with the debugger, I can see that conn is definitely a oracle.jdbc.driver.LogicalConnection. The problem is I can't actually reference LogicalConnection in my code because that class is not public, so I can't just do something like this:
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",((LogicalConnection)conn).getWrapper());

.
And this:
arrayDescriptor = ArrayDescriptor.createDescriptor("t_my_array",((oracle.jdbc.driver.OracleConnection)conn).getWrapper());

also returns a class cast exception:
java.lang.ClassCastException: oracle.jdbc.driver.LogicalConnection incompatible with oracle.jdbc.driver.OracleConnection
I need to have an OracleConnection object, but I can't seem to get one from the LogicalConnection that gets returned to me. Has anyone ever seen this before? I feel I'm missing something really obvious here, but maybe I just need another cup of coffee...

A: @Alex Poole pointed me in the right direction. Maven was including an Oracle jar, version 10.2.0.1.0, and WebSphere had the same jar, but version 10.2.0.4.0.
After fixing the POM so that the 10.2.0.1.0 version jar didn't get deployed, the problem seems to be resolved.


text:
Q: Representation theorem for quadratic form on Hilbert space I think my question is more suitable for Mathematics Stack Exchange than to MathOverflow but I've already posted two related questions there and I got even more confused, so maybe I can clarify things here. I'm studying spectral theory by myself as part of my research activity and the following question arose.
Let $H$ be a Hilbert space and $Q: \mathcal{H}\to \mathbb{C}$ a function such that:
(1) There exists $C>0$ such that $|Q(x)| \le C||x||^{2}$ for every $x\in H$
(2) $Q(x+y)+Q(x-y) = 2Q(x) + 2Q(y)$ for every $x,y \in H$ and
(3) $Q(\lambda x) = |\lambda|^{2}Q(x)$ for every $x \in H$ and $\lambda \in \mathbb{C}$.
Question: Is there some bounded linear operator $A \in H$ such that $Q(x) = \langle Ax, x\rangle$?
The answer to this question seems to be affirmative and a sketch of a possible approach is given here (page 7, Lemma 12.2.7). The idea is to define:
\begin{eqnarray}
\Psi(x,y) = \frac{1}{4}[Q(x+y)-Q(x-y)+iQ(x+iy)-iQ(x-iy)] \tag{1}\label{1}
\end{eqnarray}
where $\{e_{\alpha}\}_{\alpha \in I}$ is an orthonormal basis of $H$ and then define $A$ by means of the rule:
\begin{eqnarray}
Ax = \sum_{\alpha \in I}\Psi(x,e_{\alpha})e_{\alpha}\tag{2}\label{2}
\end{eqnarray}
But I'm puzzled with this approach since I was not able to prove that $\sum_{\alpha \in I}\Psi(x,e_{\alpha})e_{\alpha}$ converges in the first place. All I could prove was $|\Psi(x,y)| \le K(||x||^{2}+||y||^{2})$ for some $K > 0$. As you can see in my previous post on math stack, it seems that the convergence problem is a bit tricky indeed.
In summary: I don't know how to prove that (\ref{2}) converges and, thus, I don't quite understand the proof of the result. However, I believe it's possible to find a more direct proof, maybe using Riesz Representation Theorem ideas (although $Q$ here is not linear) or something like that. I'd appreciate any help on either way.

A: There is indeed a simple proof using the Riesz representation theorem. First note that replacing $x$ by $\lambda^{-1}x$ and $y$ by $\lambda y$ in $\lvert \Psi(x,y)\rvert\leq K(\lVert x\rVert^2+\lVert y\rVert^2)$, you get $\lVert \Psi(x,y)\rvert\leq K(\lambda^{-2}\lVert x\rVert^2+\lambda^2\lVert y\rVert^2)$. With $\lambda=\lVert x\rVert^{1/2}\lVert y\rVert^{-1/2}$ this gives
$$
\lvert \Psi(x,y)\rvert\leq 2K\lVert x\rVert \lVert y\rVert.
$$
Thus for every $x\in H$ there exists $A(x)\in H$ such that $\Psi(x,y)=\langle A(x),y\rangle$ for $y\in H$ by the Riesz representation theorem. Since $\Psi$ is sesquilinear, the map $x\mapsto A(x)$ is linear, and moreover,
$$
\lVert A(x)\rVert=\sup_{\lVert y\rVert=1}\lvert \Psi(x,y)\rvert\leq 2K\lVert x\rVert,
$$
so that $A$ is also bounded.

A: I think this is a fine question for mathoverflow. There does indeed seem to be a convergence issue. However, it can be finessed by restricting to the span of some finite subset of the basis. Then we are working on a finite dimensional space and convergence is trivial. Next, use the uniqueness of $A$ to show that when we pass to a larger finite subset the values $\langle Ax,x\rangle$ do not change. We can also use (1) to get a uniform bound on the norms of the partial versions of $A$, so that they do ultimately yield a bounded operator on all of $H$.

A: Too long for a comment. Let:
$$\tilde{\Psi}(x,y) := Q(x+y)-Q(x-y)$$
Fact 1: $\tilde{\Psi}(x+z,y) = \tilde{\Psi}(x,y)+\tilde{\Psi}(z,y)$, for every $x,y,z \in H$.
Proof: Let us evaluate the difference $\tilde{\Psi}(x+z,y)-\tilde{\Psi}(x,y)-\tilde{\Psi}(z,y)$. We have:
$$\tilde{\Psi}(x+z,y)-\tilde{\Psi}(x,y)-\tilde{\Psi}(z,y) = Q(x+z-y)-Q(x+z-y)-Q(x+y)+Q(x-y)-Q(z+y)+Q(z-y)$$
Now, note that:
\begin{align}
Q(x-y)-Q(z-y) &= \frac{1}{2}[Q(x-y+z-y)+Q(x-y-z+y)] \\ &= \frac{1}{2}[Q(x+z-2y)+Q(x-z)]
\end{align}
and also:
\begin{align}
Q(x+y)+Q(z+y) &= \frac{1}{2}[Q(x+y+z+y)+Q(x+y-z-y)] \\&= \frac{1}{2}[Q(x+z+2y)+Q(x-z)]
\end{align}
Thus, we get:
$$\tilde{\Psi}(x+z,y)-\tilde{\Psi}(x,y)-\tilde{\Psi}(z,y) = Q(x+z+y)-Q(x+z-y)+\frac{1}{2}Q(x+z-2y)-\frac{1}{2}Q(x+z+2y)$$
Moreover:
\begin{align}
Q(x+z+y)-\frac{1}{2}Q(\overbrace{x+z+2y}^{=x+z+y+y}) &= \frac{1}{2}Q(x+z+y-y)-Q(y) \\&= \frac{1}{2}Q(x+z)-Q(y)
\end{align}
and also:
\begin{align}
Q(x+z-y)-\frac{1}{2}Q(\overbrace{x+z-2y}^{=x+z-y-y}) &= \frac{1}{2}Q(x+z-y+y)-Q(y) \\&= \frac{1}{2}Q(x+z)-Q(y)
\end{align}
and this proves the result.
Fact 2: $\tilde{\Psi}(-x,y) = -\tilde{\Psi}(x,y)$
Fact 3: $\tilde{\Psi}(y,x) = Q(y+x)-Q(y-x) = Q(x+y)-Q(x-y) = \tilde{\Psi}(x,y)$
Fact 4: In particular, Fact 1 + Fact 2 lead to $\tilde{\Psi}(kx,y) = k\tilde{\Psi}(x,y)$ for every $x,y \in H$ and $k \in \mathbb{Z}$.
Fact 5: Let $b \in \mathbb{Z}\setminus \{0\}$. Then, $\tilde{\Psi}(x,\frac{1}{b}y) = \frac{1}{b}\tilde{\Psi}(x,y)$.
Proof: Note that:
$$\tilde{\Psi}(x,\frac{1}{b}y) = Q(x+\frac{1}{b}y)-Q(x-\frac{1}{b}y) = \frac{1}{b^{2}}[Q(bx+y)-Q(bx-y)] = \frac{1}{b^{2}}\tilde{\Psi}(bx,y) = \frac{1}{b}\tilde{\Psi}(x,y)$$
where, in the last equality, I used fact 4.
Fact 6: $\tilde{\Psi}(x,y+z) = \tilde{\Psi}(x,y)+\tilde{\Psi}(x,z)$
Proof: By fact 3, $\tilde{\Psi}(x,y+z) = \tilde{\Psi}(y+z,x) = \tilde{\Psi}(y,x)+\tilde{\Psi}(z,x) = \tilde{\Psi}(x,y)+\tilde{\Psi}(x,z)$
Fact 7: Set $\hat{\Psi}(x,y) := iQ(x+iy)-iQ(x-iy) = i\tilde{\Psi}(x,iy)$. Then all the above facts also hold for $\hat{\Psi}(x,y)$.
Fact 8: $|\Psi(x,y)|\le K(||x||^{2}+||y||^{2})$ implies $\Psi$ is continuous in the product topology.
Now, according to MaoWao's answer, the result follows from the Riesz Representation Theorem if $\Psi(x,y)$ is sesquilinear. It is easy to see that $-i\Psi(x,y) = \Psi(x,iy)$. Finally, let $\alpha = a+ib \in \mathbb{C}$. Then, we have:
$$\Psi(x,\alpha y) = \Psi(x,ay+iby) = \Psi(x,ay)-i\Psi(x,by)$$
Thus, find sequences $\{a_{n}\}_{n\in \mathbb{N}}$ and $\{b_{n}\}_{n\in \mathbb{N}}$ of rational numbers such that $a_{n}\to a$ and $b_{n}\to b$ and use the continuity of $\Psi$ to prove that it is anti-linear in the $y$ entry. The same reasoning leads us to the linearity in the $x$ entry. This, together with MaoWao's answer should be enough to prove the result.


text:
Q: Newly added layers to QGIS 2.18 will not display in the print composer I have an existing QGIS project that until today was just fine.  I added a new shapefile to the project but these new data fail to display in the print composer.  All other existing data in the project display just fine as do the other map elements in the print composer.  I have made no other alterations to the project or the print composer layout other than adding these data.
I have created a new blank project, added these data in question to the new project, created a new print composer, and confirmed that the data draw in this new project.  This leads me to believe this particular dataset in not the issue.
I have duplicated the print composer layout and this new layout has the same issue.
I have added other data for this area to the project and cannot view these data as well leading me to believe that there is some corruption in the print composer.
Please note that all data share the same CRS, and there were no alteration to any settings or elements in either the main display or the print composer.  This is happening on QGIS 2.18 with Ubuntu 16.04
What steps can I take to try to get my data to display in the print composer?


text:
Q: Angular 2 templates methods vs getters I'm wondering if there is any benefit to do this:

{{getSomething()}}

  export class MyComp {
    getSomething() { return ...}
  }

Over this:

{{getSomething}}

 export class MyComp {
   get getSomething() { return ...}
 }

Use methods vs getters to display calculated data.

A: I looked deeper into this and played with typescript Playground.
I declared two classes one with getter and the second with get method as described in your questions.
Lets see how it looks like:
In the first example we declared a method for getting the property value in the following way:
class Greeter {
  greeting: string;
  constructor(message: string) {
      this.greeting = message;
  }
   getGreeting() {
      return this.greeting;
  }
}

Which after translation to javascript it looks like:
var Greeter = (function () {
   function Greeter(message) {
       this.greeting = message;
   }
   Greeter.prototype.getGreeting = function () {
       return this.greeting;
   };
   return Greeter;
}());

And regarding the second example where we declared a getter in the following way:
class GetterGreeter {
   _greeting: string;
   constructor(message: string) {
       this._greeting = message;
   }
    get greeting() {
       return this._greeting;
   }
}

Which after translation looks like:
var GetterGreeter = (function () {
   function GetterGreeter(message) {
       this._greeting = message;
   }
   Object.defineProperty(GetterGreeter.prototype, "greeting", {
       get: function () {
           return this._greeting;
       },
       enumerable: true,
       configurable: true
   });
   return GetterGreeter;
}());

(You can play with the declaration and the translation to javascript here)
As you can see with get method (as in your first example) the method is declared on the prototype and in your second example using the getter pattern typescript uses the defineProperty api.
In both cases we are invoking a method and angular will also call a method during its change detection to identify changes and re-render.
As I see it this is only a syntactic sugar for the same approach and I don't see any performance benefit for one of the methods.

A: If you are a getter or a method doesn't matter from a technical point of view.
Some use the convention that a getter should behave similar to a field, and not do expensive computation, while a method should be used if the computation is more than some very basic things like for example building a full name from first- middle- and last name.
I think this is good practice to follow that distinction for Angular, because for view binding expensive calculation should be avoided because the method or getter can be called very often.
In such a case it's better to store the result in a field and bind to the field instead.
Very important in view binding is, that the method or getter doesn't return different values on subsequent calls when no dependencies were modified (like return {};, which would be treated as new object instance and cause an error like ExpressionChangedAfterItHasBeenCheckedError).

A: by get / set syntax the method behaves like a field, see below examples:
Using by regular getter method
usingGetterMethod()
{
  let id = this.getId();
}

getId()
{
  return this.reactiveForm.get('id');
}

Using by get method
usingGetMethod()
{
  let id = this.id;
}

get id()
{
  return this.reactiveForm.get('id');
}

A: The difference is in the first case you use a function in expression, but in the second case you use a peoperty. So you can use

{{something}}

export class MyComp {
  get something() { return ...}
}

The benefits of using second method is to use encapsulation of the property inside the class and you need to access it outside the class.
Getters and setters are part of ES5 spec. You can read about getter and setter.


text:
Q: Bad encoding of streamed CSV with Stripes / Tomcat Actually i'm trying to stream a CSV file. I set the encoding to windows-1252 but it seems it is still streamed as UTF-8 file.
   final String encoding = "windows-1252";
   exportResolution = new StreamingResolution(builder.getContentType() + ";charset=" + encoding.toLowerCase()) {
        @Override
        public void stream(HttpServletResponse response) throws Exception {
            // Set response headers
            response.setHeader("Cache-control", "private, max-age=0");
            response.setCharacterEncoding(encoding);
            OutputStream os = response.getOutputStream();
            writeExportStream(os,builder);
        }
    }.setFilename(filename);

writeExportStream just streams the content to the outputstream (with pagination and db calls, it takes some time)
It doesn't work in local (jetty plugin) + dev (tomcat) Neither with firefox / chrome
I've not tested but people at work told me that it works better when we don't stream the content but we write the file in one time after having loaded all the objets we want from db.
Anybody know what is happening? Thanks
Btw my headers:
HTTP/1.1 200 OK
Content-Language: fr-FR
Content-Type: text/csv;charset=windows-1252
Content-Disposition: attachment;filename="export_rshop_01-02-11.csv"
Cache-Control: private, max-age=0
Transfer-Encoding: chunked
Server: Jetty(6.1.14)

I want the file to be able to be imported in excel in windows-1252 but i can't, it just open in utf8 while my header is windows-1252

A: The problem lies in the writeExportStream(os,builder); method. We can't see what encoding operations it is performing, but I'm guessing it is writing UTF-8 data.

The output operation needs to perform two encoding tasks:

*

*Tell the client what encoding the response text is in (via the headers)

*Encode the data writen to the client in a matching encoding (e.g. via a writer)

Step 1 is being done correctly. Step 2 is probably the source of the error.
If you use the provided writer, it will encode character data in the appropriate response encoding.
If pre-encoded data is written via the raw byte stream (getOutputStream()), you need to make sure this process uses the same encoding.


text:
Q: Why does a single number fail to match a Range object in an array? > my @numbers = 1, 3, 5;
> 1 ~~ /@numbers/; #
「1」

is the same as:
> 1 ~~ /1 | 3 | 5/
「1」

but when the element is a Range object, it fails to match:
> my @ranges = 1..3.item, 4..6.item;
[1..3 4..6]

> 1 ~~ /@ranges/
Nil
> 1 ~~ /|@ranges/
Nil
> 1 ~~ /||@ranges/

A: When the regex engine sees /@numbers/ it treats that like an alternation of the array elements, so your first two examples are equivalent.
There just is no such automatism for Ranges I believe.
Edit: Never mind below, I totally misread the question at first.
> my @ranges = 1..3, 4..6;
[1..3 4..6]
> 1 ~~ @ranges[0];
True
> 2 ~~ @ranges[1];
False
> 4 ~~ @ranges[1];
True
> @ranges.first( 5 ~~ * )
4..6

See? @ranges is a array of, well, ranges (your call to item does nothing here). Theoretically this would hold true if the smartmatch operator were smarter.
> 1..3 ~~ @ranges;
False

Flattening also doesn't help, because a flat list of ranges is still a list of ranges.
Flattening the ranges themselves is possible, but that simply turns them into Arrays
> my @ranges2 = |(1..3), |(4..6)
[1 2 3 4 5 6]

A:
Why does single number fails to match Range object in array?

Per the doc:

The interpolation rules for individual elements [of an array] are the same as for scalars

And per the same doc section the rule for a scalar (that is not a regex) is:

interpolate the stringified value

A range object such as 1..3 stringifies to 1 2 3:
my $range = 1..3;
put $range;                   # 1 2 3
put so '1'     ~~ / $range /; # False
put so '1 2 3' ~~ / $range /; # True

So, as Holli suggests, perhaps instead:
my @ranges = flat 1..3, 4..6;
say @ranges;        # [1 2 3 4 5 6]
say 1 ~~ /@ranges/; # 「1」

Or is there some reason you don't want that? (See also Scimon's comment on Holli's answer.)


text:
Q: Update database with new data (products, categories etc) We have a live magento site with version 1.7.
In a dev installation (magento 1.9) , we had put a snap of live site database.
In dev site, we have changed theme, we have added some extension and we have done some other changes.
While we worked at dev site, in live site we have added products, we have had sales, more customers added etc.
How we can update dev database (with new products, new customers, new sales from live site database) without losing other changes we have made in dev site?

A: You can do the following:
Dump your CMS and Static Block data along with your config to a sql file.
You can then re-run the upgrade from your current live (1.7 to 1.9 upgrade)
You can then re-import your new data from your dev site back to you dev site.
The procedure will be something like this:
mysqldump -uuser -p'password' livedatabase cms_page cms_page_store cms_block cms_block_store core_config_data > temp-data-backup.sql

Then backup and restore your current live site to your dev site (All your customers and orders will be on your dev)
Now you can restore the data from cms and config by doing the following
mysql -uuser -p'password' devdatabase < temp-data-backup.sql

Before you start the above make a backup of your current dev database in case you have to go back.
You will have all your customers, orders, product and categories from live along with all your changed config data, cms and static block from dev.


text:
Q: Unable to send custom payload via DialogFlow Fulfilment npm for Slack I am unable to send a custom payload back to dialogflow from my nodejs webhook code for SLACK platform.
const {WebhookClient, Payload, Platforms, Suggestion} = require('dialogflow-fulfillment');

let payloadObj = new Payload(Platforms.SLACK, questionStringToSend);
agent.add(payloadObj);

Here, questionStringToSend is the JSON payload that i want to send.
Any help would be appreciated.
Structure of my JSON is below:
{
   "blocks":[
      {
         "type":"section",
         "text":{
            "type":"mrkdwn",
            "text":"How do you rate the company?"
         }
      },
      {
         "type":"actions",
         "elements":[
            {
               "type":"button",
               "text":{
                  "type":"plain_text",
                  "text":0
               },
               "value":0
            },
            {
               "type":"button",
               "text":{
                  "type":"plain_text",
                  "text":1
               },
               "value":1
            }
         ]
      }
   ]
}

A: While sending a response from webhook the format of json is very important Link.
Custom payload response is a json file which has a specific structure and if the structure isn't followed we won't get the expected response.
So the json file can be edited as follows:
{
"fulfillmentMessages": [

    {
        "payload": {
            "slack": {
                "attachments": [
                {"blocks":[
  {
     "type":"section",
     "text":{
        "type":"mrkdwn",
        "text":"How do you rate the company?"
     }
  },
    {
     "type":"actions",
     "elements":[
        {
           "type":"button",
           "text":{
              "type":"plain_text",
              "text":"0"
           },
           "value":"0",
           "action_id": "button"
        },
        {
           "type":"button",
           "text":{
              "type":"plain_text",
              "text":"1"
           },
           "value":"1"
        }
         ]
        }
       ]
      }
     ]
    }
   }
  }
]
}

A: try this
{
    "blocks": [
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "How do you rate the company?"
            }
        },
        {
            "type": "actions",
            "elements": [
                {
                    "type": "button",
                    "text": {
                        "type": "plain_text",
                        "text": "0"
                    },
                    "value": "0"
                },
                {
                    "type": "button",
                    "text": {
                        "type": "plain_text",
                        "text": "1"
                    },
                    "value": "1"
                }
            ]
        }
    ]
}


text:
Q: Can I receive messages in my iPhone as iMessage if it's turned off or out of battery? In case my iPhone is turned off/out of battery, will I be receiving messages as iMessage or text message?

A: This may be helpful:  from PC Pro blog: How iMessage works:

If you send a message to a fellow iMessage user who has their data
  switched off, the phone attempts to send it via the data channel at
  first, but if it can't get through after five minutes or so, the
  message turns green and is sent via the traditional SMS channel
  instead. [emphasis mine]

See the article for more details.
This next might also be relevant if you have another iOS device you'd like to receive at instead, when your phone is off: gigaom - iOS 5: iMessage:

To ensure your Message is received on all your connected devices, you
  must have them sent to your Apple ID email address. In limited
  testing, if someone sent me a test message to just my phone number, I
  only got the text on my iPhone. However, if they sent the message to
  my me.com address (which is my Apple ID address), I got it on all
  devices. This is because Apple can't associate your phone number
  (assigned by your carrier) with devices other than your iPhone.

A: Yes you will receive them. They will wait in Apple's servers. Though, it won't say "Delivered" on the sender's phone I think...


text:
Q: How to strip HTML attributes except "src" and "alt" in JAVA How do I strip all attributes from HTML tags in a string, except "alt" and "src" using Java?
And further.. how do I get the content from all "src" attributes in the string?
:)

A: You can:

*

*Implement a SAX parser;

*Built a document with a DOM parser, walk it and prune it and then convert back to HTML; or

*Use an identity transform in XSLT (assuming your HTML is in XHTML format or can be converted to that with, say, JTidy) with some additional cases to remove attributes you don't want.

Whatever you do, don't try and do it with regular expressions.

A: OK, solved this somehow.
Used the HTMLCleaner library to parse the input data to a valid format.
Then I use a DOM parser to iterate over everything, and strip all disallowed tags and attributes.
(and some minor ugly hacks;) )
This was kind of a lot of work.


text:
Q: What permanent magnet motor is the best for the bike generator? How to decide about wattage? I am new here.. I would like to build my bicycle generator with permanent magnet motor similar to this one Bicycle Power Basics
Basically, I want to run my pedal cinema with a bike generator. I am not sure about the load I will need but I will try to reduce it as much as I can because I am aware that I will not be able to produce more than 100W anyway..
I made some research about permanent magnet motors and I found some here
http://www.fireworksandscootersdirect.co.uk/category.php?CID=52 They mainly differ in watts.
My question:
- is the wattage of the PM motor important in making the decision about single bike generator? If I buy a motor with 24V 350W RPM2750 will I be able to run appliances which consume more power rather then I would purchase a motor 24V 250W RPM2750? Does it mean that the motor with higher wattage will be more effective in running appliances which consume more power?
As I understand, the adult person is able to run the bicycle with more or less RPM 60, so it means that in an hour I will be able to do RPM 360, which is 7 times smaller then RPM2750. So if I use a motor with 350W, will it give me 50W and if I use a motor with 250W it gives me only 35W? Is this correct or I am completely wrong?
How can I choose a permanent magnet motor?

A:
I am aware that I will not be able to produce more than 100W anyway.

That's about right. Another useful number to remember is that a servant can give about 1 kWh per eight-hour shift!

If I buy a motor with 24V 350W RPM2750 will I be able to run appliances which consume more power rather then I would purchase a motor 24V 250W RPM2750?

There will be losses in any motor / generator and these will increase with size although they may be countered by improving efficiency. The 250 W unit will have lower inertia and will probably be cheaper.

Does it mean that the motor with higher wattage will be more effective in running appliances which consume more power?

Yes, but as you've stated, your power source (you) is limited in output.

As I understand, the adult person is able to run the bicycle with more or less RPM 60, so it means that in an hour I will be able to do RPM 360, ...

Umm, 60 RPM x 60 minutes = 3,600 revs/hour - but why are you converting to hours?

which is 7 times smaller then RPM2750.

Much worse than you imagine: \$ \frac {60~rpm}{2750~rpm} = 2\%\$ of rated speed giving you 2% of 24 V = 0.5 V out. This won't light an LED! The DC generator's output voltage will be proportional to rotational speed.

The article is too long for me to read but here are a few pointers:

*

*You need to figure out what voltage your system requires.

*You need to generate in excess of that voltage and regulate it. (It is also possible to generate a lower voltage and boost it with a boost regulator.)

*If you go for 24 V out then you need to gear-up the motor drive to give 2750 RPM at your preferred cadence.

*You need to figure out what you want to happen when you stop pedaling for a second or a minute. Do you want your cinema to reboot? If not you need some short-term storage.

I think a more practical project would be to power your cinema from a mains-powered battery and the bicycle generator. Monitor the generator output and if you fall below a certain threshold for a time then blank the video. If you maintain output for more than ten minutes then dispense a chocolate reward.

A: Quick answer is that you will be very much an admired athlete if you can sustain a 60W output from pedal power.  Maybe you read this already.
Begin experimenting with something nice an cheap to get an idea of the human problem of power output and generator + circuit inefficiency.
Buy lots of Gatorade and setup a fan to keep yourself cool on your stationary bike.  This sounds like a really fun experiment and I used to suggest it to boys in my scout troop all of the time.


text:
Q: Constexpr destructor I've just read this post.
Does constexpr work in the same manner for destructors? Namely, if the destructor is marked as constexpr, there must exist at least one set of template arguments for which the destructor will be a constant expression? For others the destructor will still compile with constexpr keyword even though it will not be a constant expression?


text:
Q: JW-Player use video thumbnail as featured image If I upload external media (in particular a Youtube video) for use with the jw-player wordpress plugin... how do i use the thumbnail as my featured image ... so i can show thumbs in say the excerpts that link to the post where the full video is available.
the jw-player plugin seems to save the youtube screenshot as meta data, but the meta data is
associated with the attachment page and not w/ the post i am adding to my blog.

A: If that is the case, you can use <?php wp_get_attachment_metadata( $post_id, $unfiltered ) ?>. You'll need to look through the returned array to find that image and display it.
http://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata


text:
Q: Where PWA store photos? I've the PWA app, launched on Android device. The app allow to take pictures and upload them to server.
I wonder, where PWA app store this photos? In the browser cache or somewhere in android app directory?

A: PWA app can only store the pages/files in cache and it cannot access android directory. So, PWA can store images in cache if it is offline and sync the files to server then when it is offline.


text:
Q: WebDriver, всплывающая подсказка При вводе в поле e-mail чего-то вроде "абв" - появляется всплывающая подсказка, которая исчезает при клике по ней. Как можно ее отловить? В ресурсах страницы ничего подходящего не нашел.
Собственно, вот форма
https://app.heroicnow.com/login/
Как в selenium webdriver указать ее появление в asset?


text:
Q: Get localhost web page by IP Address I have a android project which feeds XML data from URL from web. I want to test this but I don't own a web address.
Therefore I created a XML Page on ASP.NET project and put the URL on android project. But the localhost URL didn't work.
How can I create a project in Visual Studio such that I can give the IP Address in the Android Project. I went through this tutorial about TCP Client but cannot resolve a solution for my problem. (I don't have an IIS Server so please don't give it as a solution)

A: If you are using real device via Wi-Fi network, your real host IP address should work. If you're using emulator, then your host address is 10.0.2.2 (see documentation here).

A: Localhost usually resolves to 127.0.0.1 and is reserved for the local machine only. I assume that your machine has a networks card of some description and as such will have an IP address.  This may be assigned automatically by your router (ADSL/Cable/Etc) but it will have one.  If you are not sure what it is (and assuming, since you are talking about VS you are developing with a PC) then open a command prompt and type
ipconfig /all

You will then get back a list of network devices and one of them will be your NIC. You should also see the IP address associated with it.
The final thing to do is ensure that your windows firewall is not blocking access to the port(s) used by your mobile app.  Should all be fine after that. If you have another PC then try browsing to the XML hosted page using that.


text:
Q: TypeError list.map is not a function Hi could someone tell me why I am getting the list.map is not a function error?
I don't know why it can't list.map

below is my code
singleProduct

import axiosLink from "../instance/axiosLink";

const SingleProduct = () => {
  const { id } = useParams();
  const [product, setProduct] = useState([]);
  useEffect(() => {
    axiosLink
      .get(`/api/products${id}`)
      .then(({ data }) => {
        setProduct(data);
      })
      .catch((error) => console.log(error));
  }, [id]);
  return (

      <SingleProductComponent list={product} />
      {/* <RelatedProducts list={product} /> */}
      <Review />

  );
};

export default SingleProduct;

SingleProductComponent
import React from "react";

const SingleProductComponent = ({ list }) => {
  return (

      {list &&
        list.map((item, index) => {
          return (

               .........

          );
        })}

  );
};

export default SingleProductComponent;

axiosLink
import axios from "axios";

const axiosLink = axios.create({
  baseURL: "http://localhost:8000/",
  responseType: "json",
});

export default axiosLink;

Can you tell me the reason why? I get this error very often and I don't know the fix yet
this is my api structure

A: you need to initialize your product state with an array like below
const [product, setProduct] = useState([])

A: Check in network (inspect element -> network) if your data is correctly coming to you. Console log your data as well and check if its array. Practically this error says that your "list" is not an array, and it cannot map through it.
Also you should use useEffect(()=>{},[]) so it should fetch your api only once, and initialise your useState for product as empty array [].


text:
Q: tcp_probe fields I am using ubuntu 14.04 LTS with the custom kernel provided here: https://github.com/multipath-tcp/mptcp
The kernel version is 4.4.70 enabled with multipath TCP. I ran tcp_probe to look at the window sizes during a 10 second iperf3 session with 2 subflows. The linux tcp testing documentation here: https://wiki.linuxfoundation.org/networking/tcp_testing does not really describe the fields clearly. Is there a better or a more recent documentation for tcp_probe.
I am interested in 2 things:

*

*To understand the difference between congestion window (field 7) and sender window (field 9) as mentioned in the above documentation. Isn't the sender window the same as the congestion window (unless the receiver advertises a size smaller than the congestion window)?

*In what units are the 7th and 9th fields logged? These fields correspond to the cwnd and sender window.


text:
Q: Query Transactional Replication Article Filters Through the UI, I can see that I have 2 tables with filters on them. I need to be able to query this information but cannot find the table that contains the data. I did a search for any column in the Distribution database with a name like either "Filter" or "Where". The results are below. Unfortunately, none of these tables has the data I'm looking for  in them.
 - SELECT * FROM IHarticles
 - SELECT * FROM IHextendedArticleView
 - SELECT * FROM MSarticles
 - SELECT * FROM MSmerge_articlehistory
 - SELECT * FROM MSmerge_articleresolver
 - SELECT * FROM sysarticlecolumns
 - SELECT * FROM sysarticles
 - SELECT * FROM sysextendedarticlesview
 - SELECT * FROM sysschemaarticles

Does anyone know where this data is held?

A: To research this, I configured transactional replication on my test server with 1 article having row filter. I did this for Adventureworks.Sales.Store table having [CustomerID] <10. Initially, I tried querying distribution..sysarticles to check the filter details. But, surprisingly it did not show any data in it.
Then I checked Adventureworks..sysarticles(i.e. in publication database) and that did the trick. See the below result:


text:
Q: Primefaces TabMenu in JSF page I'm working on JSF page which is using Primefaces TabMenu. I managed to find one possible solution of this post. This is the solution so far:
Main page:
<div id="settingsHashMapz" class="settingsHashMap" style="width:1150px; height:400px; position:absolute; top:20px; left:1px">

    <p:tabMenu id="tabs" activeIndex="0" >
        <p:menuitem value="General" url="/DCProfileTabGeneral.jsf" />
        <p:menuitem value="Zones" url="/DCProfileTabZones.jsf" />
        <p:menuitem value="UPS" url="/DCProfileTabUPS.jsf" />

    </p:tabMenu>

</div>

JSF page from tabs:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
    <h:head>

    </h:head>
    <h:body>
        <ui:composition>
            <h:panelGroup>
                <h:form id="zones" >
                    <!-- The sortable data table -->
                    .................

                    <!-- The paging buttons -->
                    <h:commandButton styleClass="bimage" value="first" action="#{DCProfileTabZonesController.pageFirst}"
                                     disabled="#{DCProfileTabZonesController.firstRow == 0}" >
                        <f:ajax render="@form" execute="@form"></f:ajax>
                    </h:commandButton>

                    ....................

                    <!-- Set rows per page -->
                    <h:selectOneMenu id="setrows" value="#{DCProfileTabZonesController.rowsPerPage}" converter="javax.faces.Integer" maxlength="2">
                        <f:selectItem itemValue="5" itemLabel="5" />
                        <f:selectItem itemValue="10" itemLabel="10" />
                        <f:selectItem itemValue="20" itemLabel="20" />
                        <f:selectItem itemValue="50" itemLabel="50" />
                        <f:selectItem itemValue="100" itemLabel="100" />
                        <f:selectItem itemValue="200" itemLabel="200" />
                        <f:ajax render="@form" event="change" execute="@form" listener="#{DCProfileTabZonesController.pageFirst}" />
                    </h:selectOneMenu>

                   ........................
                </h:form>
            </h:panelGroup>
        </ui:composition>
    </h:body>
</html>

I hope that I solve the forms problem. But I found these problems:
When I click on the h:commandButton to change the table page I'm redirected to page DCProfileTabZones.jsf. I'm not returned to page DatacenterProfile.jsf?id=1002#. Maybe this is because I use h:commandButton.
The second problem is from h:selectOneMenu. When I select different number I get this error message in Firebug:
ReferenceError: mojarra is not defined
function onchange(event) {
mojarra.ab(this, event, "valueChange", "@form", "@form");
}

Would you please give me some advice how I can solve the problems.


text:
Q: Failing in type checking I wanted to make a "leap year" programm as practice.
This is my code:
#include <iostream>
#include <string>

int main (){
int year;
std::string flag01;
do {
    std::cout << "Input year: ";
    std::cin >> year;
//check for int input
    while (std::cin.fail()){
        std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?";
        std::cin.clear();
        std::cin >> year;
    }
    if (year % 4 == 0 && year % 100 != 0 && year != 0)
        std::cout << "the year " << year << " is a leap year.\n";
    else
        std::cout << "the year " << year << " is not a leap year.\n";
    std::cout << "Would you like to input another?  yes / no \n";
    do {
        std::cin >> flag01;
            if (flag01 != "yes" && flag01 != "no")
                std::cout << "please only insert yes or no\n";
    } while (flag01 != "no" && flag01 != "yes");
} while (flag01 != "no");
return 0;
}

But I can't make the part where it checks if what you input is an int or not, work. I don't know what I am doing wrong.
When I run it and input a char or string it goes in an infinite loop and keeps printing the line 11.
I saw the std::cin.fail and std::cin.clear here: Checking input value is an integer
Please help and thanks.

A: You are clearing the error state, but the data that caused the error is still in the stream. Clear it with ignore...
    std::cout << "Oops..." << std::endl << "I failed to get a year..." << std::endl << "Try again?";
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //extract all characters until /n
    std::cin >> year;

Include header limits for std::numeric_limits.
#include <limits>