问:
RxJava 2, Flowable.doOnCancel not called when DisposableSubscriber disposed
I have a DisposableSubscriber to a Flowable. The Flowable runs for some timeUntilTimeout, but in some situations I need to kill it earlier. Right now I call .dispose() on the DisposableSubscriber but the Flowable continues to emit events. Eventually the Flowable times out and .doOnCancel() is called.

I have the following code:

```<code>private Disposable mDisposableSubscription = null;

public void start() {
    mDisposableSubscription = getFlowable()
            .timeout(timeUntilTimeout, TimeUnit.MILLISECONDS)
            .subscribeWith(new DisposableSubscriber<T>() {
                @Override
                public void onComplete() {

                }
                @Override
                public void onError(Throwable throwable) {
                    dispose();
                }
                @Override
                public void onNext(T t) {
                    // Do something
                }
            });
}

public void stop() {
    // Log "dispose"
    mDisposableSubscription.dispose();
}

private Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        public void subscribe(FlowableEmitter<T> emitter) {
            startSomeAsyncProcess();
        }
    }).doOnCancel(new Action() {
        public void run() {
            // Log "do on cancel"
            stopSomeAsyncProcess();
        }
    });
}
</code>```

Calling stop() to dispose of the DisposableSubscriber before the Flowable times out means events emitted by the Flowable are no longer handled, but the Flowable continues emitting events and the async process continues running. I was under the impression that calling .dispose() downstream of the Flowable kills the Flowable by calling .doOnCancel(), but this does not appear to be the case. What am I missing?

答:
The flowable is getting disposed, but you are not checking it on your Flowable.create function, so what happens is that the startSomeAsyncProcess() ignores it and keeps going.

To solve the issue, you should check the emitter.isDisposed() flag to know if you should stop emitting.

Example:

```<code>Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {

        public void subscribe(FlowableEmitter<T> emitter) {
            while(!emitter.isDisposed()) {
                emitter.onNext(...);
            }
        }

    });
}
</code>```

If that startSomeAsyncProcess() function doesn't allow you to check the flag, surely there is some way to cancel it. Then you can attach a cancellable:

```<code>Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {

        public void subscribe(FlowableEmitter<T> emitter) {
            startSomeAsyncProcess();
            emitter.setCancellable(() -> stopSomeAsyncProcess());
            // I don't remember if it's setCancellable() or setDisposable()
        }

    });
}
</code>```

Update: the methods setCancellable(...) and setDisposable(...) should behave equally, they just take different arguments.

Body:
I have a DisposableSubscriber to a Flowable. The Flowable runs for some timeUntilTimeout, but in some situations I need to kill it earlier. Right now I call .dispose() on the DisposableSubscriber but the Flowable continues to emit events. Eventually the Flowable times out and .doOnCancel() is called.

I have the following code:

private Disposable mDisposableSubscription = null;

public void start() {
    mDisposableSubscription = getFlowable()
            .timeout(timeUntilTimeout, TimeUnit.MILLISECONDS)
            .subscribeWith(new DisposableSubscriber<T>() {
                @Override
                public void onComplete() {

                }
                @Override
                public void onError(Throwable throwable) {
                    dispose();
                }
                @Override
                public void onNext(T t) {
                    // Do something
                }
            });
}

public void stop() {
    // Log "dispose"
    mDisposableSubscription.dispose();
}

private Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        public void subscribe(FlowableEmitter<T> emitter) {
            startSomeAsyncProcess();
        }
    }).doOnCancel(new Action() {
        public void run() {
            // Log "do on cancel"
            stopSomeAsyncProcess();
        }
    });
}

Calling stop() to dispose of the DisposableSubscriber before the Flowable times out means events emitted by the Flowable are no longer handled, but the Flowable continues emitting events and the async process continues running. I was under the impression that calling .dispose() downstream of the Flowable kills the Flowable by calling .doOnCancel(), but this does not appear to be the case. What am I missing?

Body:
The flowable is getting disposed, but you are not checking it on your Flowable.create function, so what happens is that the startSomeAsyncProcess() ignores it and keeps going.

To solve the issue, you should check the emitter.isDisposed() flag to know if you should stop emitting.

Example:

Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {

        public void subscribe(FlowableEmitter<T> emitter) {
            while(!emitter.isDisposed()) {
                emitter.onNext(...);
            }
        }

    });
}

If that startSomeAsyncProcess() function doesn't allow you to check the flag, surely there is some way to cancel it. Then you can attach a cancellable:

Flowable<T> getFlowable() {
    return Flowable.create(new FlowableOnSubscribe<T>() {

        public void subscribe(FlowableEmitter<T> emitter) {
            startSomeAsyncProcess();
            emitter.setCancellable(() -> stopSomeAsyncProcess());
            // I don't remember if it's setCancellable() or setDisposable()
        }

    });
}

Update: the methods setCancellable(...) and setDisposable(...) should behave equally, they just take different arguments.


来源: stackexchange

问:
HOW to change preview?
I have been editing the stupid android studio layout for the last 3 hours, and I cant change the preview!

For some reason, android studio layout is stuck on wear square! I just want my layout to be a Nexus 6p, but when I click on that, instead of changing the layout editor phone, it just jumps to my layout-normal xml!

How can I change the phone shown on the layout editor? It is causing me way too much trouble

答:
Resize your layout by dragging the bottom-right corner of your layout to the far bottom right of your screen.
The "Device in Editor" drop-down will change to "Custom".
You should now be able to select any listed device.</p>

ContentLicense: CC BY-SA 3.0

Title: HOW to change preview?


问:
React ES5's alternative way of doing ES6's setstate callback?
I am trying to force react to perform setstate synchronously by passing a callback function to setstate

I have done my research on SO and found out that we can do something like

```<code>this.setstate({state:value}, () => {function()})
</code>```

However, since ES5 does not have the arrow function, how should I pass a callback in setstate?

I have tried  this.setstate({state:value}, function()) but it did not do what I wanted it to do.

Additionally, is there any more ideal way of forcing react to perform setstate synchronously?

答:
You can't force setState to be synchronous because React will sometimes batch multiple updates together to prevent too many updates happening at once.

If you pass a callback as the second argument, then React will call it after the component's state has been updated.

```<code>this.setState({ key: value }, function() {
  // this.state is updated
});

// this.state might not be updated
</code>```

The other option is to instead use componentDidUpdate to wait for any setState changes, which is a better solution if you always want to update after any state changes.

Just generally, React can't tell whether you passed an arrow function or a regular function as a parameter, so the behaviour won't change based on whether you're using ES6 or ES5 syntax.

Body:
I am trying to force react to perform setstate synchronously by passing a callback function to setstate

I have done my research on SO and found out that we can do something like

this.setstate({state:value}, () => {function()})

However, since ES5 does not have the arrow function, how should I pass a callback in setstate?

I have tried  this.setstate({state:value}, function()) but it did not do what I wanted it to do.

Additionally, is there any more ideal way of forcing react to perform setstate synchronously?

Body:
You can't force setState to be synchronous because React will sometimes batch multiple updates together to prevent too many updates happening at once.

If you pass a callback as the second argument, then React will call it after the component's state has been updated.

this.setState({ key: value }, function() {
  // this.state is updated
});

// this.state might not be updated

The other option is to instead use componentDidUpdate to wait for any setState changes, which is a better solution if you always want to update after any state changes.

Just generally, React can't tell whether you passed an arrow function or a regular function as a parameter, so the behaviour won't change based on whether you're using ES6 or ES5 syntax.


问:
Can't declare a 2D dynamic array in a struct
So I have 2 questions.

I'm trying to learn how to dynamically allocate memory for 2D arrays.
Here is a working code, I first want to know if it's fine, it works but I really don't know if I have memory leaks or some errors I don't see.

