Q:

Connecting 3v digital output to Arduino using bi-directional level shifting (mosfet)

I have a digital output from a 3.3v device that I would like to make 5v tolerant - i.e be able to connect it to either a 3.3v OR 5v MCU.
I could technically connect the output directly to the Arduino Uno (or a 3.3v MCU) without any problems. The problem with the output is that the VOH minimum is 3v, while the VIH for the Arduino Uno is 3v - so there is no margin for error.
So I will need to shift this output up to 5v (if so required). I have considered 3 options:
1) a part like this - MC74VHC1GT125 - would do the trick.
2) Use an optocoupler - like the HCPL-181
3) Use a bi-directional level shifter using a MOSFET and 2 resistors - like in this Philips AN97055 note

Takes a wide variety of input voltages (3v in our case), and translates it to the Vcc reference voltage (which may be 3.3v or 5v depending on our MCU of choice)
The output from the optocoupler can be tied to the Vcc reference voltage, so it will work with either 3.3v or 5v MCU
The output side of this (connected to the MCU input) can be pulled up to the Vcc reference voltage, and so is again tolerant of 3.3v or 5v MCU and will pull up to the appropriate level

3 looks very attractive as I am already using a couple of MOSFETs (BSS138) in my design (for the I2C lines), for simplifying the BOM.
However, I see that it seems to be mainly used for open drain/collector configurations like I2C pins - a digital output pin is not an open drain/collector type.
My question is - can the bi-directional level shifter shown in the Philips note above be used in the uni-directional case of a digital output pin with no ill-effects?
If so, what does say, the MC74VHC1GT125 or another specifically designed level shifter IC, offer in terms of advantages over this approach? And how does the optocoupler approach compare?
I have scoured the internet quite a bit, but am left deeply yearning for more clarity and understanding!
Thanks!
Sridhar

A:

The bidirectional MOSFET level shifter automatically detects when one side is pulled down, and then pulls the other side down. So it will still work if only one side is ever pulled down.
The pull-up resistors are needed to get a defined high level when no device is pulling the line down. When you have a push/pull output, you do not need the resistor on that side.
A pull-up resistor combines with any parasitic capacitances in the circuit to form an RC low-pass filter, i.e., the rising edge of the output signal is slowed down. This is typically not yet a problem at the 100 kHz of I²C, but might become one at higher frequencies.
The MC74VHC1GT125, or actual level shifters like the SN74LVC1T45, have push/pull outputs, so they can reach higher frequencies.
An optocoupler is used if you need galvanic isolation. When you connect the grounds of the two devices together, it is not needed (but would still work).


Q:

Parse Json array with multiple objects using retrofit 2 in android

I'm using retrofit 2 for networking functions in my project, and I'm able to parse the json object responses from the server but now I'm supposed to parse a json array that look like this
[
    {
        "id_asset": 1,
        "id_category": 1,
        "id_brand": 2,
        "name": "Samsung Galaxy 6",
        "status": 1,
        "updated_at": "Oct 3, 2016 10:24:28 AM",
        "rank": 1,
        "rate": {
            "id_asset_rate": 2,
            "id_asset": 1,
            "value": 5000,
            "loan_to_value": 50,
            "offered": 2500,
            "annual_rate": 3,
            "quantity": 5,
            "created_at": "Oct 23, 2016 5:31:31 AM",
            "updated_at": "Oct 23, 2016 5:32:31 AM"
        },
        "best_rate": {
            "id_asset": "1",
            "value": "5000",
            "loan_to_value": "50",
            "offered": "2500",
            "annual_rate": "3",
            "quantity": "5",
            "rank": "1"
        },
        "category": {
            "id_category": 1,
            "id_parent": 0,
            "name": "Mobile Phones",
            "image": "",
            "sort": 1,
            "status": 1,
            "created_at": null,
            "updated_at": null,
            "_links": {
                "self": {
                    "href": "/v1/categories/1"
                }
            }
        },
        "brand": {
            "id_brand": 2,
            "name": "Samsung",
            "status": 1,
            "created_at": null,
            "updated_at": null
        },
        "_links": {
            "self": {
                "href": "/v1/assets/1"
            }
        }
    },
    {
        "id_asset": 2,
        "id_category": 1,
        "id_brand": 1,
        "name": "i Phone 5",
        "status": 1,
        "updated_at": "Oct 3, 2016 8:04:36 AM",
        "rank": false,
        "rate": null,
        "best_rate": false,
        "category": {
            "id_category": 1,
            "id_parent": 0,
            "name": "Mobile Phones",
            "image": "",
            "sort": 1,
            "status": 1,
            "created_at": null,
            "updated_at": null,
            "_links": {
                "self": {
                    "href": "/v1/categories/1"
                }
            }
        },
        "brand": {
            "id_brand": 1,
            "name": "Apple",
            "status": 1,
            "created_at": null,
            "updated_at": null
        },
        "_links": {
            "self": {
                "href": "/v1/assets/2"
            }
        }
    }
]

This is the response from the server and I created this POJO for the response
public class AssetResponse {
    private Integer id_asset;
    private Integer id_category;
    private Integer id_brand;
    private String  name;
    private Integer status;
    private String updated_at;

    private AssetRate assetRate;
    private AssetCategory assetCategory;
    private Links links;
    private Self self;
    private AssetBrand assetBrand;
    private HasLinked hasLinked;

    public Integer getId_asset() {
        return id_asset;
    }

    public void setId_asset(Integer id_asset) {
        this.id_asset = id_asset;
    }

    public Integer getId_category() {
        return id_category;
    }

    public void setId_category(Integer id_category) {
        this.id_category = id_category;
    }

    public Integer getId_brand() {
        return id_brand;
    }

