text:
Q: Retrofit2 GET request is returning some null Entries in List when attempting to retrieve a JSON Array JSON Data:
[
  {
    "ID": 47,
    "lat": 20.2,
    "lon": 18.04308,
    "alt": "100",
    "location": "Location 001",
    "meinOrt": "Ort1",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 50,
    "lon": 28.04308,
    "alt": "134.5",
    "location": "Location 002",
    "meinOrt": "Ort2",
    "meineBeschreibung": "wald2",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 49.07458166666667,
    "lon": 16.04308,
    "alt": "134.5",
    "location": "Location 003",
    "meinOrt": "Ort3",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 46.07458166666667,
    "lon": 33.04308,
    "alt": "134",
    "location": "Location 004",
    "meinOrt": "Ort4",
    "meineBeschreibung": "wald",
    "satNr": "0"
  },
  {
    "ID": 47,
    "lat": 45,
    "lon": 24.2,
    "alt": "134.5",
    "location": "Location 005",
    "meinOrt": "Ort5",
    "meineBeschreibung": "wald",
    "satNr": "0"
  }
]

Api Interface:
    @GET("get_entries.php")
    Call<List<Entries>> getEntries();

Entries.java
class Entries {

    private int id;
    private String latitude;
    private String longitude;
    private String location;
    private String altitude;
    private String meinOrt;
    private String meineBeschreibung;
    private String myDatetime;

    public Entries(int id, String latitude, String longitude, String location, String altitude, String meinOrt, String meineBeschreibung, String myDatetime) {
        this.id = id;
        this.latitude = latitude;
        this.longitude = longitude;
        this.location = location;
        this.altitude = altitude;
        this.meinOrt = meinOrt;
        this.meineBeschreibung = meineBeschreibung;
        this.myDatetime = myDatetime;
    }

    public int getID() {
        Log.d("DEBUG", "in getID = " + latitude );
        return id;
    }

    public String getlatitude() {
        return latitude;
    }

    public String getlongitude() {
        return longitude;
    }

    public String getlocation() {
        return location;
    }

    public String getaltitude() {
        return altitude;
    }

    public String getmeinOrt() {
        return meinOrt;
    }

    public String getmeineBeschreibung() {
        return meineBeschreibung;
    }

    public String getmyDatetime() {
        return myDatetime;
    }
}

Orte.java (were the call is made):
    private void getEntries() {

        textViewResult = findViewById(R.id.text_view_result);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://myBaseUrlexample.de/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
        Log.d("DEBUG", "--> API CREATE  = " + jsonPlaceHolderApi );

        Call<List<Entries>> call = jsonPlaceHolderApi.getEntries();
        Log.d("DEBUG", "--> create call  = " + call );

        call.enqueue(new Callback<List<Entries>>() {
            @Override
            public void onResponse(Call<List<Entries>> call, Response<List<Entries>> response) {
                Log.d("DEBUG", "--> on response  = " + call );
                if (!response.isSuccessful()) {
                    textViewResult.setText("Code: " + response.code());
                    return;
                }

                List<Entries> alleEintraege = response.body();

                Log.d("DEBUG", "--> API CREATE  = " + alleEintraege );

                for (Entries einzeleintrag : alleEintraege) {

                    String content = "";
                    content += "ID: " + einzeleintrag.getID() + "\n";
                    content += "Lat: " + einzeleintrag.getlatitude() + "\n";
                    content += "Lon: " + einzeleintrag.getlongitude() + "\n";
                    content += "Ort: " + einzeleintrag.getmeinOrt() + "\n";
                    //content += "Entfernung: " + distance + "\n";
                    content += "Location: " + einzeleintrag.getlocation() + "\n";
                    content += "Höhe: " + einzeleintrag.getmyDatetime() + "\n";
                    content += "Beschreibung: " + einzeleintrag.getmeineBeschreibung() + "\n\n";

                    textViewResult.append(content);
                }
            }

            @Override
            public void onFailure(Call<List<Entries>> call, Throwable t) {
                textViewResult.setText(t.getMessage());
            }
        });
    }

Logcat:

11-06 08:11:18.702 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> API CREATE  = retrofit2.Retrofit$1@25f1b684
11-06 08:11:18.713 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> create call  = retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@208d07a1
11-06 08:11:18.873 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> on response  = retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall@208d07a1
11-06 08:11:18.873 5803-5803/com.example.mikkigpsv4 D/DEBUG: --> API CREATE  = [com.example.mikkigpsv4.Entries@1cf2c6e4, com.example.mikkigpsv4.Entries@450574d, com.example.mikkigpsv4.Entries@235cd202, com.example.mikkigpsv4.Entries@60e3713, com.example.mikkigpsv4.Entries@14876d50]

Result in my mobile Phone:

ID: 0 Lat: null Lon: null Ort: Ort1 Location: Location001 Höhe: null
  Beschreibung: wald
ID: 0 Lat: null Lon: null Ort: Ort2 Location: Location002 Höhe: null
  Beschreibung: wald2
ID: 0 Lat: null Lon: null Ort: Ort3 Location: Location003 Höhe: null
  Beschreibung: wald
ID: 0 Lat: null Lon: null Ort: Ort4 Location: Location004 Höhe: null
  Beschreibung: wald
ID: 0 Lat: null Lon: null Ort: Ort5 Location: Location005 Höhe: null
  Beschreibung: waldschreibung: wald

So, some entries are responsed fine and some entries are only nulled, any help to get that entries coorrectly would be immensely appreciated, thank you.

A: Use Gson @SerializedName("") in your model to match key with json
@SerializedName("ID")
private int id;
@SerializedName("lat")
private String latitude;
@SerializedName("lon")
private String longitude;
@SerializedName("location")
private String location;
@SerializedName("alt")
private String altitude;
@SerializedName("meinOrt")
private String meinOrt;
@SerializedName("meineBeschreibung")
private String meineBeschreibung;
@SerializedName("satNr")
private String myDatetime;