```<code>typedef struct Map Map;

struct Map
{
    int width, height;
    int** cases; // Not technically a 2D array but I use it like it in my code
};

int getMapValue(Map map, int x, int y);
void setMapValue(Map* map, int value, int x, int y);

void mallocMap(Map* map, int width, int height);
void freeMap(Map* map);

int main()
{
    int l,h,i,j;
    Map map;

    printf("Width : ");
    scanf("%d", &l);
    printf("Height : ");
    scanf("%d", &h);

    map.width = l;
    map.height = h;

    mallocMap(&map, l, h); // allocate memory for the map

    for(j = 0; j < map.height; j++)
        for(i = 0; i < map.width; i++)
            setMapValue(&map, i*j, i, j); // set some values

    for(j = 0; j < map.height; j++)
        for(i = 0; i < map.width; i++)
            printf("%d ", getMapValue(map, j, i)); // read some values, works fine

    freeMap(&map); // free memory

    return 0;
}

void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    if (map->cases == NULL)
    {
        printf("Error\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.height + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->height + x) = value;
}
</code>```

Then I have a problem.
I want to add a struct Player which has two Map elements in it like so :

```<code>struct Player
{
    Map map[2];
};
</code>```

But this results in an error array has incomplete element type. Apparently it's because of the size of the array that isn't set correctly, how should I make this work ?

Update : I needed to write the Map structure before the Player structure.

答:
The problem with the "incomplete type" is very likely because you define struct Player before having defined struct Map.

Concerning your "2D"-Array: With map->cases = malloc(sizeof(int) * width * height);, you actually reserve memory in a layout similar to a "real" 2D-array, whereas datatype int **cases denotes a pointer to pointer to an int.
So if you switch to int *cases, it should work.

Note that cases still is not a "real" 2D-Array, since you are not allowed to access it like map->cases[3][4] (this would yield undefined behaviour). But you calculate the offsets on your own in the getter and setter functions anyway, so your implementation should work.

Body:
So I have 2 questions.

I'm trying to learn how to dynamically allocate memory for 2D arrays.
Here is a working code, I first want to know if it's fine, it works but I really don't know if I have memory leaks or some errors I don't see.

typedef struct Map Map;

struct Map
{
    int width, height;
    int** cases; // Not technically a 2D array but I use it like it in my code
};

int getMapValue(Map map, int x, int y);
void setMapValue(Map* map, int value, int x, int y);

void mallocMap(Map* map, int width, int height);
void freeMap(Map* map);

int main()
{
    int l,h,i,j;
    Map map;

    printf("Width : ");
    scanf("%d", &l);
    printf("Height : ");
    scanf("%d", &h);

    map.width = l;
    map.height = h;

    mallocMap(&map, l, h); // allocate memory for the map

    for(j = 0; j < map.height; j++)
        for(i = 0; i < map.width; i++)
            setMapValue(&map, i*j, i, j); // set some values

    for(j = 0; j < map.height; j++)
        for(i = 0; i < map.width; i++)
            printf("%d ", getMapValue(map, j, i)); // read some values, works fine

    freeMap(&map); // free memory

    return 0;
}

void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    if (map->cases == NULL)
    {
        printf("Error\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.height + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->height + x) = value;
}

Then I have a problem.
I want to add a struct Player which has two Map elements in it like so :

struct Player
{
    Map map[2];
};

But this results in an error array has incomplete element type. Apparently it's because of the size of the array that isn't set correctly, how should I make this work ?

Update : I needed to write the Map structure before the Player structure.


问:
Getting data from online MySQL DB in "onCreate" method of Activity
I am working on application that needs to get data from online MySQL database and show it as list in activity layout.

Problem is that my application gets error " Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"

In onCreate method I am calling asyncTask class to get the data from server and than below that line of code I set that data through adapter to listview which is my layout.
When starting that activity, I get the error.

Should I get the data from server before starting Activity? Or the problem is something else?
My php file is working okay when I check it in browser.

Here is onCreate Method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    final ListView listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();

    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}
</code>```

EDIT:

I fixed it as You all suggested, now there is no error, activity opens, but it still doesn't show any data from online database..
Here is edited onCreate() method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1);
    listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();
    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    adapter.notifyDataSetChanged();
}
</code>```

and here is AsyncTask class:

```<code>public class InvoiceDownloader extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        try {
            response += getHttpContent(params[0]);
        } catch (IOException e) {
            Log.e("error", e.toString());
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        adapter.addAll(invoices);
        listView1.setAdapter(adapter);

        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public String getHttpContent(String urlStr) throws IOException {

        String response = "";

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String json;
            while ((json = bufferedReader.readLine()) != null) {
                sb.append(json + "\n");
            }

            JSONArray jsonArray = new JSONArray(sb.toString().trim());

            for (int i = 0; i < jsonArray.length(); i++) {
                Invoice invoice = new Invoice();
                JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

                System.out.println("Company Name 1: " + companyNameOne + " Company Name 2: " + companyNameTwo + " address: " + address + " postalCode: " + postalCode + " city: " + city + " oib: " + oib + " email: " + email + " completed: " + completed + " work order num: " + workOrderNumber + " price: " + price);

                invoice.setCompanyNameOne(companyNameOne);
                invoice.setCompanyNameTwo(companyNameTwo);
                invoice.setAddress(address);
                invoice.setPostalCode(postalCode);
                invoice.setCity(city);
                invoice.setOib(oib);
                invoice.setEmail(email);
                invoice.setCompleted(completed);
                invoice.setWorkOrderNumber(workOrderNumber);
                invoice.setPrice(price);

                invoices.add(invoice);
            }
            return response;
        } catch (Exception e) {
            return null;
        }
    }
}
</code>```

2nd EDIT:

I got it. Sorry, this issue not showing data after fixing error was my mistake. In this part:

```<code>JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");
</code>```

those strings in (" ") ALL had to be small letters, because I wrote them that way in my PHP.

Thank You all for Your help.

答:
Possibly you are not getting a reply from the server, and this is the reason why the list is null, edit posting the stacktrace and will able to help you better, have a look at this post it looks the same problem you had and the reason is in the call to the web service(SQL db)
My guess is that the second line of your stacktrace says ArrayAdapter.getCount()
because is usually here the problem, the method called by ArrayAdapter that returns a List, that in your case is null because does not retrieve from the Server. maybe a JsonException, so you should add an exception with a try catch to manage what happens if the server does not retrieve the response.

```<code> public int   getCount() {

    return mObjects.size();

}
</code>```

Async task is less used than 3 years ago, almost all the community uses now Retrofit to make asyncrous calls and also RXJava

Body:
I am working on application that needs to get data from online MySQL database and show it as list in activity layout.

Problem is that my application gets error " Attempt to invoke interface method 'int java.util.List.size()' on a null object reference"

In onCreate method I am calling asyncTask class to get the data from server and than below that line of code I set that data through adapter to listview which is my layout.
When starting that activity, I get the error.

Should I get the data from server before starting Activity? Or the problem is something else?
My php file is working okay when I check it in browser.

Here is onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    final ListView listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();

    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    ArrayAdapter<Invoice> adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1, invoices);
    listView1.setAdapter(adapter);
}

EDIT:

I fixed it as You all suggested, now there is no error, activity opens, but it still doesn't show any data from online database..
Here is edited onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoice_list);
    adapter = new ArrayAdapter<Invoice>(this, android.R.layout.simple_list_item_1);
    listView1 = (ListView) findViewById(R.id.invoicelist);
    InvoiceDownloader task = new InvoiceDownloader();
    task.execute(new String[] { "http://10.0.2.2/company/getinvoices.php" });
    adapter.notifyDataSetChanged();
}

and here is AsyncTask class:

public class InvoiceDownloader extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        String response = "";
        try {
            response += getHttpContent(params[0]);
        } catch (IOException e) {
            Log.e("error", e.toString());
        }
        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        adapter.addAll(invoices);
        listView1.setAdapter(adapter);

        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public String getHttpContent(String urlStr) throws IOException {

        String response = "";

        try {
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String json;
            while ((json = bufferedReader.readLine()) != null) {
                sb.append(json + "\n");
            }

            JSONArray jsonArray = new JSONArray(sb.toString().trim());

            for (int i = 0; i < jsonArray.length(); i++) {
                Invoice invoice = new Invoice();
                JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

                System.out.println("Company Name 1: " + companyNameOne + " Company Name 2: " + companyNameTwo + " address: " + address + " postalCode: " + postalCode + " city: " + city + " oib: " + oib + " email: " + email + " completed: " + completed + " work order num: " + workOrderNumber + " price: " + price);

                invoice.setCompanyNameOne(companyNameOne);
                invoice.setCompanyNameTwo(companyNameTwo);
                invoice.setAddress(address);
                invoice.setPostalCode(postalCode);
                invoice.setCity(city);
                invoice.setOib(oib);
                invoice.setEmail(email);
                invoice.setCompleted(completed);
                invoice.setWorkOrderNumber(workOrderNumber);
                invoice.setPrice(price);

                invoices.add(invoice);
            }
            return response;
        } catch (Exception e) {
            return null;
        }
    }
}

2nd EDIT:

I got it. Sorry, this issue not showing data after fixing error was my mistake. In this part:

JSONObject inv = jsonArray.getJSONObject(i);

                String companyNameOne = inv.getString("companyNameOne");
                String companyNameTwo = inv.getString("companyNameTwo");
                String address = inv.getString("address");
                String postalCode = inv.getString("postalCode");
                String city = inv.getString("city");
                String oib = inv.getString("oib");
                String email = inv.getString("email");
                int comple = inv.getInt("completed");
                String completed = String.valueOf(comple);
                String workOrderNumber = inv.getString("workOrderNumber");
                String price = inv.getString("price");

those strings in (" ") ALL had to be small letters, because I wrote them that way in my PHP.

Thank You all for Your help.

Body:
Possibly you are not getting a reply from the server, and this is the reason why the list is null, edit posting the stacktrace and will able to help you better, have a look at this post it looks the same problem you had and the reason is in the call to the web service(SQL db)
My guess is that the second line of your stacktrace says ArrayAdapter.getCount()
because is usually here the problem, the method called by ArrayAdapter that returns a List, that in your case is null because does not retrieve from the Server. maybe a JsonException, so you should add an exception with a try catch to manage what happens if the server does not retrieve the response.

 public int   getCount() {

    return mObjects.size();

}

Async task is less used than 3 years ago, almost all the community uses now Retrofit to make asyncrous calls and also RXJava