    public void setId_brand(Integer id_brand) {
        this.id_brand = id_brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public AssetRate getAssetRate() {
        return assetRate;
    }

    public void setAssetRate(AssetRate assetRate) {
        this.assetRate = assetRate;
    }

    public AssetCategory getAssetCategory() {
        return assetCategory;
    }

    public void setAssetCategory(AssetCategory assetCategory) {
        this.assetCategory = assetCategory;
    }

    public Links getLinks() {
        return links;
    }

    public void setLinks(Links links) {
        this.links = links;
    }

    public Self getSelf() {
        return self;
    }

    public void setSelf(Self self) {
        this.self = self;
    }

    public AssetBrand getAssetBrand() {
        return assetBrand;
    }

    public void setAssetBrand(AssetBrand assetBrand) {
        this.assetBrand = assetBrand;
    }

    public HasLinked getHasLinked() {
        return hasLinked;
    }

    public void setHasLinked(HasLinked hasLinked) {
        this.hasLinked = hasLinked;
    }

    private class AssetRate {

        private Integer id_asset_rate;
        private Integer id_asset;
        private Double value;
        private Double loan_to_value;
        private Double offered;
        private Double annual_rate;
        private String updated_at;

        public Integer getId_asset_rate() {
            return id_asset_rate;
        }

        public void setId_asset_rate(Integer id_asset_rate) {
            this.id_asset_rate = id_asset_rate;
        }

        public Integer getId_asset() {
            return id_asset;
        }

        public void setId_asset(Integer id_asset) {
            this.id_asset = id_asset;
        }

        public Double getValue() {
            return value;
        }

        public void setValue(Double value) {
            this.value = value;
        }

        public Double getLoan_to_value() {
            return loan_to_value;
        }

        public void setLoan_to_value(Double loan_to_value) {
            this.loan_to_value = loan_to_value;
        }

        public Double getOffered() {
            return offered;
        }

        public void setOffered(Double offered) {
            this.offered = offered;
        }

        public Double getAnnual_rate() {
            return annual_rate;
        }

        public void setAnnual_rate(Double annual_rate) {
            this.annual_rate = annual_rate;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }
    }

    private class AssetCategory {

        private Integer id_category;
        private Integer id_parent;
        private String name;
        private String image;
        private Integer sort;
        private Integer status;
        private String created_at;
        private String updated_at;

        private Links links;

        public Integer getId_category() {
            return id_category;
        }

        public void setId_category(Integer id_category) {
            this.id_category = id_category;
        }

        public Integer getId_parent() {
            return id_parent;
        }

        public void setId_parent(Integer id_parent) {
            this.id_parent = id_parent;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public Integer getSort() {
            return sort;
        }

        public void setSort(Integer sort) {
            this.sort = sort;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public String getCreated_at() {
            return created_at;
        }

        public void setCreated_at(String created_at) {
            this.created_at = created_at;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }

        public Links getLinks() {
            return links;
        }

        public void setLinks(Links links) {
            this.links = links;
        }
    }

    private class Links {
        @SerializedName("self")
        @Expose
        private Self self;

        /**
         *
         * @return
         * The self
         */
        public Self getSelf() {
            return self;
        }

        /**
         *
         * @param self
         * The self
         */
        public void setSelf(Self self) {
            this.self = self;
        }
    }

    private class Self {
        @SerializedName("href")
        @Expose
        private String href;

        /**
         *
         * @return
         * The href
         */
        public String getHref() {
            return href;
        }

        /**
         *
         * @param href
         * The href
         */
        public void setHref(String href) {
            this.href = href;
        }

    }

    private class AssetBrand {

        private Integer id_brand;
        private String name;
        private Integer status;
        private String created_at;
        private String updated_at;

        public Integer getId_brand() {
            return id_brand;
        }

        public void setId_brand(Integer id_brand) {
            this.id_brand = id_brand;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

        public String getCreated_at() {
            return created_at;
        }

        public void setCreated_at(String created_at) {
            this.created_at = created_at;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }

    }

    private class HasLinked {

        private Integer has_linked;

        private Links links;

        public Integer getHas_linked() {
            return has_linked;
        }

        public void setHas_linked(Integer has_linked) {
            this.has_linked = has_linked;
        }

        public Links getLinks() {
            return links;
        }

        public void setLinks(Links links) {
            this.links = links;
        }

    }
   }
}

Is my pojo is right ?
My problem is, I can't parse this response. Any help will be appreciated.
Thanks in advance
EDIT :
This is my request to server (using rest api)
@GET("url")
Call<AssetResponse> getAssetList();

EDIT 2:  I've changed the code to List, as suggested by Niko Adrianus Yuwono.
This is the new changes
    private void getAssets() {

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(logging);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();

        final ApiInterface apiInterface = retrofit.create(ApiInterface.class);

        final AssetRequest assetRequest = new AssetRequest();
        assetRequest.setAcc_tok(ACCESS_TOKEN);

        final Call<List<AssetResponse>> assetList = apiInterface.getAssetList();

        assetList.enqueue(new Callback <List<AssetResponse>>() {

            @Override
            public void onResponse(Call<List<AssetResponse>> call, Response<List<AssetResponse>> response) {
                int statusCode = response.code();

                List<AssetResponse> assetResponseList = response.body();

                if (statusCode == 200) {

                  for (int i = 0; i < assetResponseList.size(); i++ ){
                        Integer id_asset = assetResponseList.get(i).getId_asset();
                        Integer id_category = assetResponseList.get(i).getId_category();
                        Integer status = assetResponseList.get(i).getStatus();
                        String name = assetResponseList.get(i).getName();
                        Log.d("Assets ","Asset id_asset  bb : " + id_asset);
                        Log.d("Assets ","Asset id_category  bb : " + id_category);
                        Log.d("Assets ","Asset name  bb : " + name);
                        Log.d("Assets ","Asset status  bb : " + status);

                        Double val = assetResponseList.get(i).getAssetRate().getValue();
                        Log.d("val ","val is : " +val);

                    }
                } else {
                    Toast.makeText(getContext(), "network error " + statusCode, Toast.LENGTH_LONG).show();

   }
  }

@Override
public void onFailure(Call<List<AssetResponse>> call, Throwable t) {

       Log.d("Asset GET Failure", "onFailure: " + t.getMessage());
      //showProgress(false);
    }
 });
}

and this is the response from the server

D/Assets: Asset id_asset  bb : 1 D/Assets: Asset id_category  bb : 1 D/Assets: Asset name  bb : Samsung Galaxy 6 D/Assets: Asset status
  bb : 1 10-26 13:13:17.898 22784-22784/ D/AndroidRuntime: Shutting down
  VM 10-26 13:13:17.898 22784-22784/ E/AndroidRuntime: FATAL EXCEPTION:
  main Process:  , PID: 22784 java.lang.NullPointerException: Attempt to
  invoke virtual method 'java.lang.Double
  .api.model.AssetResponse$AssetRate.getValue()' on a null object
  reference
  .AssetDatabaseFragment$2.onResponse(AssetDatabaseFragment.java:133)
  retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
  android.os.Handler.handleCallback(Handler.java:739)
  android.os.Handler.dispatchMessage(Handler.java:95)
  android.os.Looper.loop(Looper.java:148)
  android.app.ActivityThread.main(ActivityThread.java:5417)
  java.lang.reflect.Method.invoke(Native Method)
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Whenever I access the inner objects it throws error like the above

A:

Your Json key value data is changing from one index to another.
Wrong Json:
[{
//Make this either integer or boolean
 "rank": 1,
// best rate is object here in the next index, it's treated as boolean.
  "best_rate": {
            "id_asset": "1",
            "value": "5000",
            "loan_to_value": "50",
            "offered": "2500",
            "annual_rate": "3",
            "quantity": "5",
            "rank": "1"
        }

},
{
"rank":false,
"best_rate":false,
}
]

I have a complete project shared on github with your json.
https://github.com/lingarajsankaravelu/retrofit2v.git
Retrofit code should be like this as i mentioned in the question comment.
@GET("url")
Call<List<AssetResponse>> getAssetList();

As you have requested to explain the changes in your pojo class it should be like this.
AssetReponse.class:
public class AssetResponse {
    private Integer id_asset;
    private Integer id_category;
    private Integer id_brand;
    private String  name;
    private Integer status;
    private String updated_at;

    private AssetRate assetRate;
    private AssetCategory assetCategory;
    private Links links;
    private Self self;
    private AssetBrand assetBrand;
    private HasLinked hasLinked;

    public Integer getId_asset() {
        return id_asset;
    }

    public void setId_asset(Integer id_asset) {
        this.id_asset = id_asset;
    }

    public Integer getId_category() {
        return id_category;
    }

    public void setId_category(Integer id_category) {
        this.id_category = id_category;
    }

    public Integer getId_brand() {
        return id_brand;
    }

    public void setId_brand(Integer id_brand) {
        this.id_brand = id_brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public AssetRate getAssetRate() {
        return assetRate;
    }

    public void setAssetRate(AssetRate assetRate) {
        this.assetRate = assetRate;
    }

    public AssetCategory getAssetCategory() {
        return assetCategory;
    }

    public void setAssetCategory(AssetCategory assetCategory) {
        this.assetCategory = assetCategory;
    }

    public Links getLinks() {
        return links;
    }

    public void setLinks(Links links) {
        this.links = links;
    }

    public Self getSelf() {
        return self;
    }

    public void setSelf(Self self) {
        this.self = self;
    }

    public AssetBrand getAssetBrand() {
        return assetBrand;
    }

    public void setAssetBrand(AssetBrand assetBrand) {
        this.assetBrand = assetBrand;
    }

    public HasLinked getHasLinked() {
        return hasLinked;
    }

    public void setHasLinked(HasLinked hasLinked) {
        this.hasLinked = hasLinked;
    }
}

AssetRate.class
public class AssetRate {

        private Integer id_asset_rate;
        private Integer id_asset;
        private Double value;
        private Double loan_to_value;
        private Double offered;
        private Double annual_rate;
        private String updated_at;

        public Integer getId_asset_rate() {
            return id_asset_rate;
        }

        public void setId_asset_rate(Integer id_asset_rate) {
            this.id_asset_rate = id_asset_rate;
        }

        public Integer getId_asset() {
            return id_asset;
        }

        public void setId_asset(Integer id_asset) {
            this.id_asset = id_asset;
        }

        public Double getValue() {
            return value;
        }

        public void setValue(Double value) {
            this.value = value;
        }

        public Double getLoan_to_value() {
            return loan_to_value;
        }

        public void setLoan_to_value(Double loan_to_value) {
            this.loan_to_value = loan_to_value;
        }

        public Double getOffered() {
            return offered;
        }

        public void setOffered(Double offered) {
            this.offered = offered;
        }

        public Double getAnnual_rate() {
            return annual_rate;
        }

        public void setAnnual_rate(Double annual_rate) {
            this.annual_rate = annual_rate;
        }

        public String getUpdated_at() {
            return updated_at;
        }

        public void setUpdated_at(String updated_at) {
            this.updated_at = updated_at;
        }
    }

Seperate your inner class like above. Seperating your inner class model will be useful if you are working on a large project. where you don't have to write the same pojo class again. you can use this seperate class structure instead.


Q:

Android: Task affinity & Clear task

I am having three modules - ModuleA, ModuleB, ModuleC
ModuleA - 1 activity

MainActivity - no task affinity
Module B - 3 activities

Activity_A
task affinity = "com.performance.poc.main"
Activity_B
task affinity = "com.performance.poc.main"
Activity_C
task affinity = "com.performance.poc.main"
Module C - 1 activity

Activity_D - no task affinity
Navigation Case 1:

MainActivity
on btn Click - start Activity_A Intent.FLAG_ACTIVITY_NEW_TASK
on btn Click - start Activity_B
on btn Click - start Activity_C
on btn Click - start Activity_D Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK
Expected Task Result:
Task com.performance.poc
 Activity_D
 MainActivity
Task com.performance.poc.main
Activity_C
Activity_B
Activity_A
Expected : on starting the Activity_D task com.performance.poc.main should be cleared.
Actual : Still Activity_A, Activity_B, Activity_C remains but MainActivity is cleared.

Navigation Case 2:

MainActivity
on btn Click - start Activity_A Intent.FLAG_ACTIVITY_NEW_TASK
on btn Click - start Activity_B
on btn Click - start Activity_C Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK
on btn Click - start Activity_D Intent.FLAG_ACTIVITY_NEW_TASK

Expected Task Result:
Task com.performance.poc
Activity_D
MainActivity
Task com.performance.poc.main
Activity_C
Activity_B
Activity_A
 Expected : on starting the Activity_C, in task com.performance.poc.main, Activity_A, Activity_B should be cleared.
Actual :  Activity_A, Activity_B is cleared as expected.

My Question here is why in Case1, even though Activity_A, Activity_B, Activity_C are in same task and it is not clearing these and clearing MainActivity.
The Clear_Task should clear the existing task of the activity from which startActivity is called with intent new_task and clear_task.  or it will clear the task of target activity.
If it is Target activity, I need to clear the task of the leaving activity, is there any way to do it?

A:

Setting Intent.FLAG_ACTIVITY_CLEAR_TASK will clear the target task.
You say that you need to clear the current task. You can do this by using an intermediate Activity. Just create a simple Activity that does the following in onCreate():
Intent = new Intent(this, ActivityD.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();

This simple Activity should have the same taskAffinity as ActivityA, B and C.
When ActivityC wants to start ActivityD, it should start this activity instead like this:
Intent = new Intent(this, SimpleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);

This will clear the current task and then SimpleActivity will launch ActivityD and finish, which will finish the task.


Q:

How to get patches to draw with equal aspect ratio even though associated axis does not have equal aspect ratio?

Consider the following toy code:
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

def draw_circle_arrangement(ax, drawing_origin, drawing_space, scale, num_circles, box_height, box_width):
    bw = drawing_space*(box_width*scale)

    drawing_origin[0] = drawing_origin[0] - bw*0.5

    circle_diameter = drawing_space*scale
    circle_radius = 0.5*circle_diameter
    y_delta = np.array([0., circle_diameter])
    x_delta = np.array([circle_diameter, 0.])

    cell_origin = drawing_origin + np.array([circle_radius, circle_radius])
    y_delta_index = 0
    x_delta_index = 0

    for ci in range(num_circles):
        cell_patch = mpatches.Circle(cell_origin + y_delta_index*y_delta + x_delta_index*x_delta, radius=circle_radius, color='k', fill=False, ls='solid', clip_on=False)
        ax.add_artist(cell_patch)

        if y_delta_index == box_height - 1:
            y_delta_index = 0
            x_delta_index += 1
        else:
            y_delta_index += 1

fig, ax = plt.subplots()

# each tuple is: number of circles, height of box containing circles, width of box containing circle
circle_arrangements = [(10, 2, 5), (3, 1, 3), (1, 1, 1)]
data = np.random.rand(3)
ax.set_ylim([0, 1])
ax.plot(np.arange(3) + 1, data, marker='o')
ax.get_xaxis().set_ticklabels([])
scale = 1./10.

for i, ca in enumerate(circle_arrangements):
    do = np.array([1.0 + i, -0.2])
    nc, bh, bw = ca
    draw_circle_arrangement(ax, do, 0.8, scale, nc, bh, bw)

When run, it produces output like so:

As you can see, the circles are not circles! They are squished. One way to fix this is by setting ax.set_aspect('equal'), but if I don't necessarily want the axis aspect ratio to be equal, how can I still have the patches produced that way?

A:

It is not possible to only set part of the axes aspect to equal. The solution would be either to draw the circles in a different coordinate system, or, by using a different box that uses a different coordinate system.
I find the latter solution preferable. That would involve using a DrawingArea which can be placed inside an AnnotationBbox.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.offsetbox import  DrawingArea, AnnotationBbox

def draw_circle_arrangement(ax, drawing_origin, radius,
                            num_circles, box_height, box_width):
    y_delta_index = 0
    x_delta_index = 0

    origin = np.array([radius,radius])
    y_delta = np.array([0., 2*radius])
    x_delta = np.array([2*radius, 0.])

    da = DrawingArea(box_width*2*radius, box_height*2*radius, 0, 0)

    for ci in range(num_circles):
        cell_patch = mpatches.Circle(origin+y_delta_index*y_delta + x_delta_index*x_delta,
                                     radius=radius, color='k', fill=False, ls='solid',clip_on=False)
        da.add_artist(cell_patch)

        if y_delta_index == box_height - 1:
            y_delta_index = 0
            x_delta_index += 1
        else:
            y_delta_index += 1
    ab = AnnotationBbox(da, xy=(drawing_origin[0],0),
                        xybox=drawing_origin,
                        xycoords=("data", "axes fraction"),
                        boxcoords=("data", "axes fraction"),
                        box_alignment=(0.5,0.5), frameon=False)

    ax.add_artist(ab)

fig, ax = plt.subplots()
# each tuple is: number of circles, height of box containing circles, width of
#box containing circle
circle_arrangements = [(10, 2, 5), (3, 1, 3), (1, 1, 1)]
data = np.random.rand(3)
ax.set_ylim([0, 1])
ax.plot(np.arange(3) + 1, data, marker='o')
ax.get_xaxis().set_ticklabels([])

for i, ca in enumerate(circle_arrangements):
    do = np.array([1.0 + i, -0.06])
    nc, bh, bw = ca
    draw_circle_arrangement(ax, do, 5, nc, bh, bw)

plt.show()

The units of the DrawingArea are points. E.g. in the first case we create a DrawingArea of 5*2*5 = 50 points width and place 5 circles with a radius of 5 points into it (the 5 circles fill the complete 50 points then). A point is ~1.4 pixels. The position of the AnnotationBox is given in data coordinates for the x position and in axes fraction for the y position. This can be changed by using the boxcoords argument. Same for the xy argument, where we make sure that the y coordinate is at 0, and thus inside the axes (such that it AnnotationsBox is shown).


Q:

Android, passing LinearLayout, RelativeLayout and TextView between methods

I am trying to create a thread that update a certain TextView.  I have already setup the LinearLayout, RelativeLayout and TextView in the onCreate() method; I merely want to update that information.  Everything compiles fine it's just when I execute it on my phone I get a force close run time error.
I have a feeling the issue resides with the onRefresh(...){ and how I pass that information.  Would anyone be able to clarify how to pass that information correctly?
Thank you!
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Define String(s)
    String infoText = "Push button to test";
    String buttonLabelA = "Show Hello!";

    //Setup screen orientation
    LinearLayout mainWindow = new LinearLayout(this);
    mainWindow.setOrientation(LinearLayout.VERTICAL);

    //Set title
    setTitle("JOHello");

    //Set the static text that will appear in the window
    TextView label = new TextView(this);
    label.setText(infoText);
    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(400, 50);
    params1.leftMargin = 15;
    params1.topMargin = 5;
    mainWindow.addView(label, params1);

    //Set button
    Button greetingButton = new Button(this);//instantiate greeting button
    greetingButton.setText(buttonLabelA);//set button text
    mVB localVB = new mVB();
    greetingButton.setOnClickListener(localVB);//link button click to event
    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(200, 75);
    params2.leftMargin = 100;
    params2.topMargin = 100;
    mainWindow.addView(greetingButton, params2);//add button to current view*/

    //Changeable text
    TextView chgTxt = new TextView(this);
    chgTxt.setText(localVB.greetingText);
    RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(400, 50);
    params3.leftMargin = 15;
    params3.topMargin = 600;
    mainWindow.addView(chgTxt, params3);

    setContentView(mainWindow);

    doRefresh(mainWindow, params3, chgTxt);
}

private void doRefresh(final LinearLayout localWindow, final RelativeLayout.LayoutParams localParams, final TextView localText){
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            localText.setText("It truly works!");
            localWindow.addView(localText, localParams);
        }
    }, 1000);
}

I have made the variables global Eureeka! I now have a run time issue where it hangs when Handler is declared:
public class MainActivity extends Activity {

private final Handler handler = new Handler();//Hanging!?
public LinearLayout mainWindow = new LinearLayout(this);
public TextView mainText = new TextView(this);
public RelativeLayout.LayoutParams mainParams = new RelativeLayout.LayoutParams(400, 50);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

...
}

public void doRefresh(){
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            mainText.setText("It fucking works");
            mainWindow.addView(mainText, mainParams);
        }
    }, 1000);
}