A: Use jsonschema2pojo to generate your model which should be :
It should be "ID" not "id"
public class Example {

@SerializedName("ID")
@Expose
private Integer iD;
@SerializedName("lat")
@Expose
private Integer lat;
@SerializedName("lon")
@Expose
private Double lon;
@SerializedName("alt")
@Expose
private String alt;
@SerializedName("location")
@Expose
private String location;
@SerializedName("meinOrt")
@Expose
private String meinOrt;
@SerializedName("meineBeschreibung")
@Expose
private String meineBeschreibung;
@SerializedName("satNr")
@Expose
private String satNr;

public Integer getID() {
return iD;
}

public void setID(Integer iD) {
this.iD = iD;
}

public Integer getLat() {
return lat;
}

public void setLat(Integer lat) {
this.lat = lat;
}

public Double getLon() {
return lon;
}

public void setLon(Double lon) {
this.lon = lon;
}

public String getAlt() {
return alt;
}

public void setAlt(String alt) {
this.alt = alt;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getMeinOrt() {
return meinOrt;
}

public void setMeinOrt(String meinOrt) {
this.meinOrt = meinOrt;
}

public String getMeineBeschreibung() {
return meineBeschreibung;
}

public void setMeineBeschreibung(String meineBeschreibung) {
this.meineBeschreibung = meineBeschreibung;
}

public String getSatNr() {
return satNr;
}

public void setSatNr(String satNr) {
this.satNr = satNr;
}

}

A: The problem is Retrofit uses GsonConvertor to convert (JSON object to POJO) serialization. For that, you shud give the same name in a JSON object and in POJO object that you created.
As @Md.Asaduzzaman answer, you can use @SerializedName("---") or you can rename your POJO class member to match with JSON response.
i.e latitude to lat


text:
Q: Mapping a table column with values that persist on create and update in Rails I have a column in the table that has string values for:
arr = ["First Name", "Last Name", "location", "Description"]
I need to map each of these values to letters sequentially:
["A", "B", "C", "D"]
These letters aren't part of the table and aren't defined, but I am leaning toward creating a small hash with the above arr, unless there is a better suggestion?
I need to be able to map each letter to its correspond value in the arr, and when the arr is updated in a view, each letter should correspond in the arr. For example, if the "First Name" is removed from the arr, then the first latter should be "B", or if the "location" is removed, then the new array should be "A", "B", "D". Meaning, on create or update, letters should always be mapped to corresponding values in the arr. I hope I am making sense?
Many thanks.

A: For example  you have
arr = ["First Name", "Last Name", "location", "Description"]
arr_hash= Hash.new

and yout have a instance for
@client =Client.first

hash[0] = []
hash[0] << arr

hash[1] = []
hash[1] << @client

and more....

A: You can make hash with pairs first, and then remove keys that are not present in updated array.
arr = ["First Name", "Last Name", "location", "Description"]
arr2 = ["A", "B", "C", "D"]

result = Hash[arr.zip(arr2)]
# => {"First Name"=>"A", "Last Name"=>"B", "location"=>"C", "Description"=>"D"}

# update original arr like:
arr = ["Last Name", "location", "Description"]

result.delete_if { |k, _| !arr.include?(k) }
# => {"Last Name"=>"B", "location"=>"C", "Description"=>"D"}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Purpose of Reader Monad I am having difficulty in understanding the Reader Monad. My understanding from all the places I read, is that it allows to share a variable(Read Mode) to different function. Below is the implementation of two functions computation and samething (sorry for bad function names), one with Reader and one without it. I don't get the benefit using Reader.
module Moreunderstanding where
import Control.Monad.Reader

computation :: Reader Int Int

computation = do
  a <- ask
  b <- asks square
  return (a + b)

square :: Int -> Int
square x = x ^ 2

samething:: Int -> Int

samething = do
  a <- square
  b <- id
  return (a + b)

I am not sure what is that I am missing here.

A: These do both do the same thing.  In fact, the Reader monad is pretty much the same as the function monad (which you're using in samething).  It becomes useful because of the MonadReader typeclass (which (->) a has an instance for) and ReaderT, which allow you to stack multiple monad transformers on top of one another.
It's also a good statement of intent.  It means "I have a read-only value here that will be used in this computation".  I'd say that your intuition is pretty accurate though, there isn't much to the Reader monad, it's pretty simple.

A: The Reader monad becomes more useful when you have several arguments that you have to pass around from function to function. For example if you're building some API endpoints and you want to pass a configuration object around. In that case it's much easier to use the Reader monad and keep the inner functions signature clean.


text:
Q: Greet User by name using Javascript and query string I am trying to get the user's name from a form input and display it on the page in the form of a greeting "Hello (user)".
I have already got the solution to do it in 2 separate HTML files but I need to do it all in one file using query string and onload options.
Thanks for your help!
firstpage.html
<input type="text" id="titletxt">
  <button onclick="Submit()">Submit</button>

secondpage.html

  <title>Test</title>

A: Change your secondpage.html body to:

A: If I am correct in believing that you wanted all of the code to be in one file, I have a solution for you.
Solution with search params:
It simply checks if there is a search parameter called 'name' and if there is is replaces everything with Hello [name].

    <title>Hello</title>

    <input type="text" id="titletxt">
    <button onclick="Submit()">Submit</button>


text:
Q: MVC : Loading an array, depending of the selection client side of a drop down list I would like to do the following thing :
- Loading an array (meaning using EF to filter the result of a request) on my aspx page, depending of the selection, client-side, of my drop down list (containing the id to pass in parameter in my request result).
I suppose Ill have to pass by jquery or something Like that.
I have began to search a solution, like this. I'm not sure Im on the good way to find a solution.
I am quite begginer on MVC and Client side script, so I'm open to any other kind of solution, or any good tutorial, explaining the result of my question.

<% using (Html.BeginForm("Action", "Post")){%>

<%= Html.DropDownList("FK_MET_ID"); %>
<% } %>

(I used the following tutorial to start coding this part of code : http://www.dotnetcurry.com/ShowArticle.aspx?ID=443)

A: You are on the right way, you have to add some script to get it working. You need to pass in the selected value, you should add the controller code to the question. Maybe it's more a post than a get but it's out of the scope of this question. What is the datat you return? I think you should use jquery template to show your data.
$(function() {
           $("#FK_MET_ID").change(function() {
              $.get("/Provider/UpdateListProvider/" + $(this).val(), function(data) {

                if (data) {
                    $("#contractsTemplate").tmpl(data).appendTo('#contracts');
                }

                });
            });
        });

EDIT :
The best way is to work with Json, in youre controller you need a method like this one :
[HttpPost]
public virtual JsonResult GetContracts(string nameOfTheVariable)
        {
            var contracts = _session.All<Contract>();//add restriction with the variable
            return Json(contracts);
        }

In youre view you can work with jquery template :

You need to add a custom route in your global.ascx that will point to your controller with the action you want and the param nameOfTheVariable you need or can you can also do it as query parameter yoururl.com$action?nameOfTheVariable="value"
Let me know if you need more help!


text:
Q: Automatically append Query String from page request to outbound page request in ASp.NET WebForms I maintain a moderate sized public internet website for a company built using C# and ASP.Net WebForms using the .NET Framework 3.5.  One of our 3rd-party marketing/lead generation consultants wants to reserve several query string codes that go into Google Analytics for themselves and have those codes persist as the user moves around the website.  Since (for obvious reasons) I don't really want to have to touch every place we generate an internal URL link to maintain these codes, is there anywhere in the ASP.NET page lifecycle where I could intercept these (either when they are being written when the page is served or after the link is clicked) so I do not have to change the links generated on dozens of pages and hundreds of individual instances.
Thanks

A: If you're on IIS 7, look into outbound rules using the IIS URL Rewrite module - http://learn.iis.net/page.aspx/657/creating-outbound-rules-for-url-rewrite-module/.  They're extremely powerful.  You may be able to do this with older versions of IIS as well, but I've only worked with 7.
Adding the following rules to your web.config will cause all query string values in the request URL to be appended to the URLs in the hrefs of every anchor tag in the response.  The rules will apply to every page in your site.
<rewrite>
  <outboundRules>
    <rule name="Add request query string when there is an existing query string"
          patternSyntax="ECMAScript" stopProcessing="true">
      <match filterByTags="A" pattern="(.+)(\?)(.+)" />
      <conditions>
        <add input="{QUERY_STRING}" pattern=".+" />
      </conditions>
      <action type="Rewrite" value="{R:0}&{C:0}" />
    </rule>
    <rule name="Add request query string when there is a ? but no query string data"
          patternSyntax="ECMAScript" stopProcessing="true">
      <match filterByTags="A" pattern="(.+)(\?)$" />
      <conditions>
        <add input="{QUERY_STRING}" pattern=".+" />
      </conditions>
      <action type="Rewrite" value="{R:0}{C:0}" />
    </rule>
    <rule name="Add request query string when there is not an existing query string"
          patternSyntax="ECMAScript" stopProcessing="true">
      <match filterByTags="A" pattern="(.+)(\?){0}" />
      <conditions>
        <add input="{QUERY_STRING}" pattern=".+" />
      </conditions>
      <action type="Rewrite" value="{R:0}?{C:0}" />
    </rule>
  </outboundRules>
</rewrite>

A: You probably want to look at HTTP Modules.  There is a little bit of information in this KB article: http://support.microsoft.com/kb/307985.  You could catch the BeginRequest and possible modify the request or redirect the request.


text:
Q: Validation message error not working properly I'm having a problem with validation message errors for web forms. I need to get an error when both statements are true(both fields are empty). When I change statement && for || I'm able to get an error but that's not what I want.Thank you. Here is my C# code
protected void CustomValidatorForm_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (string.IsNullOrEmpty(drpState.Text) && string.IsNullOrEmpty(txtRegion.Text))
            args.IsValid = false;
        else
        {
            args.IsValid = true;
        }
    }

I'm Trying to run this code for my forms:
<asp:DropDownList ID="drpState"  runat="server" CausesValidation="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="IL">Illinois</asp:ListItem>
<asp:ListItem Value="IN">Indiana</asp:ListItem>
<asp:ListItem Value="IA">Iowa</asp:ListItem>
 </asp:DropDownList>
    <asp:TextBox ID="txtRegion" runat="server"></asp:TextBox>
    <asp:Button ID="btnSubmit" Text="Submit" runat="server"  />

        </div>
            <asp:CustomValidator ID="CustomValidatorList" runat="server"
                 ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
                 ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
                 ForeColor="Red"
                >

            </asp:CustomValidator>
            <asp:CustomValidator ID="CustomValidatorForm" runat="server"
                ControlToValidate ="txtRegion" OnServerValidate="CustomValidatorForm_ServerValidate"
                ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
                ForeColor="Red"

                >

            </asp:CustomValidator>

A: try using like this ,
<asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ErrorMessage="*" ControlToValidate="txtFrom" runat="server" Display="Dynamic" ForeColor="Red" />

Easy way to do this,
After you create a <asp:TextBox ID="txtFrom" runat="server"></asp:TextBox>
type <asp:RequiredFieldValidator and press Tab Button twice,
You can also give any ErrorMessage as well as define color of the ErrorMessage

A: It turns out I just needed to add this property ValidateEmptyText="True" and set it to true. This is how validator should look like:
<asp:CustomValidator ID="CustomValidatorList" runat="server"
     ControlToValidate ="drpState" OnServerValidate="CustomValidatorForm_ServerValidate"
     ErrorMessage="At least one of the field need to be filled out" Display="Dynamic"
     ForeColor="Red" ValidateEmptyText="True">
</asp:CustomValidator>


text:
Q: Need help with this specific use of "Should" "We will retain his rights should he wish to be moved elsewhere at a later date"
What are the rules with using "should" like that? should he wish to and so on.
Because it looks weird. but I know it's correct as it's not the first time I'm seeing "should" being used like that.
thank you


text:
Q: Sometimes a NA is returned when stuying the sd of clusters, sometimes none I have a serie of observations that I cluster using kmeans.
Then, I investigate the standard deviation (sd) inside each clusters and get the max.
If I run several time the same code, sometimes, a NA appears.
Reducing k_n (number of clusters) produce the same effect, increasing is worse; with/without na.rm=T doesn't change.
Can someone explain me what I'm doing wrong, please ?
The code:
k_n <-11
clusters=as.data.frame(kmeans(ex,k_n, nstart=50,iter.max = 15 )$cluster)
clusters<-cbind(clusters,ex)
temp<-sapply(1:k_n, function(k){temp=subset(clusters, clusters[,1]==k)
                                sd<-sd(temp[,2], na.rm = T)
                                return(sd)})
max(temp)
temp

Here are the results of three runs. As you can see, the third trial returns a NA, the two others don't.

And here are the data "ex":
1400 1400 2000 2000 2000 2001 1400 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1400 1400 1401 2000 2000 2000 2000 1401 1401 2000 2000 2000 2000 2000 2000 2000 2000  801 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1400 1400 2000 2000 2000 1400 1400 2000 2000 2000 1200 1600 1500 1960 1350 1900 1900 1900 1350 2000 2000 2000 2000 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 1900 1350 1900 1900 1350 1350 2000 2000 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1920 1350 1350 1900 1900 1900 1900 1900 1350 2000 2000 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 2000 1900 1350 1900 1900 1900 1900 1350 2000 2000 2000 2000 2000 2000 2000 2000 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1900 1901 2000 2000 2000 2000 1200 1200 1200 1200 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 2000 2000 2000 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1500 1500 1500 1500 2000 1350 1900 1900 1900 1350 2000 2000 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1500 1500 1400 1350 1350 1900 1900 1900 1350 2000 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1500 1500 1500 1500    0    0 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1500 1500 1500 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 1900 1900 1900 1900 1900 1900 1500 1500 1500 1400 1901 1901 1901 1901 2000 1350 1900 1900 1900 1350 1350 2000 2000 2000 2000 1500 1560 1900 1900 1900 1900 1900 1900 1400 2000 1350 1900 1900 1900 1350 2000 2000 2000 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1200 1200 1200 1200 1200 1200 1200 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1400 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1900 1500 1500 1500 1500 2000 1900 1900 1900 1900 1900 1900 1900 1900 2000 1350 1900 1900 1900 1350 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1900 1900 1350 1350 1350 1350 1350 1900 2000 1350 1900 1900 1900 1900 1900 1900 1350 1350 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1200 1200 1200 1200 1200 1200 1200 1200 1200 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1600 1900 1900  801 1400 1400 1400 1400 1901 1901 1900 1901 1901 1900 1901 1901 1901 1900 1900 1900 1900 1901 1900 1900 1901 1901 1900 1901 1901 1901 1350 1350 1350 1350 1350 1350 2000 2000 2000 2000 2000 2000 2000 2000 2000 1400 1400 1401 1401 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1100 1100 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 1800 2000 1800 1800 1400 1200 1400 1600 1800 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000 2000

A: You get NA for sd because there is only one member in the cluster.
Using your example:
set.seed(1)
clus = kmeans(ex,k_n, nstart=50,iter.max = 15 )

Using your code:
clusters=as.data.frame(clus$cluster)
clusters<-cbind(clusters,ex)
temp<-sapply(1:k_n, function(k){temp=subset(clusters, clusters[,1]==k)
                                sd<-sd(temp[,2], na.rm = T)
                                return(sd)})

> temp
 [1]  0.40191848  4.10391341  0.00000000  0.06097108  1.57499631 12.59800291
 [7]  0.00000000  0.00000000          NA  0.00000000  0.00000000

One of them is NA, and if you look at which cluster is giving you NA, this cluster has only one member:
clusters[clusters[,1]==which(is.na(temp)),]
   clus$cluster   ex
69            9 1960

If we look at your data:
table(ex)
ex
   0  801 1100 1200 1350 1400 1401 1500 1560 1600 1800 1900 1901 1920 1960 2000
   2    2    2  123   36   21    5   22    1   94    4  147   18    1    1  268
2001
   1

I think it's possible if you increase k, you might end up with one of the clusters having only 1 member which allows convergence.
One way I can suggest is to increase the number of starts:
STARTS = seq(50,500,by=50)
# we test over 50 reps, how many single clusters we get
n_equal_one = sapply(STARTS,function(S){
replicate(50,sum(kmeans(ex,k_n, nstart=S,iter.max = 15 )$size==1))
})

plot(STARTS,colMeans(n_equal_one),ylab="Average proportion of singleton cluster")

So if you try nstart = 400 or 500, you will avoid singleton (cluster with n=1), but if you data becomes more sparse, it might be unavoidable..
dput(ex)

c(1400, 1400, 2000, 2000, 2000, 2001, 1400, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1400, 1400, 1401,
2000, 2000, 2000, 2000, 1401, 1401, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 801, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 1400, 1400, 2000, 2000, 2000, 1400, 1400, 2000, 2000, 2000,
1200, 1600, 1500, 1960, 1350, 1900, 1900, 1900, 1350, 2000, 2000,
2000, 2000, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200,
1200, 2000, 2000, 2000, 2000, 2000, 2000, 1900, 1350, 1900, 1900,
1350, 1350, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1200, 1200,
1200, 1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1920, 1350, 1350,
1900, 1900, 1900, 1900, 1900, 1350, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 1200, 1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200,
1200, 1200, 1200, 1200, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
1900, 1350, 1900, 1900, 1900, 1900, 1350, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 1200, 1200, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200,
1200, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
1900, 1901, 2000, 2000, 2000, 2000, 1200, 1200, 1200, 1200, 1200,
1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200,
1200, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1900,
1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900,
1900, 1500, 1500, 1500, 1500, 2000, 1350, 1900, 1900, 1900, 1350,
2000, 2000, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900,
1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1500, 1500, 1400,
1350, 1350, 1900, 1900, 1900, 1350, 2000, 2000, 2000, 2000, 2000,
2000, 1200, 1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600,
1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 2000, 2000, 2000,
2000, 2000, 2000, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900,
1900, 1900, 1900, 1900, 1900, 1500, 1500, 1500, 1500, 0, 0, 1900,
1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900,
1900, 1900, 1500, 1500, 1500, 2000, 2000, 2000, 2000, 2000, 1200,
1200, 1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200,
2000, 2000, 2000, 2000, 2000, 1900, 1900, 1900, 1900, 1900, 1900,
1500, 1500, 1500, 1400, 1901, 1901, 1901, 1901, 2000, 1350, 1900,
1900, 1900, 1350, 1350, 2000, 2000, 2000, 2000, 1500, 1560, 1900,
1900, 1900, 1900, 1900, 1900, 1400, 2000, 1350, 1900, 1900, 1900,
1350, 2000, 2000, 2000, 1200, 1200, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1400, 1900,
1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900,
1900, 1900, 1900, 1900, 1900, 1900, 1500, 1500, 1500, 1500, 2000,
1900, 1900, 1900, 1900, 1900, 1900, 1900, 1900, 2000, 1350, 1900,
1900, 1900, 1350, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1200, 1600,
1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1900, 1900, 1350, 1350, 1350, 1350, 1350, 1900, 2000, 1350,
1900, 1900, 1900, 1900, 1900, 1900, 1350, 1350, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 1200, 1200, 1200, 1200,
1200, 1200, 1200, 1200, 1200, 1600, 1600, 1600, 1600, 1600, 1600,
1600, 1600, 1600, 1600, 1600, 1900, 1900, 801, 1400, 1400, 1400,
1400, 1901, 1901, 1900, 1901, 1901, 1900, 1901, 1901, 1901, 1900,
1900, 1900, 1900, 1901, 1900, 1900, 1901, 1901, 1900, 1901, 1901,
1901, 1350, 1350, 1350, 1350, 1350, 1350, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 1400, 1400, 1401, 1401, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 1100, 1100,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 1800, 2000, 1800, 1800, 1400, 1200, 1400,
1600, 1800, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000
)


text:
Q: Is there any Google Now API that we can integrate our own Apps into Now? How can I provide my information or cards of my App-Data to Google Now?
Is there any API that I can use?

A: Google Now API is only provided for who register their app with Google, it has been private. Google control which Cards will be shown on their Google Now App. So you need to contact with Google and register your app to get the Now API and then you can build your own Now Card.


text:
Q: gcloud Nodejs http 500 error cannot find server.js in workspace [more detailed repost] I am new to google cloud and so I deployed a Nodejs app using the tutorial. Everything worked just fine, here is my file structure (I didn't make the my-nodejs-service folder):
app.yaml
server.js
package.json

I deployed it, everything was fine. So then I tried to make it look like this:
mySite/
 server.js
 package.json
 app.yaml
 public/
  site contents

I just forked a github repo, deployed it, and it didn't work. By that I mean the site didn't load! I checked the logs, and here was what appeared:
Error: Cannot find module '/workspace/server.js'
 at Function.Module._resolveFilename (loader.js:880)
 at Function.Module._load (loader.js:725)
 at Function.executeUserEntryPoint (internal/modules/run_main.js:72)

"GET / HTTP/1.1" 500

listening on port 3000

It said it couldn't find the server.js file. Was it because I moved the code into the folder? I deployed it on the current working directory being the folder mySite.
package.json (Im only including the scripts part, it other stuff such as the dependencies):
{

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  }
}

Other things I tried:

*

*deploying with app.yaml at the end of the deployment command

*Using path.join()

*Deploying multiple times

Other info:
I checked the logs and I got this:
"GET / HTTP/1.1" 500 - - "Web browser agent info in here"

Another showed:
i This request caused a new process to be started for your application, and thus caused your  application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application.

And another log said:
!! Process was terminated because the request deadline was exceeded. Please ensure that your HTTP server is listening for requests on 0.0.0.0 and on the PORT environment variable. (Error code 123)

A: App Engine uses a set of conventions in order to be able to deploy and run code successfully. As you've seen, you can't necessarily take an arbitrary web server solution and deploy it successfully.
Please include more details about specific steps you take. For example, you say "I .. deployed it". It would be useful for you to include the command that you used and any immediate errors that were thrown to provide readers with more context when helping answer your question. It's unclear to me from which directory you attempted to deploy the mySite example but I assume from within mySite.
The first error Cannot find module '/workspace/server.js' results because App Engine builds your code using Cloud Build and Cloud Build (by default) puts your code into a /workspace directory on the build VM. It's not very user-friendly, but it was unable to find server.js and, because your package.json specifies node server.js, it needs it.
Another statement that gives me pause is listening on port 3000. I'm not very familiar with the Node.JS runtime but generally App Engine expects web server's to either listen on port :8080 or provide an environment variable that specifies the port, In your tutorial, this is explained: "process.env.PORT is not set, port 8080". That's probably (!?) another issue.
Lastly, you may (I think you probably don't) need to explicitly reference the public subdirectory (unsure) in order to ensure that it's available at runtime.


text:
Q: jackson serialization with recursive structure I have this java model serialized by jackson:
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="orderId")
public class ClonedOrder extends ResourceSupport implements Serializable{
    private long orderId;
    private ClonedOrder parent;
    private List<ClonedOrder> children = new ArrayList<>();

    @JsonProperty("root")
    public ClonedOrder root() {
        if (parent == null) {
            return this;
        } else {
            return parent.root();
        }
    }

When jackson serialize this tree the response is as following:
{
  "orderId": 163811134,
  "parent": {
    "orderId": 153684020,
    "parent": null,
    "children": [],
    "root": 153684020
  },
  "children": [
   {
     "orderId": 163811135,
     "parent": 163811134,
     "children": [],
     "root": 153684020
   },
  "root": 153684020
}

The problem is that the root node that is of type ClonedOrder is not serialized as a ClonedOrder (with parent, children and root) but only with the id as long type.
The problem is that I cannot use the same model for serialize and deserialize since the json changes from server to client.
Any idea how to achieve this goal?

A: You can use the two annotations @JsonManagedReference and @JsonBackReference to handle bi-directional references.
Take a look here

A: As you noticed before, with JsonIdentityInfo jackson just serialises the long orderId and it skips the standard java-object serialisation to avoid infinite nested objects (means stackoverflow).
I suggest to serialise all the data you need with a simpler data structure like the model you would use to store these data in a relational database. The model I am figuring out is this:
relations: [
    {"id": 163811134, "parent": 153684020},
    {"id": 163811135, "parent": 163811134},
    {"id": 153684020, "parent": null},
]

with this structure it is very simple to find what you needed using utility methods:
private class CloningRelations {
    List<CloningOrder> orders;

    public Long getRoot(){
        for (CloningOrder o : orders)
            if (o.getParent() != null)
                return o.getId();
        return null;
    }

    @JsonIgnore public List<Long> getChildrenOf(long id) {
        ArrayList<Long> list = new ArrayList<>();
        for (CloningOrder o : orders)
            if (o.getParent() == id)
                list.add(o.getId());
        return list;
    }

    @JsonIgnore public List<Long> getDescendantsOf(long id) {
        ArrayList<Long> list = new ArrayList<>();
        for (CloningOrder o : orders)
            if (o.getParent() == id) {
                list.add(o.getId());
                list.addAll(getDescendantsOf(o.getId()));
            }
        return list;
    }

    @JsonIgnore public Long getParentOf(long id) {
        for (CloningOrder o : orders)
            if (o.getId() == id)
                return o.getParent();
        return null;
    }

    @JsonIgnore public List<Long> getAncestorsOf(long id) {
        ArrayList<Long> list = new ArrayList<>();
        for (CloningOrder o : orders)
            if (o.getId() == id) {
                list.add(o.getParent()); //sorted too!
                list.addAll(getAncestorsOf(o.getParent()));
            }
        return list;
    }

    private class CloningOrder {
        long id;
        Long parent;

        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public Long getParent() {
            return parent;
        }

        public void setParent(Long parent) {
            this.parent = parent;
        }

    }
}


text:
Q: How to remove block from left or right panel in magento 2? I want to remove compare product and wish list block from left panel.
I don't want to change template. I am using 2columns-left.
in magento 1.x, We uses like following in layout file.
<cms_index_index>
   <reference name="left">
      <remove name="left.newsletter"/>
   </reference>
</cms_index_index>

What to do to remove block from magento 2.x?

A: In Magento 2, you can remove Compare products and Wishlist from sidebar blocks of Category Page through xml.
You can remove it by adding a default.xml file to your theme in: theme_dir/Magento_Catalog/layout/default.xml
And add below XML

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
 <body>
    <referenceBlock name="catalog.compare.sidebar" remove="true"/>
    <referenceBlock name="sidebar.additional" remove="true"/>
 </body>
</page>

A: The code works fine in Magento 2.1.1.
With little changes :
instead referenceBlock replace with referenceContainer
<referenceContainer name="block.name.wantoberemoved" remove="true"/>

A: You can create new deafult.xml in your custom module and write below code to remove recent order block from Left sidebar
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="../../../../../../../../htdocs/lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
    <body>
     <referenceContainer name="sidebar.additional">
         <referenceBlock name="catalog.compare.sidebar" remove="true"/>
         <referenceBlock name="wishlist_sidebar" remove="true"/>
     </referenceContainer>
    </body>
</page>

A: What worked for me, even via admin "Layout XML Update" field, was the code
<referenceContainer name="sidebar.additional" remove="true" />

A: A quick note for Enterprise users: you may need to remove the "multiple wishlist" block as well:
<referenceBlock name="multiple-wishlist_sidebar" remove="true" />

A: Its almost the very same way
<referenceBlock name="block.name.wantoberemoved" remove="true"/>

Remove compare products from sidebar
<referenceBlock name="catalog.compare.sidebar" remove="true" />

Remove Wishlist from sidebar
<referenceBlock name="wishlist_sidebar" remove="true" />


text:
Q: How to find record Id in service console? If I use Salesforce classic, I can find record Id in url. Is there any way to find record Id when I am in console?

A: Click on triangle in right upper corner and click 'Get link to share'.

A: Getting Id visually: bring up the URL-grabber using the triangle tab as MrKonyk says, or using the keyboard shortcut U (assuming that you've enabled keyboard shortcuts in your console app's configuration, and typed 'Esc' once to enable the shortcuts for yourself as user).
Getting Id for use in code: use the methods in the Salesforce Console Integration Toolkit such as getFocusedPrimaryTabObjectId()


text:
Q: How to fix this infinite loop bug for Level Order Traversal Problem (Binary Trees) Professor provided this code, but I keep getting an infinite loop. I also don't understand the auto keyword with ":" in for loops.
I can't seem to understand where the bug lies.
vector<int> levelOrder(TreeNode* root) {
    vector<int> res;
    if (root == NULL)
        return res;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty()) {
        int size = q.size();
        for (int i = 0; i < size; i++) {
            TreeNode* curr = q.front();
            q.pop();
            if (curr->left != NULL)
                q.push(curr->left);
            if (curr->right != NULL)
                q.push(curr->right);
            res.push_back(curr->data);
        }
    }
    return res;
}

...

int main () {
...
    vector<int> items = levelOrder(root);
    for (int item : items) {
        cout << item << " ";
    }
    cout << endl;
...
        return 0;
}

Infinite Loop

A: First, the classical way to do a level-order traversal is to use a queue, and your code is doing that.
However, instead of relying on the state of the queue to loop using the while(!q.empty()) condition, you have a totally unnecessary, and probably harmful inner for loop.  If you removed the inner loop, then the code should run correctly.
Example:
vector<int> levelOrder(TreeNode* root) {
    vector<int> res;
    if (!root)
        return res;
    queue<TreeNode*> q;
    q.push(root);
    while (!q.empty())
    {
        TreeNode* curr = q.front();
        q.pop();
        if (curr->left)
            q.push(curr->left);
        if (curr->right)
            q.push(curr->right);
        res.push_back(curr->data);
    }
    return res;
}


text:
Q: Trying to run a service using systemd after startup I have listed below the steps as I entered them. I cannot get the Pi (Raspbian GNU/Linux Buster (10)) to launch alarm.service after startup. When I log into the Pi and launch alarm.service manually from the GUI it works, as does the script it runs -- (The script is written to loop) Only problem is I can't get alarm.service to launch automatically without the GUI. Be great to have it launch last after all other services are up and running.
1. sudo nano /home/pi/alarm_service.py - (fyi: this script runs nicely when i launch it manually from command prompt after pi has booted and i am logged in)
2. sudo nano /etc/systemd/system/alarm.service

[Unit]
Description=Alarm Service
After=multi-user.target
Conflicts=getty@tty1.service
[Service]
Type=simple
ExecStart=/home/pi/alarm_service.py
StandardInput=tty-force
[Install]
WantedBy=multi-user.target

3. sudo chmod 644 /etc/systemd/system/alarm.service
4. sudo systemctl daemon-reload
5. sudo systemctl enable alarm.service
6. sudo systemctl start alarm.service

Error log:
alarm.service - Alarm service Loaded: loaded (/etc/systemd/system/alarm.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2021-05-14 18:57:24 AEST; 1min 18s ago Process: 501 ExecStart=/home/pi/alarm_service.py (code=exited, status=1/FAILURE) Main PID: 501 (code=exited, status=1/FAILURE)
May 14 18:57:24 raspberrypi alarm_service.py[501]: File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 10 May 14 18:57:24 raspberrypi alarm_service.py[501]: sock = self._create_socket_connection() May 14 18:57:24 raspberrypi alarm_service.py[501]: File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 35 May 14 18:57:24 raspberrypi alarm_service.py[501]: return socket.create_connection(addr, source_address=source, timeout=sel May 14 18:57:24 raspberrypi alarm_service.py[501]: File "/usr/lib/python2.7/socket.py", line 575, in create_connection May 14 18:57:24 raspberrypi alarm_service.py[501]: raise err May 14 18:57:24 raspberrypi alarm_service.py[501]: socket.error: [Errno 101] Network is unreachable May 14 18:57:24 raspberrypi systemd[1]: alarm.service: Main process exited, code=exited, status=1/FAILURE May 14 18:57:24 raspberrypi systemd[1]: alarm.service: Failed with result 'exit-code'. May 14 18:57:24 raspberrypi systemd[1]: Failed to start Alarm service.

A: The principle I follow is to make the environment that systemd creates for the script to run as similar to what I use to develop it as possible.
For the sake of testing I just ran shutdown -r now on a VM where I do this exact thing. On boot, voila.
$ systemctl status mypython
● mypython.service
   Loaded: ...etc.

The file I have set is
less /etc/systemd/system/multi-user.target.wants/mypython.service

Content
[Unit]
        Description=mypython

        [Service]
        WorkingDirectory=/home/me
        ExecStart=/usr/bin/python3 /home/me/mypython.py ./config.yaml
        Restart=always
        RestartSec=5
        User=me
        Group=me

        [Install]
        WantedBy=multi-user.target


text:
Q: Why does nom expect a &str when I pass a CompleteStr? The parser works as expected until I want to parse the h: digit which is always the last digit in the string and the compiler gives me
^ expected &str, found struct `nom::types::CompleteStr`

I assume it's because the parser is looking ahead. How do I stop that, or how can I signify it's done?
#[macro_use]
extern crate nom;

use nom::digit;
use nom::types::CompleteStr;
use std::str::FromStr;

#[derive(Debug, PartialEq)]
pub struct Order {
    pub l: u64,
    pub w: u64,
    pub h: u64,
}

named!(order_parser<CompleteStr, Order>,
    do_parse!(
        l: map_res!(digit, u64::from_str) >>
        tag!("x") >>
        w: map_res!(digit, u64::from_str) >>
        tag!("x") >>
        h: map_res!(digit, u64::from_str) >>
        (Order {l:  l, w: w, h: h })
    )
);

pub fn wrap_order(order: &str) -> Result<(CompleteStr, Order), nom::Err<&str>> {
    order_parser(order)
}

#[test]
fn test_order_parser() {
    assert_eq!(
        wrap_order(CompleteStr("2x3x4")),
        Ok((CompleteStr(""), Order { l: 2, w: 3, h: 4 }))
    );
}

A: The error is not on the last digit parser, it's on each of them (Rust 1.30.0 prints the error three times). That's because u64::from_str works on &str, not CompleteStr.
You can fix your parsers to use u64::from_str correctly this way:
do_parse!(
    l: map_res!(digit, |CompleteStr(s)| u64::from_str(s)) >>
    tag!("x") >>
    w: map_res!(digit, |CompleteStr(s)| u64::from_str(s)) >>
    tag!("x") >>
    h: map_res!(digit, |CompleteStr(s)| u64::from_str(s)) >>
    (Order { l: l, w: w, h: h })
)

There are also some unrelated error with the next function, which can be fixed by using the appropriate types in the signature:
pub fn wrap_order(order: &str) -> Result<(CompleteStr, Order), nom::Err<CompleteStr>> {
    order_parser(CompleteStr(order))
}


text:
Q: Zoom ImageView in UICollectionView inconsistent I have a UICollectionView with cells that are the size of the CollectionView itself, so paging is enabled and you swipe through similar to the basic Gallery app.
I want the images to be zoomable like on Instagram (snaps back on gesture end). I Implemented the Pinch and Pan gestures with the help of an article, and it does work.
But I am having a strange issue. The speed at which it zooms is very inconsistent, and it seems to get faster with every page I flip. So the first Page it zooms and pans pretty normally, the second it is much faster, and by the third it is ridiculous.
I'm very confused, since I had this exact code running on a paging ScrollView, and it worked flawlessly.
Here is the relevant code in the UICollectionViewCell.
func setup(){
    imageView.isUserInteractionEnabled = true

    let pinch = UIPinchGestureRecognizer(target: self, action:
#selector(pinch(sender:)))
    pinch.delegate = self
    imageView.addGestureRecognizer(pinch)

    let pan = UIPanGestureRecognizer(target: self, action:
#selector(pan(sender:)))
    pan.delegate = self
    imageView.addGestureRecognizer(pan)

    let tap = UITapGestureRecognizer(target: self, action:
#selector(handleTap))
    imageView.addGestureRecognizer(tap)

    imageView.clipsToBounds = false
}

 @objc func pan(sender: UIPanGestureRecognizer) {
    if(isZooming){
        if self.isZooming && sender.state == .began {
            self.originalImageCenter = sender.view?.center
        } else if self.isZooming && sender.state == .changed {
            let translation = sender.translation(in: self)
            if let view = sender.view {
                view.center = CGPoint(x:view.center.x +
                                      translation.x,
                                      y:view.center.y +
                                      translation.y)
            }
            sender.setTranslation(CGPoint.zero, in:
self.imageView.superview)
        }
    }else{
        print("blocked pan")
    }

}

@objc func pinch(sender:UIPinchGestureRecognizer) {
    NotificationCenter.default.post(name:
Notification.Name(rawValue: "disablePage"), object: nil)

    allowedToTap = false

    if sender.state == .began {
        let currentScale = self.imageView.frame.size.width /
self.imageView.bounds.size.width
        let newScale = currentScale*sender.scale
        if newScale > 1 {
            self.isZooming = true
        }
    } else if sender.state == .changed {
        guard let view = sender.view else {return}
        let pinchCenter = CGPoint(x: sender.location(in: view).x -
                                  view.bounds.midX,
                                  y: sender.location(in: view).y -
                                  view.bounds.midY)
        let transform = view.transform.translatedBy(x:
pinchCenter.x, y: pinchCenter.y)
            .scaledBy(x: sender.scale, y: sender.scale)
            .translatedBy(x: -pinchCenter.x, y: -pinchCenter.y)
        let currentScale = self.imageView.frame.size.width /
self.imageView.bounds.size.width
        var newScale = currentScale*sender.scale
        if newScale < 1 {
            newScale = 1
            let transform = CGAffineTransform(scaleX: newScale, y:
newScale)
            self.imageView.transform = transform
            sender.scale = 1
        }else {
            view.transform = transform
            sender.scale = 1
        }
    } else if sender.state == .ended || sender.state == .failed ||
 sender.state == .cancelled {
        guard let center = self.originalImageCenter else {return}
        UIView.animate(withDuration: 0.3, animations: {
            self.imageView.transform = CGAffineTransform.identity
            self.imageView.center = center
        }, completion: { _ in
            self.isZooming = false

            NotificationCenter.default.post(name:
Notification.Name(rawValue: "enablePage"), object: nil)
            self.allowedToTap = true

        })
    }
}

I hope someone with more of an idea of how this works can help me.

A: I found a solution, I ll leave it here in case someone has the same issue.
The problem was that the setup function was being called multiple times, therefore multiple identical GestureRecognizers were being added.
So I just added a quick check.
func setup(){
    imageView.isUserInteractionEnabled = true
    playPauseImageView.alpha = 0

    if(!gesturesAreAttached){
        gesturesAreAttached = true
        addZoom()
    }
    imageView.clipsToBounds = false
}

func addZoom(){
    print("adding Zoom")
    let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinch(sender:)))
    pinch.delegate = self
    imageView.addGestureRecognizer(pinch)

    let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(sender:)))
    pan.delegate = self
    imageView.addGestureRecognizer(pan)

    let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
    imageView.addGestureRecognizer(tap)

}


text:
Q: Paypal payment pro PayPal express order not sending confirmation email in Magento I have a very long standing issue with PayPal Payments Pro in magento. If a customer places an order using PayPal express they don't receive the order email. If a customer pays with card they get it with no problems.
I have spent a lot of time investigating this with no joy at all. I am wondering if other people have had the same issue and if anyone has managed to solve it. I am running magento community 1.9.2.
The IPN seems to be working properly, and there are no orders in the email que.
Any help would be gratefully appreciated.

A: I had the same problem and it was caused by magento core bug.
In my exception.log file I had the following error:
main.CRITICAL: Notice: Array to string conversion in /home/mywebsite/public_html/var/view_preprocessed/pub/static/vendor/magento/module-payment/view/frontend/templates/info/default.phtml on line 1

If you want to fix it, create your own version of file vendor/magento/module-payment/view/frontend/templates/info/default.pthml in your theme and change line:
<?= $block->escapeHtml($label) ?>

to:

    <?php
    $x = $block->getValueAsArray($value, true);
    if(is_array($x)){
        //print_r($x);
        foreach($x as $y){
            echo $y;
        }
    }else{
        echo $x;
    }
    ?>

It's a very basic fix but it worked on my case.


text:
Q: Need a secure way of granting access to xp_cmdshell Imagine the following scenario: I need to execute a stored procedure which, amongst other things, needs to EXECUTE xp_cmdshell to run a command-line script which executes a bulk insert (bcp) command to put data into another database.
I have three Windows user accounts on the server: MyAdmin, MyProxy and MyUser.
MyAdmin is db_owner of the database and has bulkadmin server role.
MyProxy is the account associated with xp_cmdshell via sp_xpcmdshell_proxy_account.
MyUser has EXECUTE permission on the stored procedure and nothing else.
If I login as SERVER\MyUser and execute the stored procedure, it fails with error "The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.
So I thought the answer was to grant EXECUTE on xp_cmdshell to MyProxy, but this didn't work either. I then granted EXECUTE on xp_cmdshell to MyAdmin and changed the definition of the stored procedure to WITH EXECUTE AS 'MyAdmin' and although xp_cmdshell is executed OK, the bulk insert fails.
What must I do to make this scenario work?
Update: was asked on StackOverflow.com (1440332), but got no answers - hoping for better result here

A: I seem to remember a BCP step in SSIS.  Could you create a SSIS package and run that?  You can run SSIS packages from .net.

A: I would have made this a comment instead of an 'answer' had I permissions to do so, but, why not use the BULK INSERT T-SQL command instead of xp_cmdshell to bcp?


text:
Q: How to pass parameters generated by a method to a Rust unit test? I'm trying to write a parametrized unit test in Rust, which will take parameters from a method. I know how to use rstest when parameters are hardcoded:
use rstest::rstest;

#[rstest]
#[case(42)]
#[case(256)]
fn my_test(#[case] x: i32) {
  assert!(x > 0)
}

However, I want something like this:
#[cases_from(my_provider)]
fn my_test(#[case] x: i32) {
  assert!(x > 0)
}

fn my_provider() -> Vec<i32> {
  [42, 256].to_vec()
}

Is is possible with rstest? If not, which library enables this?

A: It does not appear to be possible with rstest, though a similar feature has been asked for: Issue #39: Dynamic set of tests.  There is difficulty because the library is designed around generating individual test functions that are then ran and displayed separately by the standard cargo test harness. And to do that, the procedural macros at play need all the pieces. It is not implemented by a simple for-loop over the test cases.
If you simply desire a mechanism to use the same set of test cases for multiple tests, the developer has created the rstest-reuse crate which would be used like this:
#[template]
#[rstest]
#[case(2, 2)]
#[case(4/2, 2)]
fn two_simple_cases(#[case] a: u32, #[case] b: u32) {}

#[apply(two_simple_cases)]
fn it_works(a: u32, b: u32) {
    assert!(a == b);
}

#[apply(two_simple_cases)]
fn it_fail(a: u32, b: u32) {
    assert!(a != b);
}

If you're fine with a single test that loops over inputs (and therefore loses some visibility into which test failed and functionality to continue with other cases), then you can simply write that yourself:
#[test]
fn my_test() {
    fn my_test_inner(x: i32) {
        assert!(x > 0)
    }

    for x in my_provider() {
        my_test_inner(x);
    }
}

fn my_provider() -> Vec<i32> {
    [42, 256].to_vec()
}


text:
Q: "play is not recognized as an internal or external command" I am new to play framework. I added the path of the play folder in my environment variable - C:\play-2.1.2\play .
On console, when i go inside the play folder and run "play" command, it works but when i created a new application and ran play inside it, it showed me an error - "play is not recognized as an internal or external command" . Please help.

A: Changing it to C:\play-2.1.2\ should work (remove the last play thing). Also be sure to add this to environment variable Path, not somewhere else


text:
Q: Error Message: It looks like you are missing some dependencies you need to get Electron running After globally installing electron-forge with npm install -g electron-forge any command I enter in the terminal related to electron-forge gives me the following message:

It seems like it's missing some dependencies you need to run Electron.
  Make sure you have git and Node.js version 6.0.0+ installed

I don't know why it tells me that it is missing git and Node which both installed both locally and globally versions 0.1.5 and 14.0.0 respectively.

A: git 0.1.5 is a partial implementation of access to git object database; for other not implemented things it requires native git command line.


text:
Q: For real numbers $a,b,c$ calculate the value of: $\frac{c}{a+b}+\frac{a}{b+c}+\frac{b}{c+a}$ if we have... For real numbers $a,b,c$ we have: $a+b+c=11$ and  $\frac1{a+b}+\frac1{b+c}+\frac1{c+a}=\frac{13}{17}$, calculate the value of: $\frac{c}{a+b}+\frac{a}{b+c}+\frac{b}{c+a}$
I think we should use a trick to solve this,because doing algebraic operations on this problem are too tedius!

A: $\frac{c}{a+b} +\frac{a}{b+c}+\frac{b}{c+a}=\frac{11-a-b}{a+b}+\frac{11-b-c}{b+c}+\frac{11-a-c}{c+a}
=(11\cdot \frac{13}{17})-3=\frac{92}{17}$

A: $$\frac{a}{b+c}+\frac{b}{a+c}+\frac{c}{a+b}=\frac{a+b+c}{b+c}+\frac{a+b+c}{a+c}+\frac{a+b+c}{a+b}-3=$$
$$=(a+b+c)\left(\frac{1}{a+b}+\frac{1}{b+c}+\frac{1}{a+c} \right)-3=$$
$$=11\cdot\frac{13}{17}-3=\frac{92}{17}$$

A: Hint:
As $(a+b+c) ( \frac1{a+b}+\frac1{b+c}+\frac1{c+a})= 3+\frac{a}{b+c} +\frac{b}{c+a} + \frac{c}{a+b}$

Now applying the values given in question we get $\frac{a}{b+c} +\frac{b}{c+a} + \frac{c}{a+b}=(11 \cdot \frac{13}{17})- 3=\frac{92}{17}$


text:
Q: Terminate .NET remoting async service call from client side There is a .NET remoting service that usually takes a longer time. When a client makes an async request to the service and when client times out, I need to terminate the execution of server call. How do I do it ?
Current service mode: Singleton

A: I think there isn't a way, unless you can abort the TCP channel. Best to use an async delegate and abort that.


text:
Q: Interact with shell python from another python So my issue is the following:
I am using a version of python with my main libraries, to do something I need to interface with a program's python libraries. That program comes with a .bat file that sets up the variables and start python.
What I want to do from my main python is the following:

*

*call the .bat file

*From the python session created import my custom function

*Send inputs to me custom functions (nested lists of strings mostly)

*Stop the new python instance once the data is processed

How can such a thing be done from python? Should I anchor myself to the cmd prompt that is created in order to be able to send command to the new python instance? Would os or subprocess still be viable or would I need to create something like a powershell script to hand it all?
Thanks.

A: So I think I found a way to solve this as it appears that the subprocess is continuous it was quite straightforward.
Here is the code I used:
import subprocess as sb
from time import sleep

bat_file="C:\\...\\python_env.bat"

def executor(commands:list,mode=0):
    #initiate the process with the batch file
    proc=sb.Popen(bat_file, shell=False, stdin=sb.PIPE, stdout=sb.PIPE, stderr=sb.PIPE,)
    sleep(18)#Make sure python gets initiated
    if mode==0:
        for command in commands:#send commands
            proc.stdin.write((command+'\r\n').encode(encoding='utf-8',errors='strict'))
        outp=proc.communicate('print("done") \r\n'.encode(encoding='utf-8',errors='strict'),timeout=999999999)
    elif mode:
        commands="\r\n".join(commands)+"\r\n"
        outp=proc.communicate(commands.encode(encoding='utf-8',errors='strict'),timeout=999999999)
    #print all the console outputs
    print(outp[0].decode(encoding='utf_8', errors='strict'))
    print('done')

I used stdin.write since it was the only way to send multiple commands instead of having to restart my python process for each instance, and I have also made a mode that concatenate everything together in order to all be handled by communicate.
As an example the input of the function could be :
commands=['import numpy as np','a=np.rand(3,2,1)','print(a)']

EDIT_ important things to consider
For anyone planning to rely on this, if you plan to send string there are 2 important things to consider!

*

*You must find a way to preserve your quotation marks on each end of the string, here are the possible ways to preserve them ['"',"'",'\'',"\"","\'",'\"',"""'""",'''"''']

*Another thing that is important to consider is if you plan on using string that indicate paths or contain \ in them, add 'r' to the start of the string so the encode will interpret it as a raw string and not throw an error cause by \ and the characters surrounding it.


text:
Q: How to receive a JSON string in C? I am trying to develop a socket client program in C language that will receive a JSON string from server.
How to implement the receiving side of the JSON data?
Is the JSON string will be received as character by character in client socket side?

A: The best thing that you could is to use some JSON API like for example Jansson. You can follow this link for documentation.
Jansson API Documentation


text:
Q: Sharepoint 2013: Repeated user authentification in Outlook I've searched for this for quite a time and haven't found a solution yet, so I hope you guys can maybe help meout here.
Im running Sharepoint 2013 in our buisness enviroment and everything works fine - except synchronisation with outlook.
What I'm trying to do is: Creating a Sharepoint Contact-List and sync it with Outlook and have it open for specific users only. For this List I want to break the right-transmission, since some users should only be allowed to hae permission to this list, but not the site.
Now the List is done, right-transmission-break is done, sync is done - but i get the user-authentification-window every time I open Outlook and try to enter this list. I tried to put myself in various authorization-groups, I get the same result everytime. Only exeption here is, if I put myself as the site-colletion-administrator, which is ofc not the purpose of my goal here. Anonymus access is not what i need here btw.
Version of Outlook is 2019 and 2013.
If anyone here might have an idea to get rid of the repeated userauth.prompts, i would be happy to try them.
thanks

A: Got it fixed.
I had to edit Intranetsites in the IExplorer via GPO's. Problem here was I had my sharepoint site entry in "trusted sites" like ".domain", where it was requiered like this "*.domain" to solve my Problem. I dont know why i couldn't edit it in the trusted sites.


text:
Q: Why this C++ LinkedList statement is invalid? I'm new with C++, currently studying it for data structure. I saw this example on Pointers and I couldn't specify why it's invalid. I searched on Google but couldn't find the answer.

The question:
Are the following expressions true or false
a.  head->next == ptr1     TRUE
b.  ptr1->next->data== 46      FALSE (Why!)
c.  ptr2->next == NULL     FALSE (Why!)
d.  head->data == 12       TRUE

A:
b.  ptr1->next->data== 46      FALSE (Why!)

ptr1 points to the node whose data is 24. That node's next points to the node whose data is 34.  The node after that one is whose data is 46.  So, ptr1->next->next->data == 46 would be TRUE instead.

c.  ptr2->next == NULL     FALSE (Why!)

ptr2 points to the node whose data is 63.  That node's next is not NULL, it points to the node whose data is 75.  That node's next is NULL.  So, ptr2->next->next == NULL would be TRUE instead.


text:
Q: inheritance in objective C i am new to objective C.is it possible multiple ,multilevel,hybrid,hierarchical,all types of inheritance in objective C?
(Translation:  What kind of inheritance does Objective-C support?)

A: No multiple inheritance of implementation in Objective C. As an alternative, consider categories.  Not sure what you mean by multilevel, hybrid or hierarchical in this context. What are your actual NEEDS, as opposed to, a bunch of buzzwords...?-)

A: No.  Objective-C supports single inheritance.
You can declare multiple inheritance intentions through protocols, but you'll need to provide implementations per conforming class.
Categories allow for the extension of an existing class, but do not allow for the extension of multiple classes simultaneously.
I would suggest that you start here:
Introduction to The Objective-C 2.0 Programming Language


text:
Q: undefined symbol: lua_rotate I had done below steps,
downloaded lua-cjson-2.1.0.7 from this repo, Not really know what went wrong. can anybody know whats going on and how to resolve this?
make install
mkdir -p /usr/local/lib/lua/5.1
rm -f /usr/local/lib/lua/5.1/cjson.so
cp cjson.so /usr/local/lib/lua/5.1
chmod 755 /usr/local/lib/lua/5.1/cjson.so

Then,
sudo systemctl restart nginx.service

Error:
2020/02/19 06:59:52 [error] 29524#29524: *1 lua entry thread aborted: runtime error: error loading module 'cjson' from file '/usr/local/lib/lua/5.1/cjson.so':
        /usr/local/lib/lua/5.1/cjson.so: undefined symbol: lua_rotate
stack traceback:
coroutine 0:
        [C]: in function 'require'

nginx.conf has below :
lua_package_path "/usr/local/lib/lua/?.lua;;";
And
/usr/bin/lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio


text:
Q: .NET 6 - Pass JSON in query string I use .NET 6, and I want to use HttpClient.GetAsync to send a query.
One of the arguments is JSON, and I do not know how to encode it correctly.
Here is the documentation I use:
https://docs.datadoghq.com/api/latest/metrics/#query-timeseries-points
I have tried with this method, but I got a BAD REQUEST from the server
    public async Task<string> MetricAggregateAsync(string from, string to, string query)
    {
        AddDDApiKey();
        AddDDApplicationKey();

        //var content = new StringContent(json, Encoding.UTF8, "application/json");
        //System.Web.Helpers.Json.Encore(query);

        query = System.Web.HttpUtility.UrlEncode(query);

        string content = "?from=" + from +"&to=" + to + "&query=" + query;

        HttpResponseMessage response = await _httpClient.GetAsync("v1/query" + content);

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadAsStringAsync();
    }

A: From the documentation you shared (thanks for that!) it seems like this GET /query endpoint does not expect a JSON content at all. Try this version of your code:
public async Task<string> MetricAggregateAsync(string from, string to, string query)
{
    AddDDApiKey();
    AddDDApplicationKey();

    query = System.Web.HttpUtility.UrlEncode(query);

    string url = $"v1/query?from={from}&to={to}&query={query}";

    HttpResponseMessage response = await _httpClient.GetAsync(url);

    response.EnsureSuccessStatusCode();

    return await response.Content.ReadAsStringAsync();
}

By the way, there are some tricks you could employ:

*

*You could remove those
AddDDApiKey()
AddDDApplicationKey()

calls in MetricAggregateAsync (and all other methods that consume this API) if you configured your _httpClient to include some headers in all requests it sends, e.g.:
_httpClient.DefaultRequestHeaders.Add("DD-API-KEY", "TODO");
_httpClient.DefaultRequestHeaders.Add("DD-APPLICATION-KEY", "TODO");

This should be done in the same place where that _httpClient is instantiated (not in MetricAggregateAsync).

*A safer way to build URL strings would be to replace
query = System.Web.HttpUtility.UrlEncode(query);

string url = $"v1/query?from={from}&to={to}&query={query}";

with
var urlParameters = System.Web.HttpUtility.ParseQueryString(""); // Strange way to start, but please bear with it :)
urlParameters.Add("from",  from);
urlParameters.Add("to",    to);
urlParameters.Add("query", query); // Automatically encodes URL, so you don't have to do it manually

string url = $"v1/query?{urlParameters}";


text:
Q: Tradingview Pine-Script: how to use show_last with if im frustraed I try to make a simple indicator for each timframe and I did it only that in inputs something like this and I must reduce them with conditional if
I want the show last as the offset to change at different times 4h 2h 1h 30m 15m but the code is long because I have several this is a simple code it works normally if the conditional if but when I put the if so that the condition changes value no change

a = 0
b = 0
if  timeframe.period =="240"
    a:= 30
    b:= 30
//
if timeframe.period =="120"
    a:= 60
    b:= 60

bgcolor( showSemanal2 and isTue2()  ? semanalcolor : na, title="inicio semanal color", show_last = b, offset = a)

bgcolor( showSemanal2 and isTue2()  ? semanalcolor : na, title="inicio semanal color" , show_last = b )

bgcolor( showSemanal and isTue2() ? semanalcolor : na)```

I expected it to change in each timeframe but it didn't work out I hope you can help me

A: show_last only takes input integer, which means a constant. Here is a possible work around.
var show30 = timeframe.period=="240"
var show60 = timefram.period=="120"

bgcolor( showSemanal2 and isTue2() and show30  ? semanalcolor : na, title="inicio semanal color", show_last = 30, offset = 30)
bgcolor( showSemanal2 and isTue2() and show30 ? semanalcolor : na, title="inicio semanal color" , show_last = 30)

bgcolor( showSemanal2 and isTue2() and show60  ? semanalcolor : na, title="inicio semanal color", show_last = 60, offset = 60)
bgcolor( showSemanal2 and isTue2() and show60 ? semanalcolor : na, title="inicio semanal color" , show_last = 60 ) ```


text:
Q: Public fixed-length Strings I am just summarizing info about implementing a digital tree (Trie) in VBA. I am not asking how to do that so please do not post your solutions - my specific question regarding fixed-length Strings in class modules comes at the end of this post.
A Trie is all about efficiency and performance therefore most of other programming languages use a Char data type to represent members of TrieNodes. Since VBA does not have a Char datatype I was thinking about faking it and using a fixed-length String with 1 character.

*

*Note: I can come up with a work-around to this ie. use Byte and a simple function to convert between Chr() and Asc() or an Enum, or delcare as a private str as String * 1 and take advantage of get/let properties but that's not the point. Stay tuned though because...

According to Public Statement on Microsoft Help Page you can't declare a fixed-length String variable in class modules.

I can't find any reasonable explanation for this constrain.
Can anyone give some insight why such a restriction applies to fixed-length Strings in class modules in VBA?

A: The VBA/VB6 runtime is heavily reliant on the COM system (oleaut32 et al) and this enforces some rules.
You can export a class flile between VB "stuff" but if you publish (or could theoretically publish) it as a COM object it must be able to describe a "fixed length string" in its interface description/type library so that say a C++ client can consume it.
A fixed length string is "special" because it has active behaviour, i.e. its not a dumb datatype, it behaves somewhat like a class; for example its always padded - if you assign to it it will have trailing spaces, in VBA the compiler adds generated code to get that behaviour. A C++ consumer would be unaware of the fixed-length nature of the string because the interface cant describe it/does not support a corresponding type (a String is a BSTR) which could lead to problems.
Strings are of type BSTR and like a byte array you would still lose the padding semantics if you used one of those instead.


text:
Q: How to create ipa in xcode 6 without Apple Developer account? Need to generate .ipa file for Ad-Hoc distribution. Client has provided only certificates, private keys and provisioning profiles which were enough to create .ipa till Xcode 5. But in Xcode 6.1 when I export as Save For Ad Hoc Deployment it gives message
To save for Ad Hoc Deployment, you need to add an Apple ID account that is enrolled in the iOS Developer Program for the development team 'xxxxxxxxxx'

Is there any way of creating .ipa without developer account credentials?

A: Finally found a way for creating .ipa build with xcodebuild command.

*

*Right click on Archive on Organizer.

*Click Show in Finder.

*You can see .xcarchive file in Finder.

*Open Terminal and cd to .xcarchive path.

*Using following command to generate .ipa file.

This will save .ipa on Desktop.
xcodebuild -exportArchive -exportFormat ipa -archivePath <FILE_NAME>.xcarchive -exportPath ~/Desktop/<FILE_NAME>.ipa

Still looking for better solution, don't know why Apple removed this feature from Xcode 6 :(

A: There are 3 WAYS to create .ipa WITHOUT Command & Apple Developer Account.
1. Fast & Best
(Works on all Xcode, All Mac OS, Bundled package can be used for OTA links like Diawi)

*

*Just build (Command+B) your app from XCode by setting proper code signing identities

*From XCode's file search at left bottom, search for .app (This will be under product directory)

*Right Click on this .app file and select Show in Finder

*Now, create directory and name it as Payload, copy .app into Payload directory.

*Archive/Compress(.zip) this Payload directory, rename file extension from .zip to .ipa

2. Extract .ipa from organizer
(Works on all Xcode, All Mac OS)

*

*Create Archive

*Go to Organizer

*Get location of Archive by Right Click and selecting Show in Finder

*Now right click on this .xcarchive file and select Show Package Contents

*Go to path Products > Applications > YourAppFile

*Open iTunes's on Mac and drag-drop this  YourAppFile from above path in Apps tab. (NOTE: Delete the previous app with the same identifier if any)

*Now right click on your app under Apps tab of iTunes and select Show in Finder, this is your .ipa file !!!

3. For devs having Xcode 5.x
(NOTE: Xcode 5.x doesn't work on El Capitan, By this way you can archive using any Xcode but you will need Xcode 5.x to create .ipa)

*

*Create Archive using any Xcode version.

*Close Xcode.

*Go to Organizer window of Xcode 5.x and from Archive tab select your archive.

*On top right section select Export, click radio button with title Save for Ad Hoc Deployment

*Click Next and Select desired code signing identities to save .ipa

A: There is even better way without doing all the command line stuff.
Select "Save For Ad Hoc Deployment" & Click Next.
Then open the "select a development team" drop down. It will have the option "Use Local singing assets" at the bottom. Select this option & Click Choose.
Here you go. The build will be created by Xcode without Apple ID Account.

A: You can also create an IPA file using Xcode 6 & latest follow below steps:

*

*Create Build File of your Project Command+B

*Go to Products folder & it will show app file right click "Show In Finder".

*Create an empty folder & call it 'Payload' then copy your app file in that folder.

*Archive Payload Folder & rename the zip file to YourApp.ipa

A: Another solution is to use Xcode 5.1.

A: From some time (for example Swift & Xcode7) when you are to make a build formula is more complicated - xcodebuild requires exportOptionsPlist parameter:
xcodebuild -exportArchive -exportOptionsPlist app.plist  -archivePath app.xcarchive -exportPath app.ipa

and app.plist contains:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
    <key>method</key>
    <string>app-store</string>
    <key>uploadSymbols</key>
    <true/>
    </dict>
</plist>


text:
Q: It throws #2025 error when moving a image in as3/flex When i tried to run the code, it throws an error:

TypeError: Error #1034: Type Coercion failed: cannot convert mx.controls::Image@a9030b1 to mx.containers.Canvas.

When i just try to replace
var num1:int = Canvas(event.currentTarget).mouseX;

with
var num1:int = Image(event.currentTarget).mouseX;

it throws below error:

ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.

Below is the code,
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="carcan();">
<mx:Script>
    <![CDATA[

            import mx.containers.Canvas;
            import mx.controls.Image;

            private var images:Array;
            private var dragInitiator:Image = new Image();
            private const IMAGE_COUNT:uint = 5;
            private var img:Image;

            private var dragInitiator:Image = new Image();

            private var points:flash.geom.Point;
            private var offset_x:int;
            private var offset_y:int;
            private var canal:Canvas;
            private var doDrag:Boolean;

            [Embed(source='cards/2C.png')]
            private var Image0:Class;

            [Embed(source='cards/2D.png')]
            private var Image1:Class;

            [Embed(source='cards/2H.png')]
            private var Image2:Class;

            [Embed(source='cards/2S.png')]
            private var Image3:Class;

            [Embed(source='cards/3C.png')]
             private var Image4:Class;

             public function carcan():void
             {
                canal = new Canvas();
                canal.setStyle("backgroundColor","blue");
                canal.x=100;
                canal.y=50;
                canal.width=500;
                canal.height=400;
                this.addChild(canal);
                init();
             }

             public function init():void
             {
              images = new Array(IMAGE_COUNT);

                 for (var i:int = 0; i < IMAGE_COUNT; i++)
                    {
                         img= new Image();
                            images[i] = this["Image" + i];
                            trace(images[i]);

                    img.x=(i*30)+50;
                    img.source=images[i];
                    img.id="Image"+i;
                    canal.addChild(img);

                     img.addEventListener(MouseEvent.MOUSE_DOWN, md);
                    img.addEventListener(MouseEvent.MOUSE_MOVE, mm);
                    img.addEventListener(MouseEvent.MOUSE_UP, mu);

                    }

             }

                public function md(event:MouseEvent):void
            {
                img = new Image();
                doDrag=true;

                canal.setChildIndex(Image(event.target), images.length-1);
                img.addEventListener(MouseEvent.MOUSE_MOVE, mm);

            }
            public function mm(event:MouseEvent):void
            {

                 if(doDrag==true)
                 {
                    points = new Point();
                images = new Array(IMAGE_COUNT);

                img = new Image();
                img = Image(event.target);

                points.x=event.target.x;
                points.y=event.target.y;
                points = localToGlobal(points);
                img.x=points.x;
                img.y=points.y;

                var boundar:flash.geom.Rectangle=new Rectangle(this.x, this.y, this.width/ 2 + 3 * offset_x, this.height / 2 + 3 * offset_x);
                img.startDrag(false, boundar);
                 }
            }

            public function onmove(event:MouseEvent):void
            {

                img = new Image();

            }

            public function mu(event:MouseEvent):void
            {
                canal = new Canvas();
                canal.stopDrag();
                doDrag=false;

                this.stopDrag();
                doDrag=false;
                var num1:int = Canvas(event.currentTarget).mouseX;

        if(num1 > 50 && num1 < 80){
             canal.setChildIndex(dragInitiator, 0);
             setCards();
            }
        if(num1 > 80 && num1 < 110){
             canal.setChildIndex(dragInitiator, 1);
            setCards();
            }
        if(num1 > 110 && num1 < 140){
             canal.setChildIndex(dragInitiator, 2);
            setCards();
            }
        if(num1 > 140 && num1 < 170){
             canal.setChildIndex(dragInitiator, 3);
            setCards();
            }
        if(num1 > 170 && num1 < 200){
            canal.setChildIndex(dragInitiator, 3);
            setCards();
            }

            }

             private function setCards():void{
            var b:int = 0;
            var a:int;
            var cardsArray:Array = this.getChildren();
            for(a = 0;a < cardsArray.length; a++)
            {
                canal.getChildAt(a).x = 90+b;
                b=b+20;
            }
             }

    ]]>
</mx:Script>
</mx:Application>

A: Instead of casting Image as a CAnvas (the first error), you need to cast it... as an Image.
import spark.components.Image;

public function mu(event:MouseEvent):void {
    var current:Image = event.currentTarget as Image; //this is the correct way to cast event.currentTarget
}

A: The two error originate from different statements:
#1034 originates from
var num1:int = Canvas(event.currentTarget).mouseX;
because an img is not a Canvas
Where #2025 originates from one of the
canal.setChildIndex(dragInitiator, ...);
because img is not a child of canal, you have to addChild(...) before you can setChildIndex(...)
you can use addChildAt instead of setChildIndex it would work the same, if not a bit less efficiently.


text:
Q: Why are PCIE's coupling capacitors so large I was looking at the PCIE specification, and I don't understand the
requirement for coupling capacitors.  For 2.5GT/s, the standard requires
AC coupling capacitors of 75nF to 265nF.  I tried to analyze the number
like in this article in
High-Speed Digital Design Online Newsletter.  The line is terminated at
both ends, the capacitor faces 100Ω, the RC time constant is 7.5µs to
26.5µs, or 19000 to 66000 bit intervals.  Since we're using 8b/10b
encoding and there are at most 3 ones or zeros in a row, the RC time
constant only needs to be large compared with 3 bit intervals, so the
capacitance should only need to be large compared with 12pF.  The
requirement of at least 75nF seems unnecessarily large.  Why is that?
If the capacitance were allowed to be around 100pF, the capacitors can
even be made into the chip.
The requirement for coupling capacitors can be found
here,
page 357, section 4.3.13.

A: The larger AC coupling value passes the low-speed 'ping' pulses used for sensing the presence of a link partner. The TX PHY sends the pulses, then watches the signal using the known R-C time constant to detect an open or terminated line.
Here's an excerpt from an article describing this:
"Receiver detection: PCIe uses an ingenious means to recognize both the presence of a physical link and channel width. The specification exploits the fact that an un-terminated, ac-coupled transmission line will have a very different charge time when the line is terminated versus open. Each PCIe transmitter, at the commencement of linkup, produces a low-frequency "ping" on each of the differential TX outputs. The transmitter includes a simple detection circuit to monitor the line response to this ping. With no receiver attached, the edge rate (and amplitude) of the line change is much higher than when a receiver is present. Because the specification has a defined range of coupling capacitance and the receiver termination, a distinct, detectable time constant range defines when a receiver is present or not."
From here: https://www.electronicdesign.com/technologies/communications/article/21762833/pci-express-and-the-physical-journey-to-gen-3
Once the link partners have found their connections, then the 8b/10b linkup and training process begins.


text:
Q: Could not refresh state. Known issue, and known workaround is not working So, if you have been working for some time with Terraform, probably you have faced this error message more than once:
Initializing the backend...

Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Error refreshing state: state data in S3 does not have the expected content.

This may be caused by unusually long delays in S3 processing a previous state
update.  Please wait for a minute or two and try again. If this problem
persists, and neither S3 nor DynamoDB are experiencing an outage, you may need
to manually verify the remote state and update the Digest value stored in the
DynamoDB table to the following value:

Usually, this is caused because something was screwed up during a destroy operation, and now there is a mismatch between the state and the lock.
The known solution for this is to delete the lock from DynamoDB and run terraform init again. And if it didn't resolve with that, also delete the tfstate from S3, which at this point doesn't have any data as the infrastructure was destroyed.
Surprisingly, neither is working now, and I don't have a clue why. There is no tfstate in the bucket, in fact, I even deleted every old version stored (bucket has versioning enabled). There is no lock in DynamoDB either.
Changing the tfstate name works without issues, but I can't change it as it would break the naming convention I'm using for all my tfstates.
So, any ideas what's going on here? On Friday, the infrastructure was deployed and destroyed without issues (as part of the destroy, I always check there is no lock left behind and delete the tfstate from S3). But today, I'm facing this error, and it's been a while already and can't figure it out..

A: Holy ****!
So, it turns out DynamoDB was being a serious troll here.
I searched for the key of the md5 of this tfstate, and it wasn't returned. But then I noticed there was a message about that there were more items to be returned... After clicking like 6 times on that button, it eventually returned a hidden lock for this tfstate.
Deleted it, and everything is back to normal again.
So, as summary, if you ever face this issue and you can't find the lock on DynamoDB... be sure that all items are returned in the query, as it can take many attempts to return them all.


text:
Q: Detected a TLS handshake to an endpoint that does not have TLS enabled I have an ASP.NET Core Web API running in a Linux Docker container orchestrated using Docker compose. When I try to access the Swagger endpoint of the Web API on HTTPS, the browser cannot reach the endpoint, and I see the following error in the Web API logs.

Detected a TLS handshake to an endpoint that does not have TLS enabled

After reading this topic, I "fixed" the issue by adding the following to my configuration. However, I am not sure why this is needed. It seems overkill and has too much complexity to enable HTTPS, so I am wondering if I am missing something.
builder.WebHost.ConfigureKestrel(options =>
{
    options.Listen(
        address: IPAddress.Any,
        port: 443,
        configure: listenOptions =>
        {
            listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
            listenOptions.UseHttps(new TlsHandshakeCallbackOptions
            {
                OnConnection = context =>
                {
                    if (string.Equals(context.ClientHelloInfo.ServerName, "localhost", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(context.ClientHelloInfo.ServerName, "host.docker.internal", StringComparison.OrdinalIgnoreCase))
                    {
                        // Different TLS requirements for this host
                        context.AllowDelayedClientCertificateNegotation = true;

                        return new ValueTask<SslServerAuthenticationOptions>(
                            new SslServerAuthenticationOptions
                            {
                                ServerCertificate = new X509Certificate2("/root/.aspnet/https/webapi.pfx", "password")
                            });
                    }

                    return new ValueTask<SslServerAuthenticationOptions>(
                        new SslServerAuthenticationOptions
                        {
                            ServerCertificate = new X509Certificate2("/root/.aspnet/https/webapi.pfx", "password")
                        });
                }
            });
        });
});


text:
Q: Proof involving Gamma distribution X has Gamma(r, λ) distribution. Prove that Y=λX has Gamma(r,1) distribution.
I thought that you might be able to merely substitute the pdf for a Gamma(r, λ) distribution and then multiply that by lambda to then compare that to the pdf of a Gamma(r, 1) distribution. However this did not work. Any hints are greatly appreciated!

A: You need to use the rule for change of variables, which for $Y=g(X)$, the density function of $Y$, denoted by $f(y)$ is
$$f(y)=f(x)\left|\frac{dX}{dY}\right|=f(g^{-1}(y))\left|\frac{dX}{dY}\right|$$
where $g^{-1}(y)$ denotes the inverse function.
So for $$f(x)=\Gamma(r,\lambda)=\frac{\lambda^r}{\Gamma(r)}x^{r-1}e^{-\lambda x}$$ and $Y=\lambda X$ you have
$$f(y)=\frac{\lambda^r}{\Gamma(r)}\left(\frac{y}{\lambda}\right)^{r-1}e^{-\lambda \frac{y}{\lambda}}\times\frac{1}{\lambda}=\frac{1}{\Gamma(r)}y^{r-1}e^{-y}=\Gamma(r,1)$$


text:
Q: Confused between QSQLITE and SQLITE I'm a creating a music library manager on Qt. I'm confused whether I should use Qt's driver for SQLITE(QSqlite) or raw SQLITE that I just grabbed from their website. I'll need to create .dll from the raw code though. But if I use Qt's native library, I believe I'll have to install the drivers inorder to use the app on a different system.
I'm a newbie to both Qt and SQLITE. Any kind of help/advise would be awesome :)
Thanks!

A: I highly recommend you to use the QSQLITE driver.

*

*It is part of Qt SQL module which provides support for SQL databases in a really "Qtish" way. You'll save a lot of time and effort.

*There's no need for additional installation. You just have to include the driver (sqldrivers/qsqlite.dll) in your deploy folder. After all, if you don't pay for a comercial license, when you deploy a Qt application you'll have to carry with several dynamic libraries. I don't think just one more will make a difference.


text:
Q: Libgdx draws objects black instead of colored I have a starfield for a side scroller game. The stars are moving from right to left. There are three different types of stars fast, normal and slow simulating a parallax effect. Depending on their type they have different colors and speeds.
It works fine so far but the stars remain black.
The code of the starfield:
public class Starfield extends AbstractGameObject {

    public static final String TAG = Starfield.class.getName();
    private Array<Star> stars;

    public enum STAR_TYPE {
        FAST(255, 255, 255),
        NORMAL(190, 190, 190),
        SLOW(120, 120, 120);

        private int color;

        private STAR_TYPE(int r, int g, int b) {
            int R = r << 24;
            int G = g << 16;
            int B = b << 8;
            color = R | G | B | 0xff;
            //color = r << 24 | g << 16 | b << 8 | 0xff;
        }

        public static STAR_TYPE getRandomType() {
            return values()[MathUtils.random(0, values().length - 1)];
        }

        public int getColor() {
            return color;
        }
    }

    public Starfield() {
        init();
    }

    private void init() {
        stars = new Array<Star>();

        for(int i = 1; i <= Constants.COUNT_STARS; i++){
                stars.add(new Star());
        }
    }

    @Override
    public void update(float deltaTime) {
        super.update(deltaTime);

        for(Star star : stars){
            star.update(deltaTime);
        }
    }

    @Override
    public void render(SpriteBatch batch) {
        for (Star star : stars)
            star.render(batch);
    }

    public class Star extends AbstractGameObject {

        private STAR_TYPE starType;
        private Texture texStar;

        public Star() {
            init();
        }

        private void init() {
            Pixmap pixmap;

            position.set(MathUtils.random() * Constants.WORLD_WIDTH, MathUtils.random() * Constants.WORLD_HEIGHT);
            dimension.set(0.02f, 0.02f);

            starType = STAR_TYPE.getRandomType();

            pixmap = new Pixmap((int) dimension.x, (int) dimension.y, Pixmap.Format.RGBA8888);
            pixmap.setColor(starType.getColor());
            pixmap.fill();
            texStar = new Texture(pixmap);

            switch (starType) {
                case FAST:
                    velocity.set(-0.5f, 0);
                    break;
                case NORMAL:
                    velocity.set(-0.2f, 0);
                    break;
                case SLOW:
                    velocity.set(-0.1f, 0);
                    break;
            }
        }

        @Override
        public void update(float deltaTime) {
            super.update(deltaTime);

            if(position.x <= 0)
                position.x = Constants.WORLD_WIDTH;
        }

        @Override
        public void render(SpriteBatch batch) {
            batch.draw(texStar, position.x, position.y, dimension.x, dimension.y);
        }
    }
}

I was wondering if the bit shift works properly but it does. Then I changed the color manually to something like pixmap.setColor(1, 0, 0, 1);. The Stars remained black. I debuged the render method and looked into texStar. The pixmap is saved correctly including the previously selected color (I can rule out the possibility that I override the color in other parts of my code). I suspected the draw method to be wrong and used batch.draw(texStar, position.x, position.y); instead. But then all stars disappeared for some reason. I don't understand why because the texture should have the dimension of the pixmap (0.02f). The overall render method renderWorld looks like this:
private void renderWorld (SpriteBatch batch) {
        worldController.camerHelper.applyTo(camera);
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(texBorder, 0, 0);
        worldController.starfield.render(batch);
        batch.end();
    }

Btw, the texBorder Texture consisting of couple of colored rectangles is drawn just fine. Any thoughts what the reason for this behaviour could be?

A: The issue was this line:
pixmap = new Pixmap((int) dimension.x, (int) dimension.y, Pixmap.Format.RGBA8888);

The dimension of a pixmap is an integer. dimension.x and dimension.y are way smaller than 1. So after casting they are 0. Changing dimensions to 1 makes the stars colorful.