答:
you should set the data through adapter to listview on the onPostExecute() of the asyncTask. (https://developer.android.com/reference/android/os/AsyncTask.html)

Since the task is asynchronous, you are trying to access to the data of the invoices list, before the response from the server has arrived.

Title: Getting data from online MySQL DB in "onCreate" method of Activity


问:
Removing unnecessary labels in the tooptip in R and ggplot2 chart
Upon running the R and ggplot2 script below, the following snapshot is generated. Upon hovering on any box, we get the following tooltip as shown in the plot. My simple requirement is to get rid of the fourth tooltip attribute as it is similar to the third . I guess something needs to be done in the aes() of ggplot command below.Also if the text can be made more clear without increasing the size of the plot or font, please help and thanks.

```<code>library(bupaR)
library(ggplot2)
library(scales)
library(plotly)
library(splitstackshape)
tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr$Actuals = percent(tr$absolute_frequency/sum(te$absolute_frequency))
tr.df <- cSplit(tr, "trace", ",")
pos <- c(1,4:ncol(tr.df))
tr.df <- tr.df[,..pos]
tr.df <- melt(tr.df, id.vars = "trace_id")
mp1 = ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value,
label = value)) + geom_tile(colour = "white") +
geom_text(colour = "white",  size = 1.9) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none") + labs(x = "Traces", y = "Activities")
ggplotly(mp1, height = 500, width = 645)
</code>```

答:
```<code>library(bupaR)
library(ggplot2)
library(scales)
library(plotly)
library(splitstackshape)
tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr$Actuals = percent(tr$absolute_frequency/sum(tr$absolute_frequency))
tr.df <- cSplit(tr, "trace", ",")
pos <- c(1,4:ncol(tr.df))
tr.df <- tr.df[,..pos]
tr.df <- melt(tr.df, id.vars = c("trace_id","Actuals"))

mp1 = ggplot(data = tr.df, aes(x = variable, y = trace_id, fill = value, label = value,
text=paste("Variable:",variable,"<br>Trace ID:",trace_id,"<br>Value:",value,"<br>Actuals:",Actuals))) +
geom_tile(colour = "white") +
geom_text(colour = "white",  size = 4) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none") + labs(x = "Traces", y = "Activities")

gg <- ggplotly(mp1, tooltip="text")
layout(gg, margin=list(l=50, b=50))
</code>```

Body:
Upon running the R and ggplot2 script below, the following snapshot is generated. Upon hovering on any box, we get the following tooltip as shown in the plot. My simple requirement is to get rid of the fourth tooltip attribute as it is similar to the third . I guess something needs to be done in the aes() of ggplot command below.Also if the text can be made more clear without increasing the size of the plot or font, please help and thanks.

library(bupaR)
library(ggplot2)
library(scales)
library(plotly)
library(splitstackshape)
tr <- data.frame(traces(patients, output_traces = T, output_cases = F))
tr$Actuals = percent(tr$absolute_frequency/sum(te$absolute_frequency))
tr.df <- cSplit(tr, "trace", ",")
pos <- c(1,4:ncol(tr.df))
tr.df <- tr.df[,..pos]
tr.df <- melt(tr.df, id.vars = "trace_id")
mp1 = ggplot(data = tr.df, aes(x = variable,y = trace_id, fill = value,
label = value)) + geom_tile(colour = "white") +
geom_text(colour = "white",  size = 1.9) +
scale_fill_discrete(na.value="transparent") +
theme(legend.position="none") + labs(x = "Traces", y = "Activities")
ggplotly(mp1, height = 500, width = 645)


问:
reverse() not working on map() Component state ( Firebase )
1. reverse() not working properly on Child Component

I have this state on a Component

```<code>this.state = {
    score_board_data:[]
}
</code>```

and the following componentDidMount lifecycle

```<code>componentDidMount(){

    const tempArray = this.state.score_board_data

    this.dataBase.orderByChild("player_score").on('child_added', snap =>{
        tempArray.push({
            player_score: snap.val().player_score,
            player_name: snap.val().player_name
        });
        this.setState({score_board_data:tempArray});
     });
}
</code>```

When I use the map() function on the state

```<code>this.state.score_board_data.map((player,i)=>{
    return(
        <tr key={i}>
              <td>{player.player_name}</td>
              <td>{player.player_score}</td>
        </tr>
    )
});
</code>```

I get sorting based on this:

```<code>.orderByChild("player_score")
</code>```

which for looks like this (
125,
150,
150,
150,
150,
150,
175,
225,
300,
325
)

Now I want to reverse it, so I use the reverse() method on the map() function like this

```<code>this.state.score_board_data.reverse().map( ....
</code>```

i get this
   ( 325,
225,
150,
150,
150,
125,
150,
150,
175,
300 )
..... which is not reversed at all :D

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

2. componentWillUnmount dilemma.

I have a parent Component, which uses Google Firebase

```<code>//child
this.app = firebase.initializeApp(DB_CONFIG);
this.database = this.app.database().ref().child("numbers");
</code>```

I pass the database ref to the child component as a prop

```<code>//child props from parent
dataBase={this.database}
</code>```

I use react router to navigate from parent to child and back ...

but when I add an element to the database in the parent component and use the router to get to the child component which uses the same database reference as the parent I  get this error ...

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

I think I need to add some code in the child componentWillUnmount() to  remove the database from it .... sadly I  don't know how

```<code>//child
componentWillUnmount(){
}
</code>```

I looked up on Google and here but couldn't figure it out

答:
Array#reverse() does reverse the Array in place, like Array#sort().

So you don't just reverse the output you've created by map(), but instead you reverse the input this.state.score_board_data. Then you push() the 300 to the (reversed) Array.

Solution: change the order in wich you call the functions

```<code>this.state.score_board_data.map(...).reverse()
</code>```

Body:
1. reverse() not working properly on Child Component

I have this state on a Component

this.state = {
    score_board_data:[]
}

and the following componentDidMount lifecycle

componentDidMount(){

    const tempArray = this.state.score_board_data

    this.dataBase.orderByChild("player_score").on('child_added', snap =>{
        tempArray.push({
            player_score: snap.val().player_score,
            player_name: snap.val().player_name
        });
        this.setState({score_board_data:tempArray});
     });
}

When I use the map() function on the state

this.state.score_board_data.map((player,i)=>{
    return(

              {player.player_name}
              {player.player_score}

    )
});

I get sorting based on this:

.orderByChild("player_score")

which for looks like this (
125,
150,
150,
150,
150,
150,
175,
225,
300,
325
)

Now I want to reverse it, so I use the reverse() method on the map() function like this

this.state.score_board_data.reverse().map( ....

i get this
   ( 325,
225,
150,
150,
150,
125,
150,
150,
175,
300 )
..... which is not reversed at all :D

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

2. componentWillUnmount dilemma.

I have a parent Component, which uses Google Firebase

//child
this.app = firebase.initializeApp(DB_CONFIG);
this.database = this.app.database().ref().child("numbers");

I pass the database ref to the child component as a prop

//child props from parent
dataBase={this.database}

I use react router to navigate from parent to child and back ...

but when I add an element to the database in the parent component and use the router to get to the child component which uses the same database reference as the parent I  get this error ...

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

I think I need to add some code in the child componentWillUnmount() to  remove the database from it .... sadly I  don't know how

//child
componentWillUnmount(){
}

I looked up on Google and here but couldn't figure it out

Body:
Array#reverse() does reverse the Array in place, like Array#sort().

So you don't just reverse the output you've created by map(), but instead you reverse the input this.state.score_board_data. Then you push() the 300 to the (reversed) Array.

Solution: change the order in wich you call the functions

this.state.score_board_data.map(...).reverse()


问:
MySQL query for maximum duplicate value(s)
```<code>| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |
</code>```

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

```<code>select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;
</code>```

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

```<code>| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |
</code>```

答:
```<code>select b_id, count(b_id)
    from books
    group by b_id
    having count(b_id) = (select max(count(b_id)) as count_bid from books);
</code>```

Body:
| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |


问:
How do I receive the default value of a form control in my custom control (ControlValueAccessor)
Let's say I have a form like this:

```<code>this.form = fb.group({
        genders: [['MALE']],
    });
</code>```

And I've implemented my own custom form control which implements the ControlValueAccessor interface. I understand that we have the writeValue method, but this method is only called when using either setValue or patchValue. How do I get the default value which was set in the FormBuilder's group method?

答:
You can do this by passing a simple @Input() inside a component.

```<code>@Component({ selector: 'my-component', template: `....` })
export class Component extends ControlValueAccessor {
  @Input('property') property: any;
}
</code>```

and then inside the HTML,

```<code><my-component formControl="gender" [property]="value">
</code>```

Body:
Let's say I have a form like this:

this.form = fb.group({
        genders: [['MALE']],
    });

And I've implemented my own custom form control which implements the ControlValueAccessor interface. I understand that we have the writeValue method, but this method is only called when using either setValue or patchValue. How do I get the default value which was set in the FormBuilder's group method?

Body:
You can do this by passing a simple @Input() inside a component.

@Component({ selector: 'my-component', template: `....` })
export class Component extends ControlValueAccessor {
  @Input('property') property: any;
}

and then inside the HTML,

<my-component formControl="gender" [property]="value">


问:
transfer data from a gridview to a database
I have this code

```<code>private void BindSecondaryGrid()
{
    DataTable dt = (DataTable)ViewState["SelectedRecords1"];
    gridview3.DataSource = dt;
    gridview3.DataBind();
}
</code>```

The selected records from the gridview2 are saved there ViewState["SelectedRecords1"].The columns are id, name, quantity, total.
Then these records are saved in gridview3 with

```<code>gridview3.DataSource = dt;
gridview3.DataBind();
</code>```

Now i would like to get these values from gridview3 and store them in a table in my database with same columns of course.Is there a way to do that?

答:
Is the question about "how to get to the data" or "how to write to DB"?

I'll try with "how to get to the data" :-)

You can loop the rows of "dt" using:

```<code>foreach(DataRow oRow in dt.Rows)
{
  int id = Convert.ToInt32(oRow["id"]);
  string name = oRow["name"].ToString();
  int quantity = Convert.ToInt32(oRow["quantity"]);
  int total = Convert.ToInt32(oRow["total"]);
}
</code>```

Then you need to setup a DB connection and add the values.

ContentLicense: CC BY-SA 2.5

Body:
I have this code

private void BindSecondaryGrid()
{
    DataTable dt = (DataTable)ViewState["SelectedRecords1"];
    gridview3.DataSource = dt;
    gridview3.DataBind();
}

The selected records from the gridview2 are saved there ViewState["SelectedRecords1"].The columns are id, name, quantity, total.
Then these records are saved in gridview3 with

gridview3.DataSource = dt;
gridview3.DataBind();

Now i would like to get these values from gridview3 and store them in a table in my database with same columns of course.Is there a way to do that?

Body:
Is the question about "how to get to the data" or "how to write to DB"?

I'll try with "how to get to the data" :-)

You can loop the rows of "dt" using:

foreach(DataRow oRow in dt.Rows)
{
  int id = Convert.ToInt32(oRow["id"]);
  string name = oRow["name"].ToString();
  int quantity = Convert.ToInt32(oRow["quantity"]);
  int total = Convert.ToInt32(oRow["total"]);
}

Then you need to setup a DB connection and add the values.


问:
Caching with Pyramid
How can I cache my views and templates with Pyramid?

The docs talk about pyramid_beaker ( https://docs.pylonsproject.org/projects/pyramid_beaker/en/latest/ ) but the page doesn't actually show how to use the cache.

The first result on google for "pyramid caching" is this - https://docs.pylonsproject.org/projects/pylons-webframework/en/latest/caching.html but it's about Pylons, there are lots of interesting things - caching of views, controller actions, templates and fragments, is it possible to do that in Pyramid, and how?

答:
You should install pyramid_beaker.

Then read the beaker documentation too.

Title: Caching with Pyramid


问:
Why compiler didn't use same object reference for a static expression tree?
As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

To clarify the question please see the example:

```<code>static void Main(string[] args)
{
    Test(p => true);//2637164
    Test(p => true);//3888474
    Test("true");//-292522067
    Test("true");//-292522067
    Console.ReadKey();
}

public static void Test(Expression<Func<string,bool>> exp)
{
    Console.WriteLine(exp.GetHashCode());
}

public static void Test(string str)
{
    Console.WriteLine(str.GetHashCode());
}
</code>```

答: Blindly guessing of what your actual issue is: instead of reference equality, use the answer from this question as the IEqualityComparer for your dictionary. It is obviously not as fast as Object.ReferenceEquals, but is definately faster than compiling the expression tree I would imagine.</p>

Body:
As I know Expression trees is immutable so why compiler didn't use same object reference for a static expression, like string literals?

To clarify the question please see the example:

static void Main(string[] args)
{
    Test(p => true);//2637164
    Test(p => true);//3888474
    Test("true");//-292522067
    Test("true");//-292522067
    Console.ReadKey();
}

public static void Test(Expression<Func<string,bool>> exp)
{
    Console.WriteLine(exp.GetHashCode());
}

public static void Test(string str)
{
    Console.WriteLine(str.GetHashCode());
}


问:
SQL - Coulmn headers as rows (for both 0's and 1's)
Please help, I have a table like this :

```<code>ID  HCC1    HCC2    HCC3    HCC4
101 0   1   1   0
102 0   0   1   0
103 0   0   0   0
</code>```

I want the resulting table to look like this:

```<code>ID  HCC
101 HCC2
101 HCC3
102 HCC3
103 0
</code>```

If a member has 1 in multiple HCC's , both need to be listed in separate rows (for instance ID-101). If member has 0 in all HCC's then there should be 0 in HCC column (for instance ID-103). I tried "unpivot" but it works only for 1's, I need 0's too.

I have 150 such column headers and 100,000 ID's

Thank You!

答:
One method uses union all:

```<code>select id, 'HCC1' as hcc from t where hcc1 = 1 union all
select id, 'HCC2' as hcc from t where hcc2 = 1 union all
select id, 'HCC3' as hcc from t where hcc3 = 1 union all
select id, 'HCC4' as hcc from t where hcc4 = 1 union all
select id, '0' as hcc from t where hcc1 = 0 and hcc2 = 0 and hcc3 = 0 and hcc4 = 0;
</code>```

This is standard SQL.  Specific databases might have other methods or short-cuts.

Body:
Please help, I have a table like this :

ID  HCC1    HCC2    HCC3    HCC4
101 0   1   1   0
102 0   0   1   0
103 0   0   0   0

I want the resulting table to look like this:

ID  HCC
101 HCC2
101 HCC3
102 HCC3
103 0

If a member has 1 in multiple HCC's , both need to be listed in separate rows (for instance ID-101). If member has 0 in all HCC's then there should be 0 in HCC column (for instance ID-103). I tried "unpivot" but it works only for 1's, I need 0's too.

I have 150 such column headers and 100,000 ID's

Thank You!

Body:
One method uses union all:

select id, 'HCC1' as hcc from t where hcc1 = 1 union all
select id, 'HCC2' as hcc from t where hcc2 = 1 union all
select id, 'HCC3' as hcc from t where hcc3 = 1 union all
select id, 'HCC4' as hcc from t where hcc4 = 1 union all
select id, '0' as hcc from t where hcc1 = 0 and hcc2 = 0 and hcc3 = 0 and hcc4 = 0;

This is standard SQL.  Specific databases might have other methods or short-cuts.


问:
Best Fit Rectangle From Set of Coplanar Points in Three.js
First off, I apologize if there is a solution for this somewhere, but I've done a great deal of digging through Three.js and A-Frame docs as well as Stack Overflow and haven't found what I'm looking for.

What I want to do is create a best-fit A-Frame plane from a set of Vector3s that I already know are coplanar. This can be easily done if the angle of the plane is a multiple of 90, but anything else and the .setFromPoints() algorithm for Box3s doesn't work the way I need it to.

The conversion from Three.js to A-Frame I can most likely handle myself, but if anyone wants to tackle that they're more than welcome to. I just need to create a rectangular plane that actually makes sense.

Basically, I want to create an algorithm that does this:

Create the bolded plane, rather than the lighter box/plane with too much wasted space.

I don't want to create custom geometry that perfectly fits the points, which I've already done. I actually do just want an A-Frame plane with nothing but height, width, position, and rotation attributes. I understand this is less precise, but it's far more ideal for what I'm working on.

答:
First find the best line passing through the points. This is called "line fit", like here: http://stackoverflow.com/questions/2352256/fit-a-3d-line-to-3d-point-data-in-java , it should be easy to do this in two dimensions instead of three. See also here: https://en.wikipedia.org/wiki/Deming_regression
The line gives you the angle, the minmax of the perpendicular distance of the points is the height of the rectangle, the minmax of the positions of the perpendicular foot points to the line makes the width of the rectangle.
Or you rotate all points by the negativ angle of the line and simply calculate the minmax values of the x and y components of the points for the width and height of the rectangle.</p>


问:
Cocoapods error after installing "firebase_firestore" Flutter plugin
I've got my app working with the Firebase RTDB but want to experiment with Firestore so I have followed the instructions and installed the 'firebase_firestore' plugin.

When I run my app now I get the following error:

```<code> Resolving dependencies of `Podfile`
    [!] Unable to satisfy the following requirements:

    - `Firebase/Firestore` required by `firebase_firestore (0.0.1)`

    Specs satisfying the `Firebase/Firestore` dependency were found, but they required a higher minimum deployment target.
</code>```

I've tried specifying platform :ios, '9.0' and also 10.0in my Podfile but that didn't make any difference. All other pods install fine.

Here's the entire Cocoapods run log: https://pastebin.com/raw/SBz8Bqgf

My Podfile looks like this (standard Flutter Podfile):

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  # Pods for Runner

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

Here's a link to the Podfile.lock, maybe that's more interesting. I see that it has not been updated with Firestore though, presumably because the run fails: https://pastebin.com/raw/hj2jHE76

答:
cloud_firestore has progressed to 0.03 by now, which should allow you to run the PODs.

in pubspec.yaml
  cloud_firestore: "^0.0.3"

If that does not work from the start, add Firebase core to your podfile and run pod install.

Note: As far as I have seen, you cannot yet combine Firestore with other modules such as Firebase auth or Firebase analytics.

Body:
I've got my app working with the Firebase RTDB but want to experiment with Firestore so I have followed the instructions and installed the 'firebase_firestore' plugin.

When I run my app now I get the following error:

 Resolving dependencies of `Podfile`
    [!] Unable to satisfy the following requirements:

    - `Firebase/Firestore` required by `firebase_firestore (0.0.1)`

    Specs satisfying the `Firebase/Firestore` dependency were found, but they required a higher minimum deployment target.

I've tried specifying platform :ios, '9.0' and also 10.0in my Podfile but that didn't make any difference. All other pods install fine.

Here's the entire Cocoapods run log: https://pastebin.com/raw/SBz8Bqgf

My Podfile looks like this (standard Flutter Podfile):

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  # Pods for Runner

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

Here's a link to the Podfile.lock, maybe that's more interesting. I see that it has not been updated with Firestore though, presumably because the run fails: https://pastebin.com/raw/hj2jHE76


问:
SSMS 2014 Only Allow Execute F5 if Text Selected
Update: Would like something that everyone can use, not just admin.

I tried to find if this question has already been asked before this post. In SSMS 2014, is there an option to only allow query execution if any text has been selected?

If none is selected, F5 and/or the execution button should be disabled. Thank you!

答:
I have this snippet that I sometimes include at the top of my queries:

```<code>raiserror('Highlight something and tell me what you''d like to do.', 20, -1) with log
</code>```

Per the Microsoft Connect page titled, Add an Execute Selected Text Only to SQL Server Management Studio:

...We are considering adding this as a text-editor option for an
  upcoming release. I have no way to mark it as "added to backlog", so
  I'm resolving it as "Won't Fix". It's there though...

Cheers
  -Sam Hughes

That was in 2011. If there is a way to do this I suspect it would be using Redgate. I'm not a redgate guru but I know that, for example, SQL Prompt will throw a warning before letting you do a DELETE or UPDATE without a WHERE clause. That's where I'd start.

Body:
I have this snippet that I sometimes include at the top of my queries:

raiserror('Highlight something and tell me what you''d like to do.', 20, -1) with log

Per the Microsoft Connect page titled, Add an Execute Selected Text Only to SQL Server Management Studio:

...We are considering adding this as a text-editor option for an
  upcoming release. I have no way to mark it as "added to backlog", so
  I'm resolving it as "Won't Fix". It's there though...

Cheers
  -Sam Hughes

That was in 2011. If there is a way to do this I suspect it would be using Redgate. I'm not a redgate guru but I know that, for example, SQL Prompt will throw a warning before letting you do a DELETE or UPDATE without a WHERE clause. That's where I'd start.


问:
Haskell - Couldn't match type `(Int, Integer)' with `Pos'
I am currently learning Haskell and I am currently having an issue.

This is my code:

```<code>data Pos = Pos (Int, Int) deriving (Show, Eq)
allCoordinates :: [Pos]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

allHelper ::Int -> [Int]
allHelper x = [x | y<-[0..8]]
</code>```

I have to use that specific data type and I am having a little issue due to this.

This code works perfectly fine if the code is written like this:

```<code>type Pos = (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]
</code>```

but  I need to edit this bit:

```<code>concat [(zip (allHelper x) [0..8]) | x<-[0..8]]
</code>```

so that it works with:

```<code>allCoordinates :: [Pos]
</code>```

It is probably a simple issue and I having a bit of a mental block however can anyone help?

Thank you

答:
If you write:

```<code>type Pos = (Int, Int)
</code>```

You have not constructed a new type: you have constructed a type alias, so you can interchange Pos with (Int, Int) in the code. So a function with signature f :: [(Int,Int)] is equivalent to f :: [Pos].

You can clean up the code and write:

```<code>allCoordinates :: [Pos]
allCoordinates = [ (x,y) | x <- [0..8], y <- [0..8]]
</code>```

Or even more clean (but probably somewhat harder to understand):

```<code>allCoordinates :: [Pos]
allCoordinates = (,) <$> [0..8] <*> [0..8]
</code>```

A disadvantage of the fact that you work with a type signature is that there can be a lot of functions defined on that type, and perhaps you want to define functions with the same name (in case of type classes), but with a different implementation. In that case you can define a datatype:

```<code><b>data</b> Pos = Pos (Int,Int)</code>```

Now we have defined a new type, with a constructor Pos. Now the above code will no longer work, but we can easily alter it by calling the constructor on the tuples we produce. So:

```<code>allCoordinates :: [Pos]
allCoordinates = [ <b>Pos</b> (x,y) | x <- [0..8], y <- [0..8]]</code>```

In case you define a type with one constructor and that constructor has one parameter, we can use newtype. Now we have defined a type, but Haskell can optimize it such that internally, it will not wrap and unwrap in a constructor, but simply treat the tuple in another way:

```<code><b>newtype</b> Pos = Pos (Int,Int)</code>```

Body:
I am currently learning Haskell and I am currently having an issue.

This is my code:

data Pos = Pos (Int, Int) deriving (Show, Eq)
allCoordinates :: [Pos]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

allHelper ::Int -> [Int]
allHelper x = [x | y<-[0..8]]

I have to use that specific data type and I am having a little issue due to this.

This code works perfectly fine if the code is written like this:

type Pos = (Int, Int)
allCoordinates :: [(Int, Int)]
allCoordinates = concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

but  I need to edit this bit:

concat [(zip (allHelper x) [0..8]) | x<-[0..8]]

so that it works with:

allCoordinates :: [Pos]

It is probably a simple issue and I having a bit of a mental block however can anyone help?

Thank you

Body:
If you write:

type Pos = (Int, Int)

You have not constructed a new type: you have constructed a type alias, so you can interchange Pos with (Int, Int) in the code. So a function with signature f :: [(Int,Int)] is equivalent to f :: [Pos].

You can clean up the code and write:

allCoordinates :: [Pos]
allCoordinates = [ (x,y) | x <- [0..8], y <- [0..8]]

Or even more clean (but probably somewhat harder to understand):

allCoordinates :: [Pos]
allCoordinates = (,) <$> [0..8] <*> [0..8]

A disadvantage of the fact that you work with a type signature is that there can be a lot of functions defined on that type, and perhaps you want to define functions with the same name (in case of type classes), but with a different implementation. In that case you can define a datatype:

data Pos = Pos (Int,Int)

Now we have defined a new type, with a constructor Pos. Now the above code will no longer work, but we can easily alter it by calling the constructor on the tuples we produce. So:

allCoordinates :: [Pos]
allCoordinates = [ Pos (x,y) | x <- [0..8], y <- [0..8]]

In case you define a type with one constructor and that constructor has one parameter, we can use newtype. Now we have defined a type, but Haskell can optimize it such that internally, it will not wrap and unwrap in a constructor, but simply treat the tuple in another way:

newtype Pos = Pos (Int,Int)


问:
Printing all values in one line in python in stead of multiple columns
I have a python code that gathers values from from multiple sources of a database, the output looks something like this

However I want to tune this function that will display the values like:

Following is the function which has some inputs from the database and are parsed accordingly:

```<code>import cx_Oracle
import sys
import fileinput
import string
import os, xmlrpclib

#contraints
DESIREDCOUNT = 50000
YEARS = [number of years i specify]
PARAMHASH = ['val1', 'val2','val3','val4' ]

for year i YEARS
        ids = getYearlySamples(DataCURR, year)

        modVal = len(ids)/DESIREDCOUNT;
        modval = int(modVal)

        if modval == 0:
            modval = 1

        finalids = []
        count = 0
        for id in ids:

            count = count + 1
            if count % modval == 0:# or True:

                sampleId = gatSamples(DataCURR, id)
                # grab the passed Value
                score = getXXValue(DataCURR, id)
                colldt = gatDate(DataCURR, id)
                dsMap = gatSamples(DataCURR, id) # will take sampleId

                for sid in dsMap:
                    for ds in dsMap[sid]:
                            for mark in dsMap[sid][ds][1]:

                                line = "%s,%s,%s,%s"%(sid, mark, score, colldt)

                                for col in PARAMHASH:
                                    if col == 'Somevalue1' or col == 'somevalue2':
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][mark][col]['val']
                                        except:
                                            line = line + ",*"
                                    else:
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][marker][col]['val']
                                            line = line + "," + dsMap[sid][ds][2][marker][col]['val']
                                        except:
                                            line = line + ",*"

                                print line
</code>```

Thanks

答:
Just add a , after your print statement.

i.e. print line,

```<code>import cx_Oracle
import sys
import fileinput
import string
import os, xmlrpclib

#contraints
DESIREDCOUNT = 50000
YEARS = [number of years i specify]
PARAMHASH = ['val1', 'val2','val3','val4' ]

for year i YEARS
        ids = getYearlySamples(DataCURR, year)

        modVal = len(ids)/DESIREDCOUNT;
        modval = int(modVal)

        if modval == 0:
            modval = 1

        finalids = []
        count = 0
        for id in ids:

            count = count + 1
            if count % modval == 0:# or True:

                sampleId = gatSamples(DataCURR, id)
                # grab the passed Value
                score = getXXValue(DataCURR, id)
                colldt = gatDate(DataCURR, id)
                dsMap = gatSamples(DataCURR, id) # will take sampleId

                for sid in dsMap:
                    for ds in dsMap[sid]:
                            for mark in dsMap[sid][ds][1]:

                                line = "%s,%s,%s,%s"%(sid, mark, score, colldt)

                                for col in PARAMHASH:
                                    if col == 'Somevalue1' or col == 'somevalue2':
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][mark][col]['val']
                                        except:
                                            line = line + ",*"
                                    else:
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][marker][col]['val']
                                            line = line + "," + dsMap[sid][ds][2][marker][col]['val']
                                        except:
                                            line = line + ",*"

                                print line,
                    print