Here is the log cat:

02-13 23:32:56.204: E/AndroidRuntime(11184):  ... 11 more

02-13 23:33:43.500: I/dalvikvm(11215): Debugger is active
02-13 23:33:43.580: I/System.out(11215): Debugger has connected
02-13 23:33:43.580: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:43.781: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:43.981: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:44.181: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:44.381: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:44.581: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:44.782: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:44.982: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:45.182: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:45.372: I/System.out(11215): waiting for debugger to settle...
02-13 23:33:45.582: I/System.out(11215): debugger has settled (1410)
02-13 23:34:14.651: D/AndroidRuntime(11215): Shutting down VM
02-13 23:34:14.661: W/dalvikvm(11215): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
02-13 23:34:14.711: E/AndroidRuntime(11215): FATAL EXCEPTION: main
02-13 23:34:14.711: E/AndroidRuntime(11215): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.johello/com.johello.MainActivity}: java.lang.NullPointerException
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1738)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread.access$1500(ActivityThread.java:132)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.os.Looper.loop(Looper.java:143)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread.main(ActivityThread.java:4196)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at java.lang.reflect.Method.invokeNative(Native Method)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at java.lang.reflect.Method.invoke(Method.java:507)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at dalvik.system.NativeStart.main(Native Method)
02-13 23:34:14.711: E/AndroidRuntime(11215): Caused by: java.lang.NullPointerException
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.view.View.<init>(View.java:1915)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.view.ViewGroup.<init>(ViewGroup.java:299)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.widget.LinearLayout.<init>(LinearLayout.java:116)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at com.johello.MainActivity.<init>(MainActivity.java:16)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at java.lang.Class.newInstanceImpl(Native Method)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at java.lang.Class.newInstance(Class.java:1409)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
02-13 23:34:14.711: E/AndroidRuntime(11215):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1730)
02-13 23:34:14.711: E/AndroidRuntime(11215):    ... 11 more