</code>```

Body:
I have a python code that gathers values from from multiple sources of a database, the output looks something like this

However I want to tune this function that will display the values like:

Following is the function which has some inputs from the database and are parsed accordingly:

import cx_Oracle
import sys
import fileinput
import string
import os, xmlrpclib

#contraints
DESIREDCOUNT = 50000
YEARS = [number of years i specify]
PARAMHASH = ['val1', 'val2','val3','val4' ]

for year i YEARS
        ids = getYearlySamples(DataCURR, year)

        modVal = len(ids)/DESIREDCOUNT;
        modval = int(modVal)

        if modval == 0:
            modval = 1

        finalids = []
        count = 0
        for id in ids:

            count = count + 1
            if count % modval == 0:# or True:

                sampleId = gatSamples(DataCURR, id)
                # grab the passed Value
                score = getXXValue(DataCURR, id)
                colldt = gatDate(DataCURR, id)
                dsMap = gatSamples(DataCURR, id) # will take sampleId

                for sid in dsMap:
                    for ds in dsMap[sid]:
                            for mark in dsMap[sid][ds][1]:

                                line = "%s,%s,%s,%s"%(sid, mark, score, colldt)

                                for col in PARAMHASH:
                                    if col == 'Somevalue1' or col == 'somevalue2':
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][mark][col]['val']
                                        except:
                                            line = line + ",*"
                                    else:
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][marker][col]['val']
                                            line = line + "," + dsMap[sid][ds][2][marker][col]['val']
                                        except:
                                            line = line + ",*"

                                print line

Thanks

Body:
Just add a , after your print statement.

i.e. print line,

import cx_Oracle
import sys
import fileinput
import string
import os, xmlrpclib

#contraints
DESIREDCOUNT = 50000
YEARS = [number of years i specify]
PARAMHASH = ['val1', 'val2','val3','val4' ]

for year i YEARS
        ids = getYearlySamples(DataCURR, year)

        modVal = len(ids)/DESIREDCOUNT;
        modval = int(modVal)

        if modval == 0:
            modval = 1

        finalids = []
        count = 0
        for id in ids:

            count = count + 1
            if count % modval == 0:# or True:

                sampleId = gatSamples(DataCURR, id)
                # grab the passed Value
                score = getXXValue(DataCURR, id)
                colldt = gatDate(DataCURR, id)
                dsMap = gatSamples(DataCURR, id) # will take sampleId

                for sid in dsMap:
                    for ds in dsMap[sid]:
                            for mark in dsMap[sid][ds][1]:

                                line = "%s,%s,%s,%s"%(sid, mark, score, colldt)

                                for col in PARAMHASH:
                                    if col == 'Somevalue1' or col == 'somevalue2':
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][mark][col]['val']
                                        except:
                                            line = line + ",*"
                                    else:
                                        try:
                                            line = line + "," + dsMap[sid][ds][1][marker][col]['val']
                                            line = line + "," + dsMap[sid][ds][2][marker][col]['val']
                                        except:
                                            line = line + ",*"

                                print line,
                    print


问:
unable to select items in object in react component
in my redux action i have a fetch that works great. i'm using redux-thunk to dispatch it to my reducer. I then obviously connect my component to the store. within my reactjs component i am able to see the json object. lets say the structure is

```<code>object:{
    person: {
        name: {
            first: "first",
            last: "last"
    }
  }
}
</code>```

when I try to obtain just the first name like (person.name.first) it says "TypeError: Cannot read property 'first' of undefined" but first is defined. basically any information that is three items deep it gives me the same message.
When looking in my react component the issue is within the console.log(). the issue is happening anywhere within the component that i try to access the same location of the object not just within the console.log().

my Action:

```<code>import { WEEKWEATHER,
    TODAYWEATHER,
    SEARCH,
    LOCATIONERROR
} from './types';

//autolocate on page load
 export const autoLocate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {

          fetch(url)
             .then((response) => response.json())
             .then(response => forcast(dispatch, response))
             .catch( (error) => { dispatch({ type:LOCATIONERROR }) })
};
};

//locate with search bar
 export const Locate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {
 dispatch({type: SEARCH,
          payload: location
          });

          fetch(url)
            .then((response) => response.json())
            .then(response => forcast(dispatch, response))
            .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

};
};

//gathering forcast data from either auto or typed info
 const forcast = (dispatch, response) => {
 const location = response.location.zip
 const tenDayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/forecast10day/q/'
 + location + '.json'
    const todayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/hourly/q/' +
 location + '.json'

 fetch(todayUrl)
   .then((response) => response.json())
   .then(response => dispatch({
                               type: TODAYWEATHER,
                               payload: response.hourly_forecast[0]
                             }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

   fetch(tenDayUrl)
     .then((response) => response.json())
     .then(response => dispatch({
                                 type: WEEKWEATHER,
                                 payload:
 response.forecast.simpleforecast.forecastday[0]
                               }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

 };
</code>```

my reducer:

```<code>import { TODAYWEATHER,  WEEKWEATHER, LOCATIONERROR, SEARCH } from
'../Actions/types';

const INITIAL_STATE =  {
    week:[],
};
export default (state = INITIAL_STATE, action) => {
    switch (action.type){
        case WEEKWEATHER:
        return{ ...state, week:action.payload, loading:false }
                return state;
        }

    };
</code>```

my react componenet:

```<code>import React, { Component }     from 'react';
import { connect }              from 'react-redux';
import { Locate, autoLocate }   from '../Actions';
import {Card} from './Common'

class Weather extends Component{
    constructor(props){
        super(props);
        this.state={

         };
    }
    render() {
        const Loading = <Card>Loading...</Card>

        const Weather =  <div style={styles.PositionColumn}>
                            <div>tuesday</div>
                                <Card>
                                    <div style={styles.flexColumn}>
                                        <div style={styles.flexRow}>
                                            <div>jklsjdfkls</div>
                                            <div>2jlsfjle</div>
                                        </div>
                                        <div style={styles.flexRow}>
                                           <div>11</div>
                                            <div>22</div>
                                        </div>
                                    </div>
                                </Card>
                            </div>

        const displayWeather = (this.props.loading === true)? Loading
: Weather;

        console.log(this.props.week.date.day)

        return(
           <div>
                <img style={styles.Background} src=
{this.state.background} alt=''/>

                    {displayWeather}

            </div>
        );
    }
}

const mapStateToProps = state => {
    const week = state.locate.week;

        return{ week };
}

export default connect(mapStateToProps, {Locate, autoLocate})(Weather)
</code>```

答:
When React components mount, redux always sends the defaultState first. It doesn't matter if if fetch is in componentWillMount. That dispatch is not fast enough. You need to fix your initial state in your reducer file so that it has the same template as the actual data.

```<code>const INITIAL_STATE =  {
   person: {
     name: {
       first: "",
       last: ""
     }
   }
};
</code>```

Body:
in my redux action i have a fetch that works great. i'm using redux-thunk to dispatch it to my reducer. I then obviously connect my component to the store. within my reactjs component i am able to see the json object. lets say the structure is

object:{
    person: {
        name: {
            first: "first",
            last: "last"
    }
  }
}

when I try to obtain just the first name like (person.name.first) it says "TypeError: Cannot read property 'first' of undefined" but first is defined. basically any information that is three items deep it gives me the same message.
When looking in my react component the issue is within the console.log(). the issue is happening anywhere within the component that i try to access the same location of the object not just within the console.log().

my Action:

import { WEEKWEATHER,
    TODAYWEATHER,
    SEARCH,
    LOCATIONERROR
} from './types';

//autolocate on page load
 export const autoLocate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {

          fetch(url)
             .then((response) => response.json())
             .then(response => forcast(dispatch, response))
             .catch( (error) => { dispatch({ type:LOCATIONERROR }) })
};
};

//locate with search bar
 export const Locate = (location) => {
 const url =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/geolookup/q/' +
 location + '.json'

 return (dispatch) => {
 dispatch({type: SEARCH,
          payload: location
          });

          fetch(url)
            .then((response) => response.json())
            .then(response => forcast(dispatch, response))
            .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

};
};

//gathering forcast data from either auto or typed info
 const forcast = (dispatch, response) => {
 const location = response.location.zip
 const tenDayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/forecast10day/q/'
 + location + '.json'
    const todayUrl =
 'http://api.wunderground.com/api/cc9e7fcca25e2ded/hourly/q/' +
 location + '.json'

 fetch(todayUrl)
   .then((response) => response.json())
   .then(response => dispatch({
                               type: TODAYWEATHER,
                               payload: response.hourly_forecast[0]
                             }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

   fetch(tenDayUrl)
     .then((response) => response.json())
     .then(response => dispatch({
                                 type: WEEKWEATHER,
                                 payload:
 response.forecast.simpleforecast.forecastday[0]
                               }))
   .catch( (error) => { dispatch({ type:LOCATIONERROR }) })

 };

my reducer:

import { TODAYWEATHER,  WEEKWEATHER, LOCATIONERROR, SEARCH } from
'../Actions/types';

const INITIAL_STATE =  {
    week:[],
};
export default (state = INITIAL_STATE, action) => {
    switch (action.type){
        case WEEKWEATHER:
        return{ ...state, week:action.payload, loading:false }
                return state;
        }

    };

my react componenet:

import React, { Component }     from 'react';
import { connect }              from 'react-redux';
import { Locate, autoLocate }   from '../Actions';
import {Card} from './Common'

class Weather extends Component{
    constructor(props){
        super(props);
        this.state={

         };
    }
    render() {
        const Loading = <Card>Loading...</Card>

        const Weather =

tuesday

                                <Card>

jklsjdfkls

2jlsfjle

11

22

                                </Card>

        const displayWeather = (this.props.loading === true)? Loading
: Weather;

        console.log(this.props.week.date.day)

        return(

                    {displayWeather}

        );
    }
}

const mapStateToProps = state => {
    const week = state.locate.week;

        return{ week };
}

export default connect(mapStateToProps, {Locate, autoLocate})(Weather)

Body:
When React components mount, redux always sends the defaultState first. It doesn't matter if if fetch is in componentWillMount. That dispatch is not fast enough. You need to fix your initial state in your reducer file so that it has the same template as the actual data.

const INITIAL_STATE =  {
   person: {
     name: {
       first: "",
       last: ""
     }
   }
};


问:
Strikethrough UITableView cell text after cell containing String
I'd like to strikethrough all cell text in UITableView after a specific line of text.

Example (after "+")

I think I'm close, but the strikethrough isn't applied in the Simulator. (build is successful)

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

   if indexPath.row > dailyTasks.index(of: "+")! {

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: dailyTasks[indexPath.row])
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length))

    cell.textLabel?.attributedText = attributeString

   } else {
     cell.textLabel?.text = dailyTasks[indexPath.row]
    }

    cell.textLabel?.font = UIFont(name: "GillSans-Light", size: 17)
    cell.indentationLevel = 1
    cell.textLabel?.addCharactersSpacing(1.2)
    cell.backgroundColor = UIColor(red:0.99, green:0.97, blue:0.91, alpha:1.0)
    cell.selectionStyle = UITableViewCellSelectionStyle.none

    return cell

}
</code>```

答:
Don't set the font on the label if you are using an attributed string; instead set the font as an attribute.  Here is a playground that shows how to do it:</p>

```<code>import UIKit
import PlaygroundSupport

let label = UILabel()
let text = "sample text"
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let attributes: [NSAttributedStringKey: Any] =
    [NSAttributedStringKey.font: UIFont(name: "GillSans-Light", size: 17)!,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strikethroughStyle: 1]
label.attributedText = NSAttributedString(string: text, attributes: attributes)
view.addSubview(label)
label.sizeToFit()
PlaygroundPage.current.liveView = view
</code>```

Body:
I'd like to strikethrough all cell text in UITableView after a specific line of text.

Example (after "+")

I think I'm close, but the strikethrough isn't applied in the Simulator. (build is successful)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")

   if indexPath.row > dailyTasks.index(of: "+")! {

    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: dailyTasks[indexPath.row])
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length))

    cell.textLabel?.attributedText = attributeString

   } else {
     cell.textLabel?.text = dailyTasks[indexPath.row]
    }

    cell.textLabel?.font = UIFont(name: "GillSans-Light", size: 17)
    cell.indentationLevel = 1
    cell.textLabel?.addCharactersSpacing(1.2)
    cell.backgroundColor = UIColor(red:0.99, green:0.97, blue:0.91, alpha:1.0)
    cell.selectionStyle = UITableViewCellSelectionStyle.none

    return cell

}