Thanks again for your help guys!

A:

Your NullPointerException stack trace is caused by the change you made to the view creation.  You can't instantiate views like this:
public LinearLayout mainWindow = new LinearLayout(this);
public TextView mainText = new TextView(this);

as member variables because the Context they need (your this pointer) doesn't have valid resources until onCreate() is called.  If you want to declare the references to the view as class members, that's fine; but instantiate them in onCreate(), a la:
public class MainActivity extends Activity {
    public LinearLayout mainWindow;
    public TextView mainText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mainWindow = new LinearLayout(this);
        mainText = new TextView(this);

        mainWindow.addView(mainText);

        setContentView(mainWindow);
    }

}

The crash you were probably receiving with your old code is that a view cannot be added to a parent multiple times, and doing so will throw an exception.  In the old code, the last mainWindow.addView() inside and later localWindow.addView() from inside the Handler attempt to add the same TextView to the same parent view twice.


Q:

How to use observeEvent with a checkbox event Shiny

How do I trigger an action (in this case updateSelectInput) with observeEvent based on a TRUE/FALSE checkbox event?
For example I would like to update result when test is TRUE:
library(shiny)
ui<-fluidPage(
  checkboxInput("test","Test",value=FALSE),
  selectInput("result","Result",choices=c("1","2","3"),selected="1")
)

server<-function(input, output){
  observeEvent(input$test{
    updateSelectInput(session,"result",choices=c("1","2","3","4","5"),selected="1")
  })
}

shinyApp(ui=ui,server=server)

A:

See below:
library(shiny)
ui<-fluidPage(
    checkboxInput("test","Test",value=FALSE),
    selectInput("result","Result",choices=c("1","2","3"),selected="1")
)

server<-function(input, output, session){
    observeEvent(input$test,{
        updateSelectInput(session,"result",choices=c("1","2","3","4","5"),selected="1")
    }, ignoreInit = TRUE)
}

shinyApp(ui=ui,server=server)

I added session to the server function(), a comma after input$test, and ignoreInit = TRUE.
Update
library(shiny)
ui<-fluidPage(
    checkboxInput("test","Test",value=FALSE),
    selectInput("result","Result",choices=c("1","2","3"),selected="1")
)

server<-function(input, output, session){
    observeEvent(input$test,{
        updateSelectInput(session,"result",choices=if(input$test == FALSE){c("1","2","3")}else{c("1","2","3","4","5")},selected="1")

    }, ignoreInit = TRUE)
}

shinyApp(ui=ui,server=server)


Q:

jQuery's isFunction and InternetExplorer

When adapting jQuery's isFunction method
isFunction: function( obj ) {
  return toString.call(obj) === "[object Function]";
}

InternetExlorer 8 returns the following error: "Object doesn't support this property or method". A good article digging into this function won't fix this behaviour. To check wether obj is defined, I changed the function in reference to the MSDN article:
isFunction: function( obj ) {
  return obj && toString.call(obj) === "[object Function]";
}

Any other ideas for a solution?

A:

You need to call the toString method directly from the Object.prototype object:
function isFunction (obj) {
    return Object.prototype.toString.call(obj) === "[object Function]";
}

alert(isFunction({})); // false
alert(isFunction(function{})); // true

jQuery has a local variable named toString that refers to the method on Object.prototype.
Calling just toString.call(obj); without declaring a toString identifier on scope, works on Firefox, Chrome, etc, just because the Global object inherits from Object.prototype, but this is not guaranteed by the spec.
Object.prototype.isPrototypeOf(window); // false on IE

The article you link to talks about a change that was introduced in the ECMAScript 5th Edition specification to the call and apply methods.
Those methods allow you to invoke a function passing the first argument as the this value of the invoked function.
On ECMAScript 3, if this argument was undefined or null, the this value of the invoked function will refer to the global object, for example:
function test () {  return this; }
test.call(null) === window; // true

But that changed in ES5, the value should now be passed without modification and that caused the Object.prototype.toString to throw an exception, because an object argument was expected.
The specification of that method changed, now if the this value refers to undefined or null the string "[object Undefined]" or "[object Null]" will be returned, fixing the problem (thing that I don't think is really good, since both results results feel just wrong, undefined and null are not objects, they are primitives... that made me remember typeof null == 'object'... Moreover I think it messes up with the concept of the [[Class]] internal property, anyway...)
Now you might wonder why jQuery uses this method to check for a function object, instead of using the typeof operator?
Implementation bugs, for example in Chrome/Safari/WebKit, the typeof for RegExp objects returns "function", because RegExp objects where made callable, e.g.:
typeof /foo/; // "function" in Chrome/Safari/WebKit

The typeof operator returns "function" if the object implements the [[Call]] internal property, which made objects to be callable.
This was originally introduced by the Mozilla implementations, invoking a RegExp object is equivalent to call the exec method.


Q:

calculating a hash of a data structure?

Let's say I want to calculate a hash of a data structure, using a hash algorithm like MD5 which accepts a serial stream, for the purposes of equivalence checking. (I want to record the hash, then recalculate the hash on the same or an equivalent data structure later, and check the hashes to gauge equivalence with high probability.)
Are there standard methods of doing this?
Issues I can see that are problematic are

if the data structure contains an array of binary strings, I can't just concatenate them since ["abc","defg"] and ["ab","cdefg"] are not equivalent arrays
if the data structure contains a collection that isn't guaranteed to enumerate in the same order, e.g. a key-value dictionary {a: "bc", d: "efg", h: "ijkl"} which should be considered equivalent to a key-value pair {d: "efg", h: "ijkl", a: "bc"}.

A:

For the first issue, also hash the lengths of the strings. This will differentiate their hashes.
For the second, sort the keys.


Q:

How to notify UI of change with readonly property?

In WPF, I have a property with only a get{}.  The value is coming from the return of method.  NotifyPropertyChanged is often used within a property set{}.  It can then notify the UI and the updated value is displayed.  But with a get{} only, there isn't a way of detecting if a new or different value is available since you have to execute the method to check.
Is there some way to update the UI without having to keep a local value that contains the last value from the method, in which case a compare would need to be done?

A:

But with a get{} only, there isn't a way of detecting if a new or different value is available since you have to execute the method to check.

The problem boils down to this: What is changing the property?  The method that changes the property should call your NotifyPropertyChanged with the name of the property, which will, in turn, cause WPF to refetch the value and update the user interface.
WPF doesn't care where the PropertyChanged event gets raised - it just listens for it, and refreshes the binding as needed.

Edit in response to comment:
It sounds like this may be the result of performing some operation upon your Model class.  In this case, it's common that you know that one or more properties may change, but not necessarily which ones.  If your Model implements INotifyPropertyChanged, you can subscribe to that and "bubble up" the notifications to the UI via your NotifyPropertyChanged method.  If it does not, however, there is another option.
If you know that one or more properties may change, you can raise a PropertyChanged event with string.Empty as the PropertyName in the EventArgs.  This will cause all bound properties to get refreshed by WPF.  This is likely just a matter of putting something like this in your code:
this.Model.DoSomething(); // This will change 1+ properties
this.NotifyPropertyChanged(string.Empty); // Refresh our entire UI

I wouldn't recommend doing this everywhere, however, as it does add overhead - but it's often the cleanest solution if you don't know which properties will change when you perform an operation.


Q:

StreamReader issue

if I put a debuger from starting line one of this code and step through i dont get anything
event after the line
    xmlData = reader.ReadToEnd();

but if I have debugger on the last line of this code.. where the brace closes, I get everything. i dont know if this only the debuger acting crazy, or a real thing
using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
    xmlData = reader.ReadToEnd();
}

Can anyone tell me whats going on. cause sometimes i am not able to get any data from streamreader, even though the data is sent correctly.
Thanks

A:

The reader isn't going to perform the actual "read" until the ReadToEnd method is called.  What are you trying to do?


Q:

unable to run npm start for react-native project

This is my first attempt at running react-native project. Followed all the instructions mentioned at react-native side. and ran 'npm start'
Getting below error in command prompt :
     ERROR  watchman--no-pretty get-sockname returned with exit code null dyld: Library not loaded: /usr/local/lib/libpcre.1.dylib
  Referenced from: /usr/local/bin/watchman
  Reason: image not found

Error: watchman--no-pretty get-sockname returned with exit code null dyld: Library not loaded: /usr/local/lib/libpcre.1.dylib
  Referenced from: /usr/local/bin/watchman
  Reason: image not found

    at ChildProcess.<anonymous> (/Users/z013mrq/AwesomeProject/node_modules/react-native/node_modules/sane/node_modules/fb-watchman/index.js:198:18)
    at emitTwo (events.js:87:13)
    at ChildProcess.emit (events.js:172:7)
    at maybeClose (internal/child_process.js:818:16)
    at Socket.<anonymous> (internal/child_process.js:319:11)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at Pipe._onclose (net.js:469:12)

A:

Try reinstalling watchman:
npm r -g watchman
brew update && brew upgrade
brew install watchman

If that doesn't fix it, try the answers posted here.

Try to re-install libtool by:
brew reinstall libtool --universal && brew unlink libtool && brew link
  libtool
If won't help, try to remove it completely and re-try above
  again:
brew uninstall libtool


Q:

Android language changes after rotation

When my app is installed, on first run it asks user to choose language; But if user starts app on second time, language is set automatically (to previously selected one).
Problem is that, on first run when user selects language, app still is in English (no matter what language user selects), but if I rotate device, then language is changed to correct one (to selected one). Same problem occurs on apps second run; App starts in English, but after rotation language is changed to correct one.
Any suggestions? thank you in advance
here code from MainActivity from where I change language:
private void initApp() {
        if (Settings.getLanguage().equals("")){
            String[] items = { getResources().getString(R.string.lang_eng), getResources().getString(R.string.lang_geo)};
            showDialogSingleChoise(items, getResources().getString(R.string.select_language_title), 0, false, false, this.languageSelectedListener, this.languageConfirmedListener, null);
        } else {
            System.out.println("initApp: " + Settings.getLanguage());

            Settings.setLanguage(MainActivity.this.getResources(), Settings.getLanguage());
            appVersionCheck();
        }
    }

private OnClickListener languageConfirmedListener = new OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        Settings.setLanguage(MainActivity.this.getResources(), MainActivity.this.language);
        appVersionCheck();
    }
};

and here is code fragment from settings:
public static void setLanguage(Resources res, String langString){
        System.out.println("lang in pref: " + langString);
        setStringProperty(PREFS_LANG ,langString);
        MainApp.getInstance().setLocale(res);
    }

Here is my Application class:
public class MainApp extends Application {
    private static volatile MainApp instance;

    public static MainApp getInstance() {
        return MainApp.instance;
    }

    @Override
    public void onCreate() {
        MainApp.instance = this;
        super.onCreate();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setLocale(this.getResources());
    }

    public void setLocale(Resources res) {
        System.out.println("initApp: " + Settings.getLanguage() == "" ? Settings.LANG_EN : Settings.getLanguage());
        Configuration conf = res.getConfiguration();
        conf.locale = new Locale(Settings.getLanguage() == "" ? Settings.LANG_EN : Settings.getLanguage());
        res.updateConfiguration(conf, res.getDisplayMetrics());
    }
}

and lastly, this is manifest (do I need android:configChanges="locale" at all?):
<application
        android:name="...MainApp"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="....MainActivity"
            android:configChanges="locale"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

A:

Your configuration cannot be applied until your Activity is restarted,so when you click to change locale it cannot be applied at once,but when you rotate your screen the Activity restarts thus applies your configuration changes.
You should restart your Activity manually after click to change the locale,and here is a code demo to restart your Activity:
private void restartActivity() {
    Intent intent = getIntent();
    finish();
    startActivity(intent);
    }

And I think you should not write the changing locale code in your Application class,it should be written in the Activity that you use to change locale.
As for applying new locale in the future app opening,you can use SharedPreferences to save your configuration and get the locale value every time your application is opened and apply it.
You can get the SharedPreferences and apply the locale in the Application class's onCreate() method.
And you certainly should write the android:configChanges="locale|orientation" in your manifest and the onConfigurationChanged() method is also necessary.Because if you rotate the screen or do anything else that change the system configuration that can restart your Activity,the default locale will be applied.So you should make sure the new locale is applied every time the configuration is changed.
For more details about how to deal with locale change,you can read this: How to refresh activity after changing language (Locale) inside application


Q:

Bold header (text) row with siunitx S column and column aligment