Body:
Don't set the font on the label if you are using an attributed string; instead set the font as an attribute.  Here is a playground that shows how to do it:

import UIKit
import PlaygroundSupport

let label = UILabel()
let text = "sample text"
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let attributes: [NSAttributedStringKey: Any] =
    [NSAttributedStringKey.font: UIFont(name: "GillSans-Light", size: 17)!,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strikethroughStyle: 1]
label.attributedText = NSAttributedString(string: text, attributes: attributes)
view.addSubview(label)
label.sizeToFit()
PlaygroundPage.current.liveView = view


问:
Remove standard title from Magento bundled products
Hope anybody can help me on this matter.

I want to delete the standard title from the bundled products, but I can not find where to do this.

Help is appreciated.

Thanks and regards

Extra information

In my email confirmation I see:

Test Bundled products (= product name)

[title]
1x Product A - € 5.00     SKU1
[title]
1x Product B - € 5.00     SKU2

I already cleared the price in /app/code/local/Mage/Bundle/Block/Sales/Orders/Items/Renderer.php, but the [title] must be hidden or gone in my email notification so it finally looks like this:

1x Product A - € 5.00     SKU1
1x Product B - € 5.00     SKU2

答:
In your phtml template you can replace:

<?php echo $this->getSelectionQtyTitlePrice($_selection) ?>

with

```<code><?php echo $this->escapeHtml($_selection->getName()); ?>
<span class="price-notice">
    <span class="price">
        + <?php echo $this->formatPriceString($_selection->getPrice()); ?>
    </span>
</span>
</code>```

Body:
In your phtml template you can replace:

<?php echo $this->getSelectionQtyTitlePrice($_selection) ?>

with

<?php echo $this->escapeHtml($_selection->getName()); ?>
<span class="price-notice">
    <span class="price">
        + <?php echo $this->formatPriceString($_selection->getPrice()); ?>
    </span>
</span>


问:
Twitter Share encodeURIcomponent Struggle
I'm working on a project and I'm having some trouble with the encodeURIcomponent function. The site is a social media content bank that allows me to store copy in a CMS and display it on it's on page with links and buttons to share to social media sites. I'm struggling with the Twitter component and need some help. Here's my code:

function tweetClick() {
 var url = "http://urlfromcms.com";
 var text = "I'm getting this text dynamically from the CMS too.";
 window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text), '');
   }                   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Tweet It!</code>```

This is working like a champ with one problem. If the copy has an ampersand, apostrophe, quotes, etc. then it get's encoded as well and and the tweet needs to be edited which defeats the purpose. How to I encode to get the %20 in the spaces that twitter needs but leave my ampersands and apostrophes alone?

Any help would be greatly appreciated!

答: Your code seems to work as-is. Twitter is smart enough to decode the text you give it:

Body:
I'm working on a project and I'm having some trouble with the encodeURIcomponent function. The site is a social media content bank that allows me to store copy in a CMS and display it on it's on page with links and buttons to share to social media sites. I'm struggling with the Twitter component and need some help. Here's my code:

function tweetClick() {
 var url = "http://urlfromcms.com";
 var text = "I'm getting this text dynamically from the CMS too.";
 window.open('http://twitter.com/share?url='+encodeURIComponent(url)+'&text='+encodeURIComponent(text), '');
   }

Tweet It!

This is working like a champ with one problem. If the copy has an ampersand, apostrophe, quotes, etc. then it get's encoded as well and and the tweet needs to be edited which defeats the purpose. How to I encode to get the %20 in the spaces that twitter needs but leave my ampersands and apostrophes alone?

Any help would be greatly appreciated!