Ok, I want to have the first row of my table bold faced: Make first row of table all bold, done! But my table has a lot of numbers so siunitx comes in handy with its column specifier S, then the first solution makes the S columns ragged left (why?).
Seems like Bold row in table aligned with dcolumn: A solution with package siunitx could be what I'm looking for, but no. The same thing happens with Heiko's proposal. This is obviously because of the text Header, but why is it happening and how can I get around it?
The following MWE incorporates both solutions and the compilation result is placed below.
\documentclass{standalone}
\usepackage{siunitx,array,booktabs,multirow}
\sisetup{output-decimal-marker={,}}
\newcolumntype{$}{>{\global\let\currentrowstyle\relax}}
\newcolumntype{^}{>{\currentrowstyle}}
\newcolumntype{L}{%
  >{\rowstyle{\relax}}l%
}
\newcolumntype{B}{%
  >{\currentrowstyle}S[detect-weight]%
}
\newcommand{\rowstyle}[1]{\gdef\currentrowstyle{#1}%
  #1\ignorespaces
}

\begin{document}
\begin{tabular}{L^cBB}
    \toprule
    \rowstyle{\bfseries}
    \multirow{2}{*}{Day} & {Running time} & {Water bag weight} & {Frost formation rate} \\
 & [days] & \multicolumn{1}{c}{[\si{\gram}]} & \multicolumn{1}{c}{[\si{\gram\per\hour}]} \\
\midrule
    26.09.2016  &   4   &   1098,2  &   11,4    \\
    27.09.2016  &   1   &   329,8   &   13,5    \\
    28.09.2016  &   1   &   288,4   &   11,8    \\
    29.09.2016  &   1   &   291,7   &   11,9    \\
    \midrule
    \rowstyle{\bfseries}
    Average         &       &       &   12,2    \\
    \bottomrule
\end{tabular}

\begin{tabular}{$l^c^S^S}
    \toprule
    \rowstyle{\bfseries}
    \multirow{2}{*}{Day} & {Running time} & {Water bag weight} & {Frost formation rate} \\
 & [days] & \multicolumn{1}{c}{[\si{\gram}]} & \multicolumn{1}{c}{[\si{\gram\per\hour}]} \\
\midrule
    26.09.2016  &   4   &   1098,2  &   11,4    \\
    27.09.2016  &   1   &   329,8   &   13,5    \\
    28.09.2016  &   1   &   288,4   &   11,8    \\
    29.09.2016  &   1   &   291,7   &   11,9    \\
    \midrule
    \rowstyle{\bfseries}
    Average         &       &       &   12,2    \\
    \bottomrule
\end{tabular}
\end{document}

A:

The issue here is \relax. This is a 'do nothing' command in TeX but is non-expandable. The siunitx package takes this as being 'end of number' in a table cell: there's not reason to expect one in the middle of a number. As such, you need to arrange that \currentrowstyle is something else, for example an empty macro, when it's not 'active':
\documentclass{standalone}
\usepackage{siunitx,array,booktabs,multirow}
\sisetup{output-decimal-marker={,}}
\newcolumntype{$}{>{\global\let\currentrowstyle\empty}}
\newcolumntype{^}{>{\currentrowstyle}}
\newcolumntype{L}{%
  >{\rowstyle{}}l%
}
\newcolumntype{B}{%
  >{\currentrowstyle}S[detect-weight]%
}
\newcommand{\rowstyle}[1]{\gdef\currentrowstyle{#1}%
  #1\ignorespaces
}

\begin{document}
\begin{tabular}{L^cBB}
    \toprule
    \rowstyle{\bfseries}
    \multirow{2}{*}{Day} & {Running time} & {Water bag weight} & {Frost formation rate} \\
 & [days] & \multicolumn{1}{c}{[\si{\gram}]} & \multicolumn{1}{c}{[\si{\gram\per\hour}]} \\
\midrule
    26.09.2016  &   4   &   1098,2  &   11,4    \\
    27.09.2016  &   1   &   329,8   &   13,5    \\
    28.09.2016  &   1   &   288,4   &   11,8    \\
    29.09.2016  &   1   &   291,7   &   11,9    \\
    \midrule
    \rowstyle{\bfseries}
    Average         &       &       &   12,2    \\
    \bottomrule
\end{tabular}
\end{document}


Q:

Increment Integer by one

When creating messages in C# I've done something similar to this.
            ByteMessage[i] = "A"
            ByteMessage[++i] = "B"
            ByteMessage[++i] = "C"
            ......................

I would like to accomplish this in VB.NET, except VB.NET does not support the ++ or -- operators. I've tried things like
            ByteMessage(i += 1) = "A"
            ByteMessage(i += 1) = "B"
            ByteMessage(i += 1) = "C"
            ......................

But this doesn't seem to work.  The MATH library didn't seem to have anything in it either for use.
Is there any clean solution for this in VB.NET like there is for C#?

A:

There is nothing inherent in .Net that supports pre/post increment and return functionality.  The C# compiler supports its by emitting the required IL statements when it compiles the code.  While VB.Net language developers did not deem this feature necessary, there is nothing that prevents you from using Extension Methods to add this functionality.
The only limitation is that you need to use valid method name (for example IncrPre or IncrPost) for the extension method and use method notation instead of the ++i or i++ notation.
Public Module Int32Extensions
    <Extension()>
    Public Function IncrPost(ByRef i As Int32) As Int32
        Dim ret As Int32 = i
        i += 1
        Return ret
    End Function

    <Extension()>
    Public Function IncrPre(ByRef i As Int32) As Int32
        i += 1
        Return i
    End Function
End Module

Example usage:
Dim i As Int32 = 0
Dim ByteMessage As String() = New String(0 To 4) {}
ByteMessage(i) = "A"
ByteMessage(i.IncrPre) = "B"
ByteMessage(i.IncrPre) = "C"
i = 3
ByteMessage(i.IncrPost) = "D"
ByteMessage(i) = "E"

yields:


Q:

A difference between Unicode and ASCII operators

I found out that Unicode and ASCII operators sometimes work differently when  quote-interpolated.
Consider this:
$ perl6 -e'my $a = BagHash.new: <a a a a b b b c c c c c d>;for $a.keys -> $k { say "$k => $a<<$k>>" }'

d => 1
b => 3
c => 5
a => 4

and this:
$ perl6 -e'my $a = BagHash.new: <a a a a b b b c c c c c d>;for $a.keys -> $k { say "$k => $a«$k»" }'

c => c(5) a(4) b(3) d«c»
a => c(5) a(4) b(3) d«a»
b => c(5) a(4) b(3) d«b»
d => c(5) a(4) b(3) d«d»

But this works even when using an Unicode operator:
$ perl6 -e'my $a = BagHash.new: <a a a a b b b c c c c c d>;for $a.keys -> $k { say "$k => {$a«$k»}" }'
d => 1
b => 3
a => 4
c => 5

Is this a bug, or there's an explanation I can't see?

A:

Seems to be fixed with commit 2835  from MasterDuke17:
  sub bracket_ending($matches) {
      my $check     := $matches[+$matches - 1];
      my str $str   := $check.Str;
      my $last  := nqp::substr($str, nqp::chars($check) - 1, 1);
-     $last eq ')' || $last eq '}' || $last eq ']' || $last eq '>'
+     $last eq ')' || $last eq '}' || $last eq ']' || $last eq '>' || $last eq '»'
  }


Q:

How to prevent browser from refilling form data when navigating back

I have a php form that submits data to a database. When the form has been successfully filled out and the data submitted, the form clears because of the page refresh. When the user hits the back button on the browser, the data comes back.
Is there a php function that will prevent the caching of this data?

A:

autocomplete="off" in the input fields of your forms?

A:

There isn't a reliable method, because the behaviour on back varies between browsers. Moreover, if someone has gone back through history, and you change what's happening, you are changing history. The metaphysical "woah!" of that aside, it's not a great idea.
What problem does this cause, apart from issues of from-resubmission? If form-resubmission is a problem then you need to deal with it in the case of a quick double-click on submit too anwyay. Include a hidden nonce value (UUIDs are good), store the nonce with your record of whatever it is the form does, and reject repeated nonces.


Q:

"no snap ins have been registered for powershell 4"

I have a Windows Server 2012 R2 Standard enabled with ADFS. I can open and use ADFS Management console. I am not sure which version of ADFS is installed on the server. As per Microsoft blogs Windows Server 2012 R2 comes with ADFS 2.0. I donot know how to confirm this.
Now I need to skew the ADFS clock by 2 minutes using the powershell ADFS snapin.
But when I try giving "get-pssnapin -registered" It doesnot list ADFS server.
Can anyone help me on how to execute the below commands on powershell:
Add-PSSnapin Microsoft.Adfs.PowerShell
Get-ADFSRelyingPartyTrust –identifier “urn:party:sso” | Set –NotBeforeSkew 2

Below is the error that I am getting:
PS C:\Users\manasa.pandiri> add-pssnapin microsoft.adfs.powershell
add-pssnapin : No snap-ins have been registered for Windows PowerShell version 4.
At line:1 char:1
+ add-pssnapin microsoft.adfs.powershell
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidArgument: (microsoft.adfs.powershell:String) [Add-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand

A:

We also encountered this issue.  Did a get-module -listavaiable and found that ADFS v1 was present.  Next did a get-command -noun "ADFS" and it returned all the ADFS cmdlets.  From there we issues the Set-ADFSRelyingPartTrust and was able to get the notBeforeShew set.


Q:

Photoelectric effect:- Reduction of wavelength increases current?

I did a question in which, the intensity of the incident radiation on a metal surface was kept constant but the wavelength of the photons has been reduced. The question inquired what will be the effect on the maximum photoelectric current? The initial wavelength was smaller than threshold wavelength of the metal surface.
My thinking was since the intensity remains constant, thus the number of photons emitted from the source remains constant and thus the number of electrons emitted from the metal surface. And since number of electrons per unit time isn't changed, the current will remain the same.
However, the answer key stated "Fewer photons (per unit time) so (maximum) current is smaller"
How does decreasing wavelength (equivalent to increasing the energy of photons) result in a fewer photon emission?

A:

It is the interface between classical electrodynamics and quantum mechanics.
Intensity is a classical electromagnetic wave measure of energy, measured by the  average electric field in the wave :

the average intensity for a plane wave can be written

So for a given value of intensity/energy  for a classical wave of frequency $\nu$, there are $N$ number of photons with energy $E=h\nu$. If the intensity is constant and the frequency gets larger , fewer photons are needed to add up to the classical intensity .


Q:

How do I detect when a telnet client is improperly closed to a tcp server?

I am experimenting in creating a small IRC server to learn some new programming concepts (and others I haven't used in forever).  The first step is to get a basic client connecting via TCP to send plaintext commands to the server.
To listen for connection I have the following code:
public NetworkClient(Server server, TcpClient socket, int id)
{
    _socket = socket;
    _id = id;
    _server = server;
}

private async void ListenForClients()
{
    int numClients = 0;
    while (IsRunning)
    {
        var tcpClient = await _listener.AcceptTcpClientAsync();
        var netClient = new NetworkClient(this, tcpClient, numClients);
        netClient.Start();
        Console.WriteLine("Client Connected");

        numClients++;
    }
}

Then in my NetworkClient class my Start() method looks like:
public async void Start()
{
    using (var reader = new StreamReader(_socket.GetStream()))
    {
        while (_server.IsRunning)
        {
            var line = await reader.ReadLineAsync();
            Console.WriteLine("Client {0} wrote: {1}", _id, line);
        }
    }
}

This works well while a telnet client is connected, however once I close my telnet client reader.ReadLineAsync(); constantly returns null.  I would add a check to see if line == null but I'm not sure that is the correct way to detect if a client has disconnected.
To make matters worse, _socket.Connected is constantly returning true all while nulls are getting "received" by reader.ReadLineAsync().
What is the proper way to detect when tcp clients have been disconnected?

A:

A read on a TCP/IP socket will return 0 bytes when the connection has been gracefully closed. This situation causes ReadLineAsync to return null. So, yes, you should check for null and treat it as a graceful socket closure.
Sockets may be closed other ways, too; any socket operation may throw an exception if the socket is abortively closed. If the exception happens at an acceptable part of the protocol (where a close is not considered an error), then you should treat that exception as though it were a graceful closure as well.
Oh, and TcpClient.Connected (like Socket.Connected) is practically useless; it only tells you whether the socket was connected, not whether it is connected. Just pretend that property doesn't exist.
Finally, a couple of notes:

Avoid async void. If your methods return Task, then you have a "handle" to see when they complete (and whether they raised exceptions). My recent MSDN article explains why async void is not recommended.
It's best to periodically send data over the connection to determine if it is still viable. I wrote a TCP/IP .NET sockets FAQ that covers this in more detail.


Q:

How to handle interpersonal issues with my supervisor at work?

I have been working at my job for over a year now and I have some minor but extremely annoying interpersonal issues with my boss. He's British and I'm Canadian but we are living in Ireland. I'm a software developer. I think it comes down to having different temperaments and lifestyles.
For example, I am 28 weeks pregnant. During this pregnancy I have been really struggling with sleep disturbances. I tend to wake up at 2AM or 4AM and cannot get back to sleep. I am also a little overweight so the extra weight is really wearing on me now. I'm also hormonal and more irritable than usual and a little stressed about this big life-changing event that will happen in 12 weeks.
My boss likes to do some 'niceties' before diving into talking about work. I don't really enjoy this because I have to lie to him to have a smooth conversation. For example, he asks me how I am. I tell him the truth: I am struggling or I am really tired. He doesn't respond well to this or he said things that I consider to be kind of sexist such as 'oh, it's normally not a problem.' A man telling a woman how pregnancy normally feels doesn't sit well with me or else he doesn't like to hear that I am tired etc. He also didn't want me to work at home even though I am struggling.
I have to lie to him to get through these conversations. If I say 'fine/good, how are you?' it gets this conversation over with but it's incredibly boring and repetitive to have to do this everyday for 5 days a week. I'd rather just jump into saying stuff like 'hey, did you see that email?' or 'hey, did you see that new ticket? What's the priority for the day?'
I also get sick of the routine of a 9-5 job + 1hr 15 mins commute at times and I'm not always thrilled about coming into work but I don't hate my job. My boss has repeatedly said that his children drive him insane and he'd rather be at work than at home. I don't always find my work to be interesting.
Other people don't seem to have an issue with me being honest about being tired. Do you have any suggestions about this situation?

A:

Lying in answer to platitudes is normal. It's always best in a work environment to put your best face forwards and appear positive.
So if you don't want to create a drama about your situation, just say 'I'm fine thanks' like everyone else.
I've been proactively keeping a positive outward expression for so long that it has actually made my whole outlook much more positive. So it's something worth cultivating.

A:

It's a false dichotomy that you must either lie or endure patronizing or normative comments from your boss. Try acknowledging your difficulties, emphasizing that you are coping with them, and seguing to whatever you are planning to do or discuss. Examples:

How are you?
I've been more comfortable, but I don't want to complain. My work still needs to get done, and I'm raring to tackle today's priorities. What's top of the list?

or

How are you?
A little better than yesterday, thanks. Getting a bit of my energy back. Just the ticket for tackling tickets -- did you see that one about the reports?

So something positive that's not a lie of "fine thanks" and that both acknowledges you are working through difficulties and puts a positive tone to it instead of complaining. Then straight into the work.
Now, it's possible your boss also wants you to ask about him. In that case try something like:

How are you?
I've been more comfortable, but I don't want to complain. How about you?
I'm fine, thanks.

If the boss then moves into the actual topic, great, but if he kind of sits quiet after answering, you can pick it back up:

The work still needs to get done, of course, and I'm raring to tackle today's priorities. What's top of the list?

If you really truly need to work from home sometimes because of how tired you are, that's a conversation of its own and not a response to a scriptlike "how are you today?" question. In that conversation you present your problem and your proposed solution to it, and you brush aside any suggestions of what pregnancies are normally like with "well, that's not the experience I am having with this one." But that's a separate thing.


Q:

Calling fancybox via ajax - where to put options?

I'm calling a fancybox-site-preview via ajax and don't know where to put further fancybox options.
$.ajax({
    type    : "POST",
    cache   : false,
    url     : "../mysite/",
    data    : $('#myform').serializeArray(),
    success : function(data) {
        $.fancybox(data);
        }
    });

I'd like to add width: '100%', height: '100%',
I tried it with various positions in, before, and after the $.fancybox(data); but I didn't get it to work.

A:

I can answer and solve my own questions: All the solutions seem to work, but you have to define minWidth and minHeight. It doesn't work with width and height.


Q:

Stop a loop while xpath = no such element

I am trying to stop a while loop when an xpath is not displayed. However, the code stop with a NoSuchElementExceptionmessage instead.  Here is my code,
 n=1
    while n<100:

        n+=1
        time.sleep(10)

#

        Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()

        if Data == True:

           ...

       if Data == False:
           break

But I obtain:

"NoSuchElementException: Message: no such element: Unable to locate
  element:
  {"method":"xpath","selector":".//tbody//tr//td//span//a[text() !=
  ""]"}"

And this is exactly when I want to stop the loop... when the element is not locatable.

A:

Use a try block and import the exception from selenium.
from selenium.common.exceptions import NoSuchElementException

...

while n<100:

   ...

   try:
        Data=driver.find_element_by_xpath('.//tbody//tr//td//span//a[text() != ""]').is_displayed()
   except NoSuchElementException:
        break

   ... rest of code ...


Q:

Non-Constant Partitioning of a List with Order Analysis

Let's say I have a set of numbers "r" whose sum equals 15, and I want to randomize all values up to and including that sum from and including 1 into a set called "a". So far I have this:
r = {4,5,6}
ord = Range[15]
a = RandomSample[ord]

And though for everyone the evaluation would yield a randomly different answer each time, for me the answer was:
{4,5,6}
{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
{13,2,8,15,7,12,14,3,11,1,6,5,9,4,10}

Now, half of the challenge I'm stuck on is how to Partition "a" (the last line of the output above) in the consecutive amounts of the set "r" ({4,5,6}), such that the output next would look like:
{{13,2,8,15},{7,12,4,3,11},{1,6,5,9,4,10}} // Lengths 4,5,6 respectively

Lastly I want the Ordering function applied to each of these subsets in one fell stroke, so that the final output derived from the above line would be:
{{2,3,1,4},{4,3,1,5,2},{1,5,3,2,4,6}}

Of course the answer would look different depending on what random sample was generated, but I need the logic to be consistent with what's here outlined.
Thanks!

A:

SeedRandom[1]
r = {4, 5, 6};
ord = Range[15];
a = RandomSample[ord]

{14, 2, 5, 1, 8, 12, 10, 13, 15, 11, 9, 4, 7, 6, 3}

b = Internal`PartitionRagged[a, r]

or, if you have version 10 or a newer version
b = FoldPairList[TakeDrop,a,r]

both give

{{14, 2, 5, 1}, {8, 12, 10, 13, 15}, {11, 9, 4, 7, 6, 3}}

And
Ordering /@ b

{{4, 2, 3, 1}, {1, 3, 2, 4, 5}, {6, 3, 5, 4, 2, 1}}


Q:

Postgis st_intersects fails on an obtained point on the line with the line itself

I am trying to split a line from its intersection with another line. I know I can use st_split directly here but I wish to split a line from several positions where it intersects other lines. What I discover is the following:
I know that lines 1 and 31 intersect
select st_intersects(a.geom,b.geom) from dumped_roads as a,
       dumped_roads as b where a.gid=1 and b.gid=31;

Output:
st_intersects
---------------
t
(1 row)

Also, st_intersection(a.geom,b.geom) returns an intersection point.
But when I do,
select st_intersects(a.geom, st_intersection(a.geom,b.geom))
from
  dumped_roads as a,dumped_roads as b where a.gid=1 and b.gid=31;

st_intersects
---------------
f
(1 row)

I can't understand what the problem is. Although a.geom && st_intersection(a.geom,b.geom) returns true but that wouldn't help me in splitting the line with the point obtained from intersection.
If it is indeed how it is, is there any way out on breaking a line from an obtained point which physically lies on the line, but is not in the linestrings point set?

A:

This is a robustness issue. ST_Intersection creates a new point that is probably not a vertex from either of the original LineStrings, but it probably is close to the line. A more robust test of intersection is to check if the distance is zero.
SELECT ST_AsText(ST_Intersection(a.geom, b.geom)),
       ST_Intersects(a.geom, ST_Intersection(a.geom, b.geom)),
       ST_Distance(a.geom, ST_Intersection(a.geom, b.geom))
FROM (select 'LINESTRING (156 258, 607 488)'::geometry as geom) as a,
     (select 'LINESTRING (105 418, 737 218)'::geometry as geom) as b;

-[ RECORD 1 ]-+-----------------------------------------
st_astext     | POINT(330.074206147054 346.773985396502)
st_intersects | f
st_distance   | 0

A:

Ok, so I have been able to work out the task of splitting a line from its intersection with other lines. There is indeed a robustness issue with postgis in which the intersection point of two lines doesnt lie on either of the lines sometimes even though the distance of the intersection point from the line is 0.
So I used st_line_locate_point to locate the point on the line closest to the intersection point (which is the intersection point itself since its distance is 0 from the line), and then I used st_line_substring to split the line.
I can explain it here using an example:
Suppose I want to split line joining (0,0) and (10,10) from its intersection with the line joining (0,10) and (10,0), I write the following query:
    select ST_ASTEXT(
      st_line_substring( st_geomfromtext('LINESTRING(0 0, 10 10)'),0,
         st_line_locate_point( st_geomfromtext('LINESTRING(0 0, 10 10)'),
            st_intersection(
              st_geomfromtext('LINESTRING(0 0, 10 10)'), st_geomfromtext('LINESTRING(0 10, 10 0)')
                       )
                   )
                )
      );

The output is correctly:
    st_astext
    ---------------------
    LINESTRING(0 0,5 5)
    (1 row)


Q:

Can I protect range 2 or 3 cell at once?

https://i.stack.imgur.com/7LagU.png
I have try to search a way but don't quite sure keyword to search about this problem. Is there a way to named cell to do this?

A:

Issue:
Protections only work for a Sheet or for a Range, not for a list of ranges. Because of this, you cannot protect them both at once. See Protect, hide, and edit sheets.
Workaround:
If you are open to using Apps Script, though, you could have a script that would protect both ranges:
var sheet = SpreadsheetApp.getActiveSheet();
var range1 = sheet.getRange("E3:F3");
var protection1 = range1.protect();
var range2 = sheet.getRange("H3");
var protection2 = range2.protect();
var protections = [protection1, protection2];
protections.forEach(protection => {
  var me = Session.getEffectiveUser();
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
});

Reference:

Protect, hide, and edit sheets


Q:

Registering Patterns in an Array

I have a simple array.
array(97) { [0]=> int(1) [1]=> int(0) [2]=> int(1) [3]=> int(1) [4]=> int(1) [5]=> int(1) [6]=> int(0) [7]=> int(1) [8]=> int(1) [9]=> int(1) [10]=> int(0) [11]=> int(0) [12]=> int(1) [13]=> int(0) [14]=> int(0) [15]=> int(0) [16]=> int(1) [17]=> int(0) [18]=> int(1) [19]=> int(1) [20]=> int(1) [21]=> int(1) [22]=> int(0) [23]=> int(0) [24]=> int(0) [25]=> int(1) [26]=> int(1) [27]=> int(1) [28]=> int(1) [29]=> int(1) [30]=> int(1) [31]=> int(1) [32]=> int(1) [33]=> int(1) [34]=> int(0) [35]=> int(1) [36]=> int(1) [37]=> int(0) [38]=> int(0) [39]=> int(1) [40]=> int(0) [41]=> int(1) [42]=> int(0) [43]=> int(1) [44]=> int(1) [45]=> int(1) [46]=> int(1) [47]=> int(1) [48]=> int(1) [49]=> int(1) [50]=> int(1) [51]=> int(1) [52]=> int(1) [53]=> int(1) [54]=> int(1) [55]=> int(0) [56]=> int(1) [57]=> int(0) [58]=> int(1) [59]=> int(0) [60]=> int(1) [61]=> int(0) [62]=> int(1) [63]=> int(1) [64]=> int(0) [65]=> int(0) [66]=> int(0) [67]=> int(0) [68]=> int(1) [69]=> int(1) [70]=> int(0) [71]=> int(0) [72]=> int(0) [73]=> int(0) [74]=> int(0) [75]=> int(0) [76]=> int(0) [77]=> int(1) [78]=> int(0) [79]=> int(1) [80]=> int(0) [81]=> int(1) [82]=> int(0) [83]=> int(0) [84]=> int(0) [85]=> int(0) [86]=> int(1) [87]=> int(0) [88]=> int(1) [89]=> int(0) [90]=> int(1) [91]=> int(0) [92]=> int(0) [93]=> int(1) [94]=> int(1) [95]=> int(1) [96]=> int(1) }

Is there a way that we can parse this and return true if it sees a 1 0 1 0 1 0 next to each other?

A:

It's definitely not the most mathematically elegant option, but a simple solution is to use implode and strpos:
if (strpos(implode('', $array), '101010') !== false) {
  echo 'Yes!';
}


Q:

Instantiate mongoid subclasses by _type field

From the Mongoid docs I see that if I have the following:
class Base
  include Mongoid::Document
end
class InheritedA < Base
end
class InheritedB < Base
end

I can do the following, which will get stored with the "_type" attribute.
a = InheritedA.new
a.save

Mongoid will create the following document.
{ _type: "InheritedA" }

My problem is that later on I have a function which has only the String _type value and I wish to instantiate the proper type. I have tried this:
Base.new({ _type: mytype });

However, Mongoid thinks this is a dynamic attribute and rejects it. I know turning on dynamic attributes is not the proper course because I don't want to allow that behavior in the general case.
I want to avoid having to do something like this:
ob = nil
if mytype == "InheritedA"
  ob = InheritedA.new
elsif
    ...

Does anyone know the proper method for accomplishing this?

A:

There are two ways you can tackle this. First one creates a base class document and then converts it into a subclass document. Using this method you would only be able to initialize based on fields defined in base class:
# attributes = {base_key1: value1, base_key2: value2}
Base.new(attributes).becomes(mytype.constantize)

Second one creates a document of subclass directly and you can initialize any fields for subclass:
# attributes = {base_key1: value1, base_key2: value2, sub_key3: value3}
Mongoid::Factory.build(mytype.constantize, attributes)


Q:

cakephp 3 original data in afterSave

Is there any way to access original data in afterSave?
I would like to log the changes on important data.
With $entity->isNew() I could check if it was an insert or an update, but how can I get what changed?

A:

You can access the original values via Entity::getOriginal() or Entity::extractOriginal(). If you want to get all changed fields, combine the latter one with Entity::visibleProperties(), something like:
debug($entity->extractOriginal($entity->visibleProperties()));

This should return the original values of all changed fields.
See also

http://api.cakephp.org/3.0/class-Cake.Datasource.EntityTrait.html#_extractOriginal
http://api.cakephp.org/3.0/class-Cake.Datasource.EntityTrait.html#_getOriginal
http://api.cakephp.org/3.0/class-Cake.Datasource.EntityInterface.html#_visibleProperties

A:

As of CakePHP 3.0.4, you can either use Entity::extractOriginal(), which will return the original value of any field, whether it has changed or not, or use Entity::extractOriginalChanged(), which will only return changed fields.
With this update, to reproduce the behaviour described in the accepted answer, you will thus need something like:
public function afterSave(Event $event, Entity $entity, $options)
{
    debug($entity->extractOriginalChanged($entity->visibleProperties()));
}

See CakePHP 3.0.4 Release Notes, stating:

EntityTrait::extractOriginal() now behaves consistently with extract(). Both methods now include all named properties [...] A new method extractOriginalChanged() can be used to extract only the original values of changed attributes.


Q:

How can I find ratio between area of triangle and area of quadrilateral?

I have a parallelogram $ABCD$. $E$ is center of $AD$. $O$ is center of $AC$ and center of $DB$. $F$ is the intersection point between $CE$ and $DO$. Point $G$ is the intersection between $EO$ and $AF$. $H$ is the middle of $DC$.
I put variables to different lines in the figure to show the ratios I found.
I need to find the ratio
$$Area_{AEG} : Area_{AEFO}$$

I don't have an idea on how to find it. I know how to find ratios like for example $$Area_{AEG} : Area_{ADH}$$ because they are similar triangles.

A:

If $H$ is the intersection between $AF$ and $CD$, then $GF=(1/2)FH$ so that $GF=(1/3)GH$, that is: $GF=(1/3)AG$. If $AM$ and $FN$ are the altitudes of triangles $AEO$ and $FEO$ with respect to $EO$ as common base, then $AGM$ and $FGN$ are similar triangle and $FN=(1/3)AM$. It follows that
$Area_{EOF}={1\over3}Area_{EOA}$.
On the other hand triangles $AEG$ and $AOG$ have equal bases $EG$ and $OG$, and share the same altitude $AM$. It follows that $Area_{AEG}=Area_{AOG}$, that is: $Area_{AEG}={1\over2}Area_{EOA}$.
In the end we have:
$$
Area_{AEFO}=Area_{EOF}+Area_{EOA}={1\over3}Area_{EOA}+Area_{EOA}={4\over3}Area_{EOA}
$$
and
$$
Area_{AEG}={1\over2}Area_{EOA},
$$
so that
$$
{Area_{AEG}\over Area_{AEFO}}=
{(1/2)Area_{EOA}\over(4/3)Area_{EOA}}={3\over8}.
$$


Q:

Andriod 10 How to check file exist

In Android Q, save pictures in app-specific directory,
path like = /data/user/0/xxx.xxx.xxx/files/phone/abc.jpg

not save in the external storage, use Device FileExplorer to view,
need to check if file exist, avoid to download again
,but in Android Q file.exist() not work
File newFile = new File(path);
newFile.exists();

always return false
this question. I need to use MediaStore or SAF to resolver it.
or other function to check it.
If I use MediaStore to check. use ContentResolver. May be like this:
public void getPhotoCursor(Uri uri) {
  Cursor cursor = getContentResolver().query(uri, null, null, null, null, null);
  try {
    if (cursor != null && cursor.moveToFirst()) {
        String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

    }
  } finally {
     cursor.close();
  }
}

But I can't get the Uri form app-specific directory. If I get the Uri, how to use file descriptor to check.
or use SAF to check.
 File testFile = new File(getExternalFilesDir()+"phone", "abc.jpg");
 FileProvider.getUriForFile(,,testFile);

 Intent testIntent = new Intent(Intent.ACTION_VIEW);
 testIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 testIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 testIntent.setDataAndType();
 startActivity(testIntent);

In the ActivityResult to check it
Any help will be apperciated

A:

is my fault, every time open APP I will delete all the .jpg from APP-specific.
so into APP I want to check avoid download again. file exist always return false.


Q:

Showing that a function is injective

I am trying to show that the following function is injective in some neighborhood of $(0, 0)$: $f:\mathbb R^2 \rightarrow \mathbb R^2$ given by
$$f(x, y)=(\sin(x^3)\cosh(y), \cos(x^3)\sinh(y))$$
I tried to use the inverse function theorem but $df(0, 0)$ is not invertible.

A:

Let $g(x,y)=(x^3,y)$ and $h(x,y)=(\sin x\cosh y,\cos x\sinh y)$, so $f=h\circ g$.
Then $g(0,0)=(0,0)$ and $g$ is invertible, and $h$ is locally invertible at $(0,0)$ since
$\displaystyle\frac{\partial(h_1,h_2)}{\partial(x,y)}=\cos^2x\cosh^2y+\sin^2x\sinh^2y=\cos^2x(\sinh^2y+1)+\sin^2x\sinh^2y=\sinh^2y+\cos^2x$,
so $\displaystyle\frac{\partial(h_1,h_2)}{\partial(x,y)}(0,0)=1\ne0$.
Therefore $f$ is locally invertible at $(0,0)$.


Q:

Twitter share button without the twitter icon, just the sharing

I want to embed the twitter share option and the code I get is the javascript as well as this link to share:
Tweet

I want the data text and all that to show BUT I want to use my own custom icon and not the twitter icon. So I took away the class="twitter-share-button" because that is what displays this button but once I do that then the data-text is lost and it just shares the link. How does one hack this to show a custom icon?
Your help = greatly appreciated

A:

Simplest way to do this is by not using their JavaScript at all, and simply building the share URL yourself:
http://twitter.com/share?text={…}&url={…}

Don’t forget to URL-encode parameter values you put in there properly.
You might want to add a target="_blank" to the link to open this in a new window/tab, or even add window.open to optionally open it in a popup with a predefined width and height.


Q:

How can I create a new tag, vsts, for Visual Studio Team Services?

How can I create a new tag, "vsts", for Visual Studio Team Services?
Tried to create, but got told "vst" already exists, and ask in Meta ...
... so here I am ...

A:

As people have explained in the comments, that tag might not be appropriate for Super User. If you were going to create it (and I would suggest based on those comments that you don't), you could deal with the length limit by partially abbreviating it, e.g. vs-team-services. The tag wiki excerpt would then clarify what exactly the tag is about, and people would likely associate Visual Studio with the phrase "team services", whereas I wouldn't immediately have a guess about vsts.
Also, the reason you're receiving that error message is that tags differing only in hyphenation or capitalization are no longer allowed. If I understand correctly, only moderators can create tags that would be blocked by that check (there are legitimate exceptions to the rule, like windows and